Saa*_*adH 5 python numpy matplotlib pandas
我有一个数据框,对于每个索引,我必须绘制两个条形图(两个系列)。以下代码给出的输出为:
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()
Run Code Online (Sandbox Code Playgroud)
我想为每个条形分配单独的孵化。这样如果A有'/'阴影,B应该有'|'。我需要在代码中进行哪些修改?
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()
Run Code Online (Sandbox Code Playgroud)
与单独绘制条形图相比,该解决方案的优点是:
主要缺点是额外的 LOC,特别是仅绘制几个条形图时。但是将其打包到函数/模块中并重新使用它可以解决这个问题。:)
您可以分别绘制两个条形图:
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='|')
Run Code Online (Sandbox Code Playgroud)