如何在python中使用matplotlib绘制叠加的条形图?
问题内容:
我想使用matplotlib绘制条形图或直方图。我不需要堆积的条形图,而是两个数据列表的叠加条形图,例如,我有以下两个数据列表:
一些代码开头:
import matplotlib.pyplot as plt
from numpy.random import normal, uniform
highPower = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,1419.34,
1415.13,1182.70,1165.17]
lowPower = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,1138.70,
1104.12,1012.95,1000.36]
plt.hist(highPower, bins=10, histtype='stepfilled', normed=True,
color='b', label='Max Power in mW')
plt.hist(lowPower, bins=10, histtype='stepfilled', normed=True,
color='r', alpha=0.5, label='Min Power in mW')
我想针对这两个列表中的值数量绘制这两个列表,以便能够看到每次读数的变化。
问题答案:
可以产生使用叠加条形图plt.bar()
与alpha
如下所示的关键字。
该alpha
控制杆的透明度。
注意, 当您有两个重叠的条,其中一个条的alpha
<1时,您会得到多种颜色。这样,即使图例将其显示为浅红色,该条也会显示为紫色。为了减轻这种情况,我修改了其中一个条的宽度,这样即使您更改了功率,仍然可以看到两个条。
plt.xticks
可用于设置图形中x标记的位置和格式。
import matplotlib.pyplot as plt
import numpy as np
width = 0.8
highPower = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,
1419.34,1415.13,1182.70,1165.17]
lowPower = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,
1138.70,1104.12,1012.95,1000.36]
indices = np.arange(len(highPower))
plt.bar(indices, highPower, width=width,
color='b', label='Max Power in mW')
plt.bar([i+0.25*width for i in indices], lowPower,
width=0.5*width, color='r', alpha=0.5, label='Min Power in mW')
plt.xticks(indices+width/2.,
['T{}'.format(i) for i in range(len(highPower))] )
plt.legend()
plt.show()