【问题标题】:Matplotlib: how to plot the difference of two histograms?Matplotlib:如何绘制两个直方图的差异?
【发布时间】:2018-03-08 23:42:59
【问题描述】:

假设您有以下数据集:

a=[1, 2, 8, 9, 5, 6, 8, 5, 8, 7, 9, 3, 4, 8, 9, 5, 6, 8, 5, 8, 7, 9, 10]
b=[1, 8, 4, 1, 2, 4, 2, 3, 1, 4, 2, 5, 9, 8, 6, 4, 7, 6, 1, 2, 2, 3, 10]

并说你制作了他们的直方图:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1,2,figsize=(16, 8))

plt.subplot(121)
plot1=plt.hist(a, bins=[0,1,2,3,4,5,6,7,8,9,10],
normed=True,edgecolor='k',linewidth=1.0,color='blue')
plt.title("a")

plt.subplot(122)
plot2=plt.hist(b, bins=[0,1,2,3,4,5,6,7,8,9,10],
normed=True,edgecolor='k',linewidth=1.0,color='green')
plt.title("b")

plt.show()

如何生成具有相同分箱和高度差的两个直方图之间的条形图?

如果你这样做:

 diff=plt.bar([1,2,3,4,5,6,7,8,9,10], 
             height=(plot1[0]-plot2[0]), edgecolor='black', 
             linewidth=1.2, color='red',width = 1) 
 plt.title("a-b")

x 轴上的值未与 bin 对齐。如何解决这个问题?

【问题讨论】:

  • 顺便说一句,您在上面的代码中创建了两次子图:您不需要fig, ax = plt.subplots(1, 2)plt.subplot(121)。最好使用从subplots 创建的轴:fig, (ax1, ax2) = plt.subplots(1, 2); plot1 = ax1.hist(a, bins=...); plot2 = ax2.hist(b, bins=...)

标签: python matplotlib histogram bar-chart


【解决方案1】:

好的,如果我正确理解了您的问题,则解决方案非常简单 - 如果您将差异的 bin 设置为从 0 开始,就像在前两个直方图中一样,并将对齐设置为边缘,它似乎效果很好。

diff=plt.bar([0,1,2,3,4,5,6,7,8,9], 
             height=(plot1[0]-plot2[0]), edgecolor='black', 
             linewidth=1.2, color='red',width = 1, align = 'edge') 
plt.title("a-b")
plt.show()

【讨论】:

  • 加上这个plt.xticks(list(range(0, 11))),就更清楚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 2020-03-14
  • 2018-09-08
  • 1970-01-01
  • 2011-10-15
  • 2019-03-05
相关资源
最近更新 更多