如何使用颜色和影线绘制 matplotlib (pandas) 条形图?

Pok*_*ulo 5 python plot matplotlib pandas

如何将不同的阴影应用于我的数据,就像我可以将不同的颜色定义为元组一样?

#!/usr/bin/env python3
import pandas
from matplotlib import pyplot as plt

data = {"Label 1": [2,3,5,10], "Label 2": [1,2,4,8]}
pandas.DataFrame(data).plot.bar(color=("grey", "white"), hatch=("/", "*"))
plt.show()
Run Code Online (Sandbox Code Playgroud)

使用此代码,舱口盖适用于所有条形图。

影线一起应用于所有条形。相反,我宁愿让每个数据集使用自己的阴影颜色组合。

我知道我可以像这样手动修改图中的每个补丁:

ax = pandas.DataFrame(data).plot.bar(color=("grey", "white"), legend=False)
for container, hatch in zip(ax.containers, ("/", "*")):
    for patch in container.patches:
        patch.set_hatch(hatch)
ax.legend(loc='upper center')
plt.show()
Run Code Online (Sandbox Code Playgroud)

手动将孵化设置为补丁:

这有点hacky,但最好的解决方案,我通过这个讨论找到了。

将剖面线应用于组合图中的不同数据集的正确方法是什么?

Ale*_*lex 1

您可以单独绘制每个系列:

import pandas as pd
from matplotlib import pyplot as plt

data = pd.DataFrame({"Label 1": [2, 3, 5, 10], "Label 2": [1, 2, 4, 8]})
data['Label 1'].plot.bar(legend=True, label='Label 1', color="red", width=-0.2, align='edge', hatch='/')
data['Label 2'].plot.bar(legend=True, label='Label 2', color="green", width=0.2, align='edge', hatch='*')
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果图