关于matplotlib,你要的饼图在这里
Table of Contents
前言
matplotlib, 官方提供的饼图Demo,功能比较比较简单,在实际应用过程中,往往会有许多个性化的绘制需求,在这里跟大家一起了解下饼图(pie chart)的一些特色的功能的实现。
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')
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 circle.
plt.savefig('Demo_official.jpg')
plt.show()
2. 将实际数据应用于官方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)
s
from matplotlib import font_manager as fm
import matplotlib as mpl
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
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 slice
fig1, 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.
plt.savefig('Demo_project.jpg')
plt.show()
上图的一些问题:
- 颜色比较生硬
- 部分文字拥挤在一起,绘图显示不齐整
3. 一些改善措施
- 重新设置字体大小
- 设置自选颜色
- 设置图例
- 将某些类别突出显示
3.1 重新设置字体大小
from matplotlib import font_manager as fm
import matplotlib as mpl
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 slice
fig1, 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()
3.2 设置显示颜色,Method 1:
from matplotlib import font_manager as fm
import matplotlib as mpl
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
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 slice
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')
# 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_color_1.jpg')
plt.show()
上面这种方法设置颜色时,但类别比较多时,部分颜色的填充会重复。
有时候,我们可能想设置成连续的颜色,可以有另外一种方法来实现。
3.3 设置显示颜色, Method 2:
from matplotlib import font_manager as fm
from matplotlib import cm
labels = s.index
sizes = s.values
# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slice
fig, ax = plt.subplots(figsize=(6,6)) # 设置绘图区域大小
colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks
patches, texts, autotexts = ax.pie(sizes, labels=labels, autopct='%1.0f%%',
shadow=False, startangle=170, colors=colors)
ax.axis('equal')
ax.set_title('Shapes -------------------', loc='left')
# 重新设置字体大小
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_color_2.jpg')
plt.show()
从上图可以看出,颜色显示是连续的,实现了我们想要的效果
3.4 设置图例(legend)
from matplotlib import font_manager as fm
from matplotlib import cm
labels = s.index
sizes = s.values
# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slice
fig, ax = plt.subplots(figsize=(6,6)) # 设置绘图区域大小
colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks
patches, texts, autotexts = ax.pie(sizes, labels=labels, autopct='%1.0f%%',
shadow=False, startangle=170, colors=colors)
ax.axis('equal')
# 重新设置字体大小
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)
ax.legend(labels, loc=2)
plt.savefig('Demo_project_set_legend_error.jpg')
plt.show()
从上面可看出,当类别较多时,图例(legend)的位置摆放显示有重叠,显示有些问题,需要进行调整。
3.5 重新设置图例(legend)
from matplotlib import font_manager as fm
from matplotlib import cm
labels = s.index
sizes = s.values
# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slice
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, labels=labels, autopct='%1.0f%%',
shadow=False, startangle=170, colors=colors)
ax1.axis('equal')
# 重新设置字体大小
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)
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()
3.6 将某些类别突出显示
- 将某些类别突出显示
- 控制label的显示位置
- 控制百分比的显示位置
- 控制突出位置的大小
from matplotlib import font_manager as fm
from matplotlib import cm
labels = s.index
sizes = s.values
explode = (0.1,0,0,0,0,0,0,0,0,0,0,0,0,0.2,0,0,0,0.1,0) # "explode" , show the selected slice
fig, axes = plt.subplots(figsize=(8,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, labels=labels, autopct='%1.0f%%',explode=explode,
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')
# 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)
ax1.set_title('Shapes', loc='center')
# ax2 只显示图例(legend)
ax2.axis('off')
ax2.legend(patches, labels, loc='center left')
plt.tight_layout()
# plt.savefig("pie_shape_ufo.png", bbox_inches='tight')
plt.savefig('Demo_project_final.jpg')
plt.show()
更多精彩内容请关注公众号:
“Python数据之道”
关于matplotlib,你要的饼图在这里的更多相关文章
- 你都用python来做什么?
首页发现话题 提问 你都用 Python 来做什么? 关注问题写回答 编程语言 Python 编程 Python 入门 Python 开发 你都用 Python 来做什么? 发现很 ...
- 我用了半年的时间,把python学到了能出书的程度
Python难学吗?不难,我边做项目边学,过了半年就通过了出版社编辑的面试,接到了一本Python选题,并成功出版. 有同学会说,你有编程基础外带项目实践机会,所以学得快.这话不假,我之前的基础确实加 ...
- matplotlib 柱状图、饼图;直方图、盒图
#-*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl m ...
- matplotlib入门--1(条形图, 直方图, 盒须图, 饼图)
作图首先要进行数据的输入,matplotlib包只提供作图相关功能,本身并没有数据读入.输出函数,针对各种试验或统计文本数据输入可以使用numpy提供的数据输入函数. # -*- coding: gb ...
- 使用matplotlib画饼图
import matplotlib.pyplot as pltx = [4, 9, 21, 55, 30, 18]labels = ['math', 'history', 'chemistry', ' ...
- Matplotlib学习---用matplotlib画饼图/面包圈图(pie chart, donut chart)
我在网上随便找了一组数据,用它来学习画图.大家可以直接把下面的数据复制到excel里,然后用pandas的read_excel命令读取.或者直接在脚本里创建该数据. 饼图: ax.pie(x,labe ...
- 06. Matplotlib 2 |折线图| 柱状图| 堆叠图| 面积图| 填图| 饼图| 直方图| 散点图| 极坐标| 图箱型图
1.基本图表绘制 plt.plot() 图表类别:线形图.柱状图.密度图,以横纵坐标两个维度为主同时可延展出多种其他图表样式 plt.plot(kind='line', ax=None, figsiz ...
- python 使用 matplotlib.pyplot来画柱状图和饼图
导入包 import matplotlib.pyplot as plt 柱状图 最简柱状图 # 显示高度 def autolabel(rects): for rect in rects: height ...
- matplotlib基本使用(矩形图、饼图、热力图、3D图)
使用matplotlib画简单的图形: #-*- coding:utf-8 -*- from numpy.random import randn import matplotlib.pyplot as ...
- matplotlib常见绘图基础代码小结:折线图、散点图、条形图、直方图、饼图
一.折线图 二.散点图 三.条形图 四.直方图 五.饼图 一.折线图折线图用于显示随时间或有序类别的变化趋势 from matplotlib import pyplot as plt x = rang ...
随机推荐
- 解决在linux安装网易云音乐无法点击图标打开
一下内容转载自:https://blog.csdn.net/Handoking/article/details/81026651 似乎linux下无法直接打开网易云音乐的原因是图标自带的启动脚本中没有 ...
- Java迭代实现斐波那契数列
剑指offer第九题Java实现 题目: 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项. public class Test9 { public static void ...
- 【洛谷 P2761】 软件补丁问题(状态压缩,最短路)
题目链接 第四题. 初看题目很懵,网络流这么厉害的吗,毫无头绪去看题解.. 所以这和网络流有什么关系呢? 把规则用二进制保存下来,然后跑最短路救星了. 在线跑,离线连边太慢了. (以后干脆不管什么题直 ...
- js_同步和异步
刚开始写js那会,对这一块是知之甚少,太多太多的知识不足,致使做什么都很艰难.现在工作也有段时间了,知识也有了点积累, 写点什么分享一下. 同步和异步?这个问题是在使用ajax请求后台数据的时候出现的 ...
- Yii 1.1.17 二、Gii创建后台与后台登录验证
一.用Gii创建后台模块 1.启用gii,在config/main.php 'gii' => array( 'class' => 'system.gii.GiiModule', 'pass ...
- python基础===* 解包,格式化输出和print的一点知识
python3中的特性: >>> name = "botoo" >>> print(f"my name is {name}" ...
- python基础=== itertools介绍(转载)
原文链接:http://python.jobbole.com/85321/ Python提供了一个非常棒的模块用于创建自定义的迭代器,这个模块就是 itertools.itertools 提供的工具相 ...
- C后端设计开发 - 第1章-流派-入我华山,学我剑法
正文 第1章-流派-入我华山,学我剑法 后记 如果有错误, 欢迎指正. 有好的补充, 和疑问欢迎交流, 一块提高. 在此谢谢大家了.
- Smarty模板快速入门
文件下载 1.下载地址:http://www.smarty.net/ 2.我下载的版本是3.1.27 ,将下载的文件smarty-3.1.27.zip解压出来,然后将libs文件夹的所有文件复制到你的 ...
- IoT之车联网
一. 背景 这是一个笔者在实习公司策划的关于车联网的小项目,也是笔者参加某竞赛的作品<基于云平台的车内滞留儿童状况监测与处理>,本项目旨在为因各种原因导致儿童滞留车内热死.闷死的社会性事件 ...