繁体   English   中英

如何 plot a matplotlib (pandas) bar plot using colors and hatches?

[英]How to plot a matplotlib (pandas) bar plot using colors and hatches?

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

#!/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()

使用此代码,Hatches 将完全应用于所有条形图。

影线完全应用于所有钢筋。 相反,我宁愿让每个数据集都使用自己的影线颜色组合。

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

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

手动设置影线到补丁:

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

在组合 plot 中将舱口应用于不同数据集的正确方法是什么?

您可以 plot 每个系列单独:

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

结果图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM