python - 如何在matplotlib的嵌套饼图中将值放在外部饼图中
问题描述
数据:
import numpy as np
import matplotlib.pyplot as plt
labels=['Cat','Dog','Human','Rabbit']
data1=[35,80,2,20]
data2=[5,3,80,8]
我正在使用上述数据绘制嵌套饼图:
size=0.3
fig,ax=plt.subplots(figsize=(20,10))
cmap=plt.get_cmap('tab20c')
outer_colors=cmap(np.arange(0,3)*5)
inner_colors=cmap(np.arange(0,3)*5)
ax.pie(x=data1,autopct='%.2f%%',shadow=True,startangle=180,radius=1,wedgeprops={'width':size,'edgecolor':'c'},colors=outer_colors)
ax.pie(x=data2,autopct='%.2f%%',shadow=True,startangle=180,radius=0.5,wedgeprops={'width':size,'edgecolor':'c'},colors=inner_colors)
plt.title('Good vs Bad Pets',fontsize=18,weight='bold')
plt.legend(labels,fontsize=15)
plt.show()
上述代码的输出:
我的问题是:
从上图中我们可以看到,在内部饼图中,值(%)也在图中,但它不在外部图中。
那么我该怎么做呢?
预期输出:
解决方案
您要查找的参数是pctdistance
. 如pie
文档所述,默认值为0.6
. size=0.3
因为您有一个和的外环radius=1
,所以这会导致标签被放置在内部区域中。此处的示例通过指定将标签居中在外环的中心pctdistance
。
size=0.3
fig, ax = plt.subplots(figsize=(20,10))
cmap = plt.get_cmap('tab20c')
outer_colors = cmap(np.arange(0,3)*5)
inner_colors = cmap(np.arange(0,3)*5)
wedges, text, autopct=ax.pie(x=data1, autopct='%.2f%%', shadow=True,
startangle=180, radius=1,
wedgeprops={'width':size, 'edgecolor':'c'},
colors=outer_colors, pctdistance=(1-size/2))
ax.pie(x=data2, autopct='%.2f%%', shadow=True, startangle=180, radius=0.5,
wedgeprops={'width':size, 'edgecolor':'c'}, colors=inner_colors)
plt.title('Good vs Bad Pets',fontsize=18,weight='bold')
plt.legend(labels,fontsize=15)
plt.show()
推荐阅读
- c++ - 将 compre_exchange 与 c++20 一起使用是否会比较值表示?(为什么这个例子不同意)
- css - 类是随机字符串——webpack 的东西还是 CSS 框架?
- python - 我不断收到错误“ModuleNotFoundError:我的 settings.py 文件中没有名为‘environ’的模块”。我已经在我的 python shell 中安装了依赖项
- node.js - 如何保存我的 NodeJs CLI 应用程序的配置设置?
- google-cloud-platform - 带有 pubsub 触发器主题的云功能不起作用
- swift - 匿名闭包参数不能在具有显式参数的闭包内使用
- excel - 将工作表复制到 csv 时出错 - VBA:对象“范围”的方法“值”失败(运行时错误“1004”)
- r - 使用 as.Date() 在 R 中迄今为止的字符,但给出的答案是一次又一次的相同日期
- python - tensorflow 错误:“没有注册 OpKernel 以支持 Op 'TPUReplicatedInput'”恢复模型时
- azure - Azure APIM - 如何使用 context.Request.Certificate.Verify() 验证客户端证书