[英]matplotlib: assigning different hatch to bars
我有一个数据框,其中每个索引都必须绘制两个条形图(对于两个系列)。 以下代码将输出显示为:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax = df.sort_values('B', ascending=True).plot.barh(rot=0,ax=ax,hatch="/")
plt.show()
我想为每个栏分配单独的阴影。 这样,如果A
带有'/'阴影,则B
应该带有'|'。 我需要对代码进行哪些修改?
您可以分别绘制两个条形图:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame(np.random.randint(0, 20, size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax.barh(np.arange(0, len(df)), df['A'], height=0.3, hatch='/')
ax.barh(np.arange(0.3, len(df) + 0.3), df['B'], height=0.3, hatch='|')
matplotlib文档提供了一个解决方案。 但是我真的不喜欢它,因为它的目的是为每个栏设置不同的阴影。
但是在大多数情况下,恕我直言,为每个“类别”栏设置一个特定的填充更为重要。 您可以通过用阴影线单独绘制条形来完成此操作,也可以在绘制后设置阴影线。 绘制后设置剖面线是非常灵活的,因此这是我的方法:
df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax = df.sort_values('B', ascending=True).plot.barh(rot=0,ax=ax)
# get all bars in the plot
bars = ax.patches
patterns = ['/', '|'] # set hatch patterns in the correct order
hatches = [] # list for hatches in the order of the bars
for h in patterns: # loop over patterns to create bar-ordered hatches
for i in range(int(len(bars) / len(patterns))):
hatches.append(h)
for bar, hatch in zip(bars, hatches): # loop over bars and hatches to set hatches in correct order
bar.set_hatch(hatch)
# generate legend. this is important to set explicitly, otherwise no hatches will be shown!
ax.legend()
plt.show()
与单独绘制条形图相比,此解决方案的优势在于:
主要缺点是附加的LOC,尤其是仅绘制少量条形图时。 但是将其打包到功能/模块中并重新使用可以解决此问题。 :)
这是一个可以帮助您的测试ca
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
plt.hist(df['A'], color = 'blue',
edgecolor = 'red', hatch = '/' , label = 'df.A',orientation = 'horizontal',
histtype = 'bar')
plt.hist(df['B'],color = 'YELLOW',
edgecolor = 'GREEN', hatch = 'O' , label = 'df.B',orientation = 'horizontal',
histtype = 'bar')
plt.legend()
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.