承接国内外服务器租用托管、定制开发、网站代运营、网站seo优化托管接单、网站代更新,新老站点皆可!!咨询QQ:3787320601
当前位置:首页  >  软件开发  >  python 画复合饼图

python 画复合饼图

管理员 2023-06-22 06:59:18 软件开发 15 ℃ 0 评论 1903字 收藏

python 画复合饼图

Python 是一种高级编程语言,因其易于学习和使用而备受欢迎。在 Python 中,我们可使用 matplotlib 库来创建数据可视化。在本文中,我们将介绍怎样使用 Python 和 matplotlib 库创建复合饼图来显示多个数据集的比例关系。

# 导入必要的库
import matplotlib.pyplot as plt
# 定义数据
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
# 画图
fig1, ax1 = plt.subplots()
ax1.pie(sizes, colors = colors, labels=labels, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
# 添加第二层数据
sizes_2 = [10, 40, 30, 20]
colors_2 = ['#ff99ff', '#99ccff', '#ccffcc', '#ffccff']
w, h = ax1.get_width(), ax1.get_height()
ax2 = ax1.twiny()
ax2.pie(sizes_2, colors=colors_2, startangle=270, radius=0.7*w, autopct='%1.1f%%')
ax2.axis('equal')
# 添加图例
plt.legend(loc='upper right', bbox_to_anchor=(1.5, 1))
# 显示图形
plt.show()

我们首先导入了必要的库,然后定义了两个数据集 sizes 和 sizes_2,和与其对应的标签 labels 和色彩集 colors。接着,我们使用 plt.subplots() 创建了一个图形,然后在该图形上创建了第一层饼图。另外,我们调用了 autopct='%1.1f%%' 参数,以在图形中显示数据百分比。

接下来,我们使用 ax1.get_width() 和 ax1.get_height() 获得第一层饼图的宽度和高度,并创建了一个具有相同宽度和高度的第二层饼图。我们还通过将 radius 设为原始饼图的 0.7 倍,使第二层饼图缩小了一些。最后我们将第二个饼图的开始角度设置为 270 度,以取得我们想要的位置和角度。

最后我们使用 plt.legend() 向图形添加图例,并使用 plt.show() 将图形显示出来。现在,您已掌握了怎样使用 Python 和 matplotlib 库创建复合饼图!

文章来源:丸子建站

文章标题:python 画复合饼图

https://www.wanzijz.com/view/58094.html

TAG: css python

相关文章

Related articles

X

截屏,微信识别二维码

微信号:weimawl

(点击微信号复制,添加好友)

打开微信