Vertical Histogram in Python and Matplotlib

会有一股神秘感。 提交于 2019-12-22 03:51:11

问题


How can I make a vertical histogram. Is there any option for that or should it be built from the scratch? What I want is the upper graph to look like the below one but on vertical axis!

from matplotlib import pyplot as plt
import numpy as np
sample=np.random.normal(size=10000)
vert_hist=np.histogram(sample,bins=30)
ax1=plt.subplot(2,1,1)
ax1.plot(vert_hist[0],vert_hist[1][:-1],'*g')

ax2=plt.subplot(2,1,2)
ax2.hist(sample,bins=30)
plt.show()


回答1:


Use orientation="horizontal" in ax.hist:

from matplotlib import pyplot as plt
import numpy as np

sample = np.random.normal(size=10000)

vert_hist = np.histogram(sample, bins=30)
ax1 = plt.subplot(2, 1, 1)
ax1.plot(vert_hist[0], vert_hist[1][:-1], '*g')

ax2 = plt.subplot(2, 1, 2)
ax2.hist(sample, bins=30, orientation="horizontal");
plt.show()




回答2:


Just use barh() for the plot:

import math
from matplotlib import pyplot as plt
import numpy as np
sample=np.random.normal(size=10000)
vert_hist=np.histogram(sample,bins=30)

# Compute height of plot.
height = math.ceil(max(vert_hist[1])) - math.floor(min(vert_hist[1]))

# Compute height of each horizontal bar.
height = height/len(vert_hist[0])

ax1=plt.subplot(2,1,1)
ax1.barh(vert_hist[1][:-1],vert_hist[0], height=height)

ax2=plt.subplot(2,1,2)
ax2.hist(sample,bins=30)
plt.show()




回答3:


i used ax[1] as the subplot

f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})

The following code rotates the histogram 90 degrees clockwise. it also plots a fitted curve for the bins The key arg is orientation=u'horizontal'

ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1, orientation=u'horizontal') 

# Fit a normal distribution to the data:
mu, std = norm.fit(data)

# Plot the PDF.
xmin = min(data)
xmax = max(data)

x = np.linspace(xmin, xmax, 10000)
p = norm.pdf(x, mu, std)

base = plt.gca().transData
rot = transforms.Affine2D().rotate_deg(-90)  # rotate the histogram line 90 degress clockwise

ax[1].plot(-x, p,  'r',linewidth=2, transform = rot+base)  # use -x for the reverse y-axis plotting


来源:https://stackoverflow.com/questions/22333568/vertical-histogram-in-python-and-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!