Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

python - How do I plot hatched bars using pandas?

I am trying to achieve differentiation by hatch pattern instead of by (just) colour. How do I do it using pandas?

It's possible in matplotlib, by passing the hatch optional argument as discussed here. I know I can also pass that option to a pandas plot, but I don't know how to tell it to use a different hatch pattern for each DataFrame column.

df = pd.DataFrame(rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='bar', hatch='/');

enter image description here

For colours, there is the colormap option described here. Is there something similar for hatching? Or can I maybe set it manually by modifying the Axes object returned by plot?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is kind of hacky but it works:

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = plt.figure(figsize=(10, 6)).add_subplot(111)
df.plot(ax=ax, kind='bar', legend=False)

bars = ax.patches
hatches = ''.join(h*len(df) for h in 'x/O.')

for bar, hatch in zip(bars, hatches):
    bar.set_hatch(hatch)

ax.legend(loc='center right', bbox_to_anchor=(1, 1), ncol=4)

bar


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...