Python和Matplotlib中的垂直直方图

时间:2014-03-11 18:31:09

标签: python numpy matplotlib plot histogram

如何制作垂直直方图。有什么选择,还是应该从头开始构建?我想要的是上图看起来像下面的图,但在纵轴上!

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()

enter image description here

3 个答案:

答案 0 :(得分:21)

orientation="horizontal"中使用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()

enter image description here

答案 1 :(得分:5)

只需使用barh()作为情节:

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()

enter image description here

答案 2 :(得分:0)

我使用ax [1]作为子图

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

以下代码将直方图顺时针旋转90度。它还为垃圾箱绘制了拟合曲线 关键参数arg是direction = u'horizo​​ntal'

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