python - 如何使用 Matplotlib 制作逐行饼图?
问题描述
我的数据框看起来像 -
state value1 value2 value3
a 20 65 15
b 35 35 30
c 30 25 45
我想要每个州的饼图(可能存在 20 个州)。我的代码如下 -
对于饼图 -
for ind in df.index:
fig, ax = plt.subplots(1,1)
fig.set_size_inches(5,5)
df.iloc[ind].plot(kind='pie', ax=ax, autopct='%1.1f%%')
ax.set_ylabel('')
ax.set_xlabel('')
但它不起作用。
解决方案
也许你应该:
- 将状态列设置为索引。
- 创建具有足够Axes对象的单个图形(在我的示例中,我将所有这些对象放在一个列中。
- 然后在相应的Axes对象中创建每个图。
就像是:
n = df.index.size
fig, axs = plt.subplots(n, 1, figsize=(5, 3 * n))
for i in range(n):
df.iloc[i].plot(kind='pie', ax=axs[i], autopct='%1.1f%%')
对于您的数据样本,我得到:
当然,您可以进一步自定义特定参数,尤其是状态名称的可见性要被纠正。
或者,如果您想将绘图排列在 3 列中,请运行:
n = df.index.size; i = 0
nRows = math.ceil(n / 3)
fig, axs = plt.subplots(nRows, 3, figsize=(14, 4 * nRows))
for ax in axs.flat:
if i < n:
df.iloc[i].plot(kind='pie', ax=ax, autopct='%1.1f%%')
else:
ax.set_visible(False)
i += 1
推荐阅读
- javascript - 在 React 和 TypeScript 中扩展 HTML标签元素
- git - Git中引用名的字母排序,它是如何工作的?
- c++ - 如何将字符串转换为给定精度的双精度?
- java - 使用 ORMLite 时出现死锁
- linux - 使用 xpack 安装 Elasticsearch 失败
- c - 新定义数据类型的 n 个指针的内存分配
- django - 如何将额外的上下文传递给 Django Rest Framework 序列化程序
- firefox - 使用 Firefox 访问 USB 设备
- java - 如何为客户提供自定义密码规则设置机制?
- c++ - 将一个向量元素和第二个向量复制到第三个向量中并避免重复