pyplot hist()为每个堆叠组件分离线条样式

时间:2016-12-16 09:34:19

标签: python matplotlib

我正在尝试制作堆叠直方图,其中每个堆叠组件具有不同的线条样式和颜色。 color参数作为列表接受每个组件的颜色。但是线型参数ls没有。有没有办法分别控制每个堆叠组件的面和线型?

import numpy as np
import matplotlib.pyplot as plt

x = np.random.random(100)

# this works:
plt.hist([x,x], histtype='stepfilled', stacked=True, color=['r', 'b'])

# this does not:
plt.hist([x,x], histtype='stepfilled', stacked=True, color=['r', 'b'], ls=['-', '--'])

理想情况下,我希望完全控制每个堆叠组件的面部和边缘颜色的coloralpha。那可能吗?我尝试使用fc选项,但也不接受列表。

我还看过这个示例[1],它在ax2上显示了这种行为,但它看起来非常黑了。例如,以下代码会产生错误结果:

plt.hist([(0,1,1), (0,0,1)], histtype='step', stacked=True, fill=True)

有一种解决方法是捕捉patches并单独控制它们,就像在这个答案[2]中一样。但我想知道是否也可以直接来自plt.hist()?

[1] http://matplotlib.org/examples/statistics/histogram_demo_multihist.html

[2] https://stackoverflow.com/a/17517721/5064815

1 个答案:

答案 0 :(得分:1)

您可以cycle through the linestyles使用与循环浏览其他参数相同的方式。

import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b']) +
                           cycler('linestyle', ['-', '--', ':']) + 
                           cycler('linewidth', [4,3,1])) )

x = np.random.random(100)
plt.hist([x,x*0.8,x*0.5], histtype='stepfilled', stacked=True )

plt.show()

旁注:我目前还不知道为什么在这个例子中循环次序被逆转,即蓝色形状有一个粗实线样式。但我想这可以根据需要进行调整。