200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Python数据可视化之matplotlib绘图教程

Python数据可视化之matplotlib绘图教程

时间:2019-07-28 23:50:22

相关推荐

Python数据可视化之matplotlib绘图教程

目录

一、快速绘图

1. 折线图

2. 柱状图

3. 饼状图

4. 散点图

5. 图片保存

二、基本设置

1. 图片

2. 坐标轴

3. 刻度

4. 边距

5. 图例

6. 网格

7. 标题

8. 文本

9. 注释文本

10. 主题设置

11.颜色

12. 线条样式

13. 标记形状

三、绘图进阶

1. 折线图

2. 条形图

3. 散点图

4. 饼状图

5. 多图并列

四、pyplot模块

0. 常用绘图函数

1. plot()

五、综合案例

1. 基本设置

2. 颜色设置

中文官网:Matplotlib 中文

英文官网:Matplotlib

Matplotlib 是一个 Python 的 2D 绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。可以绘制线图、散点图、等高线图、条形图、柱状图、3D 图形,甚至是图形动画等等。

一、快速绘图

1. 折线图

import matplotlib.pyplot as plt# 方式一y = [20, 40, 60, 40, 45, 60, 20]plt.plot(y)plt.show()# 方式二# x = [1, 2, 3, 4, 5, 6]# y = [20, 40, 60, 40, 45, 60, 20]# plt.plot(x, y)# # plt.show()

2. 柱状图

import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5, 6, 7]y = [20, 40, 60, 40, 45, 60, 20]plt.bar(x, y)plt.show()

3. 饼状图

import matplotlib.pyplot as plty = [1, 2, 2, 5]plt.pie(y)plt.show()

4. 散点图

import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y = [1, 2, 2, 5, 4]plt.scatter(x, y)plt.show()

5. 图片保存

plt.savefig("figure.jpg")plt.savefig("figure.png")plt.savefig("figure.svg")

二、基本设置

1. 图片

plt.figure(figsize=(10,5)) # 设置图片大小

2. 坐标轴

plt.xlabel('time (s)') # 设置x轴标签plt.ylabel('Undamped') # 设置y轴标签plt.xlim(0,10) # 设置x轴范围plt.ylim(0,99) # 设置y轴范围plt.axis([0,8,0,100]) # 同时设置x轴与y轴的范围

3. 刻度

plt.xticks([0, 1, 2], ['January', 'February', 'March']) # 设置x轴刻度值plt.yticks([0, 1, 2], ['A', 'B', 'C'], rotation=45) # 设置y轴刻度值plt.xscale("linear") # 设置x轴刻度类型,"linear", "log", "symlog", "logit", ...plt.yscale("linear") # 设置y轴刻度类型

4. 边距

plt.margins(0.2) # 同时设置xy边距比例plt.margins(x=0.2) # 同时设置x边距比例plt.margins(y=0.2) # 同时设置y边距比例

5. 图例

# 方法一plt.plot([1, 2, 3], label='Inline label')plt.legend()# 方法二line = ax.plot([1, 2, 3])line.set_label('Label via method')ax.legend()# 多个图例plt.plot([1, 2, 3])plt.plot([5, 6, 7])plt.legend(['First line', 'Second line'])

plt.legend(loc='best')# 设置图例位置为最佳位置plt.legend(loc='upper right') # 设置图例位置为右上方plt.legend(loc='upper left') # 设置图例位置为左上方plt.legend(loc='lower left') # 设置图例位置为左下方plt.legend(loc='lower right') # 设置图例位置为右下方plt.legend(loc='right') # 设置图例位置为右边plt.legend(loc='center left') # 设置图例位置为中间偏左plt.legend(loc='center right') # 设置图例位置为中间偏右plt.legend(loc='lower center') # 设置图例位置为底部偏中plt.legend(loc='upper center') # 设置图例位置为顶部偏中plt.legend(loc='center') # 设置图例位置为中间

6. 网格

plt.grid(True, 'major', 'both')plt.grid(color='r', linestyle='-', linewidth=2) # 设置网格颜色、线样式、线宽

7. 标题

plt.title(label, fontdict=None, loc=None, pad=None, *, y=None,**kwargs) # 显示标题

8. 文本

pyplot.text(x, y, s, fontdict=None, **kwargs) # 绘制文本

9. 注释文本

plt.annotate(text, xy, xytext=None) # 绘制注释文本

10. 主题设置

import matplotlib.pyplot as plt# 设置显示的样式(主题)plt.style.use('bmh')# plt.style.use('ggplot')# plt.style.use('grayscale')# plt.style.context('Solarize_Light2')x = [1, 2, 3, 4, 5, 6, 7]y = [20, 40, 60, 40, 45, 60, 20]plt.bar(x, y)plt.show()

11.颜色

12. 字体

matplotlib 中使用的字体来源于三个途径:

matplotlib 自带的字体windows 系统字体用户提供的第三方字体

通过以下代码可查看支持的字体

from matplotlib import font_managerfor font in font_manager.fontManager.ttflist:print(font.name, '-', font.fname)

13. 线条样式

linestyle

14. 标记形状

marker

三、绘图进阶

Figure:指整个图形,您可以把它理解成一张画布,它包括了所有的元素,比如标题、轴线等;Axes:绘制 2D 图像的实际区域,也称为轴域区,或者绘图区;Axis:指坐标系中的垂直轴与水平轴,包含轴的长度大小(图中轴长为 7)、轴标签(指 x 轴,y轴)和刻度标签;Artist:您在画布上看到的所有元素都属于 Artist 对象,比如文本对象(title、xlabel、ylabel)、Line2D 对象(用于绘制2D图像)等。

1. 折线图

import matplotlib.pyplot as pltx1 = [1, 2, 3, 4, 5]y1 = [4, 5, 7, 5, 6]plt.plot(x1, y1, color='g')x1 = [5, 6, 7, 8, 9]y1 = [6, 5, 7, 5, 6]plt.plot(x1, y1, color='c')plt.show()

import matplotlib.pyplot as pltx1 = [1, 2, 3, 4, 5]y1 = [4, 5, 7, 5, 6]x2 = [5, 6, 7, 8, 9]y2 = [6, 5, 7, 5, 6]plt.plot(x1, y1, x2, y2)plt.show()

import matplotlib.pyplot as pltimport numpy as npx = np.random.rand(10)y = [1,2,3,4,7,8,9,5,14,11]plt.plot(x, y, 'go--', linewidth=2, markersize=12)plt.show()

2. 条形图

2.1 堆积条形图

import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y1 = [4, 5, 7, 5, 6]y2 = [6, 5, 7, 5, 6]plt.bar(x, y1, fc='y', label='A')plt.bar(x, y2, fc='g', label='B', bottom=y1)plt.show()

import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y1 = [6, 10, 4, 5, 1]y2 = [2, 12, 4, 7, 8]plt.barh(x, y1, align='center', color='#66c2a5', tick_label=['A', 'B', 'C', 'D', 'E'], label='classA')plt.barh(x, y2, align='center', color='#8da0cb', left=y1, label='classB')plt.legend()plt.xlabel('x')plt.ylabel('y')plt.show()

2.2 并列条形图

import matplotlib.pyplot as pltimport numpy as nplabels = ['G1', 'G2', 'G3', 'G4', 'G5']men_means = [20, 34, 30, 35, 27]women_means = [25, 32, 34, 20, 25]x = np.arange(len(labels)) # 标签的位置width = 0.35 # 条形的宽度fig, ax = plt.subplots()rects1 = ax.bar(x - width/2, men_means, width, label='Men')rects2 = ax.bar(x + width/2, women_means, width, label='Women')ax.set_ylabel('Scores') # y轴标题ax.set_title('Scores by group and gender') # 图形标题ax.set_xticks(x, labels) # 修改x轴刻度值ax.legend() # 显示图例# 显示条形上方数值ax.bar_label(rects1, padding=3)ax.bar_label(rects2, padding=3)# 布局设置fig.tight_layout()plt.show()

import matplotlib.pyplot as pltimport numpy as npx = np.arange(5)y1 = [6, 10, 4, 5, 1]y2 = [2, 12, 4, 7, 8]bar_width = 0.35tick_label = ['A', 'B', 'C', 'D', 'E']plt.bar(x, y1, bar_width, color='c', align='center', label='classA', alpha=0.5)plt.bar(x+bar_width, y2, bar_width, color='b', align='center', label='classB', alpha=0.5)plt.xlabel('class')plt.ylabel('score')# 设置x轴刻度标签plt.xticks(x+bar_width/2, tick_label)# 显示图例plt.legend()plt.show()

​import matplotlib.pyplot as pltimport numpy as npx = np.arange(5)y1 = [6, 10, 4, 5, 1]y2 = [2, 12, 4, 7, 8]bar_width = 0.35tick_label = ['A', 'B', 'C', 'D', 'E']plt.barh(x, y1, bar_width, color='c', align='center', label='classA', alpha=0.5)plt.barh(x+bar_width, y2, bar_width, color='b', align='center', label='classB', alpha=0.5)plt.ylabel('class')plt.xlabel('score')# 设置y轴刻度标签plt.yticks(x+bar_width/2, tick_label)plt.legend()plt.show()​

3. 散点图

import matplotlib.pyplot as pltimport numpy as npx = np.random.rand(50)y1 = np.random.rand(50)y2 = np.random.rand(50)plt.scatter(x, y1, s=30, marker='^', c='b', label="A")plt.scatter(x, y2, s=30, marker='o', c='g', label="B")plt.legend()plt.show()

4. 饼状图

import matplotlib.pyplot as pltlabels = 'A', 'B', 'C', 'D'students = [0.35, 0.15, 0.20, 0.30]colors = ['#377eb8', '#4daf4a', '#984ea3', '#ff7f00']explode = (0.1, 0.1, 0.1, 0.1)plt.pie(students, explode=explode, labels=labels, colors=colors, autopct='%3.1f%%', shadow=True, startangle=45)plt.title('Students')plt.show()

​import matplotlib.pyplot as pltlabels = 'A', 'B', 'C', 'D'students = [0.35, 0.15, 0.20, 0.30]colors = ['#377eb8', '#4daf4a', '#984ea3', '#ff7f00']plt.pie(students, labels=labels, colors=colors,pctdistance=0.7, labeldistance=1.2, autopct='%3.1f%%', shadow=True, startangle=45)plt.title('Students')plt.show()

5. 多图并列

import matplotlib.pyplot as pltimport numpy as np# 创建2x2个绘图区域fig, a = plt.subplots(2, 2)x = np.arange(1, 5)# 绘制平方函数a[0][0].plot(x, x * x)a[0][0].set_title('square')# 绘制平方根图像a[0][1].plot(x, np.sqrt(x))a[0][1].set_title('square root')# 绘制指数函数a[1][0].plot(x, np.exp(x))a[1][0].set_title('exp')# 绘制对数函数a[1][1].plot(x, np.log10(x))a[1][1].set_title('log')plt.show()

import matplotlib as mplimport matplotlib.pyplot as plt# 数据源t=np.arange(0.0,2.0,0.1)s=np.sin(t*np.pi)# 第一个图plt.subplot(2,2,1) #要生成两行两列,这是第一个图plt.plot(t,s,'b*')plt.ylabel('y1')# 第二个图plt.subplot(2,2,2) #两行两列,这是第二个图plt.plot(2*t,s,'r--')plt.ylabel('y2')# 第三个图plt.subplot(2,2,3)#两行两列,这是第三个图plt.plot(3*t,s,'m--')plt.ylabel('y3')# 第四个图plt.subplot(2,2,4)#两行两列,这是第四个图plt.plot(4*t,s,'k*')plt.ylabel('y4')# 显示图形plt.show()

四、pyplot模块

Matplotlib 中的 pyplot 模块是一个类似命令风格的函数集合,这使得 Matplotlib 的工作模式和 MATLAB 相似。

pyplot 模块提供了可以用来绘图的各种函数,比如创建一个画布,在画布中创建一个绘图区域,或是在绘图区域添加一些线、标签等。

0. 常用绘图函数

1. plot()

matplotlib.pyplot.plot(*args,scalex=True,scaley=True,data=None,**kwargs)

plot函数可直接用于绘制折线图,这是 axes 类的基本方法,它将一个数组的值与另一个数组的值绘制成线或标记,plot() 方法具有可选格式的字符串参数,用来指定线型标记颜色、样式以及大小。其基本参数如下:

五、综合案例

1. 基本设置

import matplotlib.pyplot as plty = [1, 3, 4, 2, 6, 5, 7]plt.plot(y,label='a', # 图例名称linewidth=5, # 线的宽度)plt.grid(axis='x', # 显示网格线的轴linestyle=':', # 网格线的样式c='gray', # 网格线的颜色linewidth=2, # 网格线的宽度)plt.axis([0, 8, 0, 10]) # x轴和y轴的取值范围font = {'family': 'serif','color': 'darkred','weight': 'normal','size': 16,}plt.xlabel('X', fontdict=font) # x轴的标题plt.ylabel('Y') # y轴的标题plt.tick_params(labelcolor='r', labelsize='medium', width=2) # 设置轴刻度样式plt.legend() # 显示图例plt.show()# 如何更改坐标轴边框颜色

2. 颜色设置

import matplotlib.pyplot as pltimport numpy as npt = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t)# 1) RGB tuple:图形背景色fig, ax = plt.subplots(facecolor=(.7, .7, .7))# 2) hex string: 坐标系背景色ax.set_facecolor('#eafff5')# 3) gray level string: 标题颜色ax.set_title('Voltage vs. time chart', color='0.9')# 4) single letter color string:x轴标题颜色ax.set_xlabel('Time [s]', color='c')# 5) a named color:y轴标题颜色ax.set_ylabel('Voltage [mV]', color='peachpuff')# 6) a named xkcd color: 折线颜色ax.plot(t, s, 'xkcd:crimson')# 7) Cn notation: 折线颜色ax.plot(t, .7 * s, color='C4', linestyle='--')# 8) tab notation: 刻度颜色ax.tick_params(labelcolor='tab:orange')# 坐标轴颜色ax.spines['right'].set_color('None') # 右框不显示ax.spines['top'].set_color('None') # 上框不显示ax.spines['left'].set_color('g') # 左框绿色ax.spines['bottom'].set_color('b') # 下框蓝色plt.show()

其它资料:

Matplotlib - 知乎

python如何使用Matplotlib画图(基础篇)_鲟曦研习社

matplotlib绘图的核心原理讲解

Matplotlib.pyplot接口汇总

matplotlib.pyplot的使用总结大全(入门加进阶) - 知乎

matplotlib字体设置看这一篇就够了-技术圈

matplotlib字体设置 - 知乎

将matplotlib更改字体为 宋体、TimesNewRoman

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。