本人是Python编程爱好者,享受编程的乐趣和喜欢与大家分享学习心得。

文章目录

前言

一、首先引入相关Python库

二、实例Demo

1.1 官方Demo

1.2 将实际数据应用于官方Demo

总结



前言

Matplotlib,官方提供的饼图Demo,功能比较简单,在实际应用过程中,往往会有许多个性化的绘制需求,在这里跟大家一起了解一下饼图(pie chart)的一些特色功能的实现。

一、首先引入相关Python库

from matplotlib import font_manager as fm
import matplotlib as mpl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt%matplotlib inline
plt.style.use('ggplot')

二、实例Demo

1.1 官方Demo

代码如下(示例):

import matplotlib.pyplot as plt# Pie chart, where the slices will be ordered and plotted counter-clockwise
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice(i.e. 'Hogs')fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circleplt.savefig('Demo_official.jpg')
plt.show()

运行结果如下图:

1.2 将实际数据应用于官方Demo

代码如下(示例):

# 将实际数据应用于官方Demo
# 原始数据
shapes = ['Cross', 'Cone', 'Egg', 'Teardrop', 'Chevron', 'Diamond', 'Cylinder', 'Rectangle','Flash', 'Cigar', 'Changing', 'Formation', 'Oval', 'Disk','Sphere', 'Fireball', 'Triangle', 'Circle', 'Light']
values = [287, 383, 842, 866, 1187, 1405, 1495, 1620, 1717, 2313, 2378, 3070, 4332, 5841, 6482, 7785,9358, 9818, 20254]s = pd.Series(values, index=shapes)
from matplotlib import font_manager as fm
import matplotlib as mpl# Pie chart, where the slices will be ordered and plotted counter-clockwisse:
labels = s.index
sizes = s.values
explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)  # only "explode" the 1st slicefig1, ax1 = plt.subplots()
patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.0f%%',shadow=False, startangle=170)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circleplt.savefig('Demo_project.jpg')
plt.show()

运行结果如下图:

上图的一些问题:

1. 颜色比较生硬

2. 部分文字拥挤在一起,绘图显示不齐整

1.3 一些改善措施

§ 重新设置字体大小

§ 设置自选颜色

§ 设置图例

§ 将某些类别突出显示

1.3.1 重新设置字体大小

代码如下:

from matplotlib import font_manager as fm
import matplotlib as mpl# Pie chart, where the slices will be ordered and plotted counter-clockwisse:
labels = s.index
sizes = s.values
explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)  # only "explode" the 1st slicefig1, ax1 = plt.subplots()
patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.0f%%',shadow=False, startangle=170)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')
# font size include: 'xx-small', x-small, 'small', 'medium', 'large', 'x-large', xx-large or number, e.g. '12'
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)
plt.savefig('Demo_project_set_font.jpg')
plt.show()

运行结果如下图

1.3.2 设置显示颜色,Method1:

示例代码如下:

# 设置显示颜色,Method1
from matplotlib import font_manager as fm
import matplotlib as mpl# Pie chart,where the slices will be ordered and plotted counter-clockwisse
labels = s.index
sizes = s.valuesexplode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)  # only "explode" the 1st sli
fig1, ax1 = plt.subplots(figsize=(6,6))a = np.random.rand(1, 19)
color_vals = list(a[0])
my_norm = mpl.colors.Normalize(-1, 1) # 将颜色数据的范围设置为[0, 1]
my_cmap = mpl.cm.get_cmap('rainbow', len(color_vals)) # 可选择合适的colormap, 如:'rainbow'patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels,autopct='%1.0f%%',shadow=False, startangle=170, colors=my_cmap(my_norm(color_vals)))
ax1.axis('equal')# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)plt.savefig('Demo_project_set_color_1.jpg')
plt.show()

运行结果如下图:

上面这种方法设置颜色时,但类别比较多时,部分颜色的填充会重复。有时候,可能想设置成连续的颜色,可用另一种方法实现。

1.3.3设置显示颜色, Method2:

示例代码如下:

# 设置颜色方法Method2from matplotlib import font_manager as fm
from matplotlib import cmlabels = s.index
sizes = s.values
fig1, ax1 = plt.subplots(figsize=(6,6))colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray, spring, Darkspatches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels,autopct='%1.0f%%',shadow=False, startangle=170, colors=colors)
ax1.axis('equal')
ax1.set_title('Shapes -------------------------------', loc='left')# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)plt.savefig('Demo_project_set_color_2.jpg')
plt.show()

运行结果如下图:

从上图可以看出,颜色显示是连续的,实现了我们想要的效果。

1.3.4 设置图例

示例代码如下:

# 设置图例(legend)
from matplotlib import font_manager as fm
from matplotlib import cmlabels = s.index
sizes = s.values
fig1, ax1 = plt.subplots(figsize=(6,6))colors = cm.rainbow(np.arange(len(sizes))/len(sizes))patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels,autopct='%1.0f%%',shadow=False, startangle=170, colors=colors)ax1.axis('equal')
# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)ax1.legend(labels, loc=2)
plt.savefig('Demo_project_set_legend_error.jpg')
plt.show()

运行结果如下图:

从上图可看出,当类别较多时,图例(legend)的位置摆放显示有重叠,显示有些问题,需要进行调整 。

1.3.5 重新设置图例(legend)

示例代码如下:

# 重新设置图例(legend)from matplotlib import font_manager as fm
from matplotlib import cmlabels = s.index
sizes = s.values
fig, axes = plt.subplots(figsize=(10, 5), ncols=2) # 设置绘图区域大小
ax1, ax2 = axes.ravel()colors = cm.rainbow(np.arange(len(sizes))/len(sizes))patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels,autopct='%1.0f%%',shadow=False, startangle=170, colors=colors)ax1.axis('equal')
# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)ax1.set_title('Shapes', loc='center')# ax2只显示图例(legend)
ax2.axis('off')
ax2.legend(patches, labels, loc='center left')plt.tight_layout()plt.savefig('Demo_project_set_legend_good.jpg')
plt.show()

运行结果如下图:

1.3.6 将某些类别突出显示

§ 将某些类别突出显示

§ 控制label的显示位置

§ 控制百分比的显示位置

§ 控制突出位置的大小

示例代码如下:

# 1.3.6 将某些类别突出显示
from matplotlib import font_manager as fm
from matplotlib import cmlabels = s.index
sizes = s.valuesexplode = (0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0.1, 0)  # only "explode" the 1st sli
fig, axes = plt.subplots(figsize=(10, 5), ncols=2) # 设置绘图区域大小
ax1, ax2 = axes.ravel()colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps:Paired, autumn, rainbow, gray, spring, Darks
patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels,autopct='%1.0f%%',shadow=False, startangle=170, colors=colors, labeldistance=1.2,pctdistance=1.03, radius=0.4)# labeldistance:控制labels显示的位置
# pctdistance:控制百分比显示的位置
# radius:控制切片突出的距离ax1.axis('equal')# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)ax1.set_title('Shapes', loc='center')# ax2只显示图例(legend)
ax2.axis('off')
ax2.legend(patches, labels, loc='center left')plt.tight_layout()
plt.savefig('Demo_project_final.jpg')
plt.show()

运行结果如下图:

总结

本文的案例取自Python数据之道,以上练习的内容,仅仅简单介绍了matplotlib的使用,而matplotlib功能模块提供了大量使用方法,大家可以多多练习实践。

Matplotlib饼图实例相关推荐

  1. ECharts饼图实例

    ECharts饼图实例 1.引入jQuery的js文件 2.引入echarts的js文件 test.html页面 <!DOCTYPE html PUBLIC "-//W3C//DTD ...

  2. matplotlib 饼图 plt.pie()

    绘制饼图 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt #设置字体样式 mpl.rcParam ...

  3. python matplotlib 饼图标签重叠_Python绘制饼图调节字体大小、防止标签重叠解决方法...

    设置字体的大小 patches,l_text,p_text=plt.pie(money_rate,explode=explode,labels=names,autopct='%.2f%%') # l_ ...

  4. Matplotlib - 饼图、环形图 pie() 多重饼图 subplots() 所有用法详解

    目录 基本用法 饼图中突出显示某部分 环形图(空心饼图) 多重饼图,并添加分割线 相较散点图和折线图,柱状图.饼图.箱线图是另外 3 种数据分析常用的图形,主要用于分析数据内部的分布状态或分散状态.饼 ...

  5. python——Matplotlib饼图、直方图的绘制

    实验环境 python 3.6 matplotlib 2.2.3 饼图的绘制 matplotlib.pyplot.pie(x, explode=None, labels=None, colors=No ...

  6. Matplotlib——饼图pie()函数

    饼图(扇形图)是一种常见的可以表示离散变量各水平占比情况的一种统计图.Matpllotlib提供了pie()函数用于绘制饼图. import matplotlib.pyplot as plt_ = p ...

  7. Python matplotlib 饼图

    文章目录 一.整理数据 二.创建饼图 三.爆炸效果 四.阴影效果 五.为饼图加上百分比 六.让饼图旋转不同的角度 七.为饼图添加边缘线 八.为饼图数据分组 一.整理数据 关于cnboo1.xlsx,我 ...

  8. Matplotlib饼图注释

    import numpy as np import matplotlib.pyplot as pltplt.figure(figsize=(9,9))# 环形饼图元素 recipe = [" ...

  9. python matplotlib画图实例正弦 SIN()和余弦COS()曲线

    import matplotlib.pyplot as plt import numpy as np#在画的图中显示中文 plt.rcParams['font.sans-serif'] = ['Sim ...

最新文章

  1. Postgresql服务器配置-设置参数
  2. LeetCode40.组合总和|| JavaScript
  3. 图说开源许可协议:GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
  4. 计算机组成原理——指令流水线
  5. 【简便解法】1079 延迟的回文数 (20分)_31行代码AC
  6. ELASTIC API
  7. 前端学习(2652):初始化项目
  8. Chrome Workspace开发者调试工具
  9. 关于socket组播和ssdp(一)[修改1.2]
  10. HIVE之 DDL 数据定义 DML数据操作
  11. 移动开发—媒体查询(Media Query)
  12. 小米笔试题--数组移动
  13. 系统集成项目管理工程师14 总结
  14. 一篇文章教会你需求分析文档怎么写
  15. 02 | 给你一张知识地图,计算机组成原理应该这么学
  16. C++进程间通信的十一种方法
  17. 下载jar源码时,出现:cannt not download source Sources not found for
  18. 基于ssm整合的网上书城
  19. createrepo的用法
  20. 某软件测试大纲,软件测试(验收)大纲

热门文章

  1. 入手评测 暗影骑士龙和暗影骑士擎哪个更值得入手
  2. picACG本地缓存目录_饭团追书怎么返回目录 饭团追书和饭团探书区别
  3. 国内10个千年古镇 绝美春色洗涤你的眼
  4. 【包运行】Java 实现图形界面的邮件轰炸机附带视频指导教程
  5. 第三方远程控制工具TeamViewer的安装和使用教程,可下载window版和linux版,windows使用虚拟机可以与linux之间通讯
  6. 夜晚图像的目标检测-matlab
  7. 蓝桥杯 填空题 水题 等差素数列 C++ 简单暴力枚举
  8. Mac 安装element-ui
  9. 单摆测重力加速度的算法(Python)
  10. 服务器安全神器,Linux 上安装 Fail2Ban 保护 SSH