如何使用Pandas和Matplotlib绘制图案条形图?
使用Pandas绘制图案条形图,可以采取以下步骤 –
- 设置图形大小并调整子图之间和周围的填充。
-
使用Pandas创建具有两列的数据框。
-
向当前图添加一个坐标轴作为子图排列。
-
通过名称使用 kind=”bars” 类进行绘图。
-
制作一个图案列表。
-
使用 bars.patches 获取栏形捆绑。
-
迭代 bars patches并设置每个patch的填充。
-
使用 show() 方法显示图形。
例子
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
ax = plt.figure().add_subplot(111)
bars = df.plot(ax=ax, kind='bar')
hatches = ["*", "/", "o", "x"]
for patch in bars.patches:
patch.set_hatch(hatches[np.random.randint(10)%len(hatches)])
plt.show()