超全Matplotlib画图操作总结
目录
Matplotlib
content: data analyst, operation
intro
是Python中的低级图形绘图库,用作可视化实用程序
开源的 由John D. Hunter创建
Matplotlib 大部分是用 python 编写的,少数部分是用 C、Objective-C 和 Javascript 编写的,以实现平台兼容性
对plot()
函数的应用
*import* matplotlib.pyplot *as* plt
代码源:
https://github.com/matplotlib/matplotlib
Reference
matplotlib.pyplot.subplot — Matplotlib 3.7.1 documentation
https://www.huaxiaozhuan.com/工具/matplotlib/chapters/matplotlib.html
Matplotlib Pyplot
Most of the Matplotlib utilities lies under the pyplot
submodule(大部分的程序位于pyplot子模块下), and are usually imported under the plt
alias:
import matplotlib.pyplot as plt
plotting 绘图
plot()
:
plt.plot(xpoints, ypoints)
用于绘制点(标记)
默认情况下: plot()函数从一点到另一点绘制一条线
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
结果显示:
Plotting Without Line
using shortcut string notation parameter ‘o’, which means ‘rings’.
plt.plot(xpoints, ypoints, 'o')
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Default X-Points
如果我们不指定x轴上的点,它们将获得默认值0、1、2、3
#example:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Matplotlib Markers
Markers
You can use the keyword argument marker
to emphasize each point with a specified marker marker来强调带有指定标记的每个点
mark=’’ 作为一个parameter传进plot()
中
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = '*')
plt.show()
正常情况:
mark后:
-
Marker Reference
Marker Description ‘o’ Circle ‘*’ Star ‘.’ Point ‘,’ Pixel ‘x’ X ‘X’ X (filled) ‘+’ Plus ‘P’ Plus (filled) ‘s’ Square ‘D’ Diamond ‘d’ Diamond (thin) ‘p’ Pentagon ‘H’ Hexagon ‘h’ Hexagon ‘v’ Triangle Down ‘^’ Triangle Up ‘<’ Triangle Left ‘>’ Triangle Right ‘1’ Tri Down ‘2’ Tri Up ‘3’ Tri Left ‘4’ Tri Right ’ ’ ‘_’ Hline
Format Strings fmt
You can use also use the shortcut string notation parameter to specify the marker 快捷字符串表示法参数来指定标记
*marker*|*line*|*color*
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, 'o:r')
plt.show()
-
Line Reference
Line Syntax Description ‘-’ Solid line ‘:’ Dotted line ‘–’ Dashed line ‘-.’ Dashed/dotted line -
Color Reference
Color Syntax Description ‘r’ Red ‘g’ Green ‘b’ Blue ‘c’ Cyan ‘m’ Magenta ‘y’ Yellow ‘k’ Black ‘w’ White
Marker Size
You can use the keyword argument markersize
or the shorter version, ms
to set the size of the markers
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o', ms = 20)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Marker Color
可以直接用red这样子的字眼或者hex同样可以
区别成了边框颜色和填充颜色
You can use the keyword argument markeredgecolor
or the shorter mec
to set the color of the edge of the markers 这个是Mark边框的颜色而不是填色
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r')
plt.show()
You can use the keyword argument markerfacecolor
or the shorter mfc
to set the color inside the edge of the markers 填充的颜色
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o', ms = 20, mfc = 'r')
plt.show()
Matplotlib Line
Linestyle
You can use the keyword argument linestyle
, or shorter ls
, to change the style of the plotted line 线型
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()
Shorter Syntax
The line style can be written in a shorter syntax:
linestyle
can be written as ls
.
dotted
can be written as :
.
dashed
can be written as --
Line Styles
Style | Or |
---|---|
‘solid’ (default) | ‘-’ |
‘dotted’ | ‘:’ |
‘dashed’ | ‘–’ |
‘dashdot’ | ‘-.’ |
‘None’ | ‘’ or ’ ’ |
Line Color
You can use the keyword argument color
or the shorter c
to set the color of the line 可以用颜色名词也可以用hex
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, c = '#4CAF50')
plt.show()
Line Width
You can use the keyword argument linewidth
or the shorter lw
to change the width of the line.
#example:
import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linewidth = '20.5')
plt.show()
Multiple Lines
adding more plt.plot()
#example:
import matplotlib.pyplot as plt
import numpy as np
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])
plt.plot(y1)
plt.plot(y2)
plt.show()
You can also plot many lines by adding the points for the x- and y-axis for each line in the same plt.plot()
function
#example:
import matplotlib.pyplot as plt
import numpy as np
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])
plt.plot(x1, y1, x2, y2)
plt.show()
Matplotlib Labels and Title
Create Labels for a Plot
With Pyplot, you can use the xlabel()
and ylabel()
functions to set a label for the x- and y-axis.
plt.xlabel("")
plt.ylabel("")
#example:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Create a Title for a Plot
With Pyplot, you can use the title()
function to set a title for the plot.
plt.title("")
#example:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Set Font Properties for Title and Labels
You can use the fontdict
parameter in xlabel()
, ylabel()
, and title()
to set font properties for the title and labels 设置字体属性
fontdict = font
参数
#example:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
font1 = {'family':'serif','color':'blue','size':20} #需要的字体参数
font2 = {'family':'serif','color':'darkred','size':15} #需要的字体参数
plt.title("Sports Watch Data", fontdict = font1) #当做参数传入
plt.xlabel("Average Pulse", fontdict = font2) #当做参数传入
plt.ylabel("Calorie Burnage", fontdict = font2) #当做参数传入
plt.plot(x, y)
plt.show()
Position the Title
You can use the loc
parameter in title()
to position the title.
Legal values are: ‘left’, ‘right’, and ‘center’. Default value is ‘center’.
loc = ''
#example:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data", loc = 'left')
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.show()
Add Grid Lines
Add Grid Lines to a Plot
grid()
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.grid()
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Specify Which Grid Lines to Display
axis
parameter in the grid()
function to specify which grid lines to display.
axis = ''
根据哪个轴来显示网格线
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
#画图数据:
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
#命名:
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.grid(axis = 'x') #根据x轴划线
plt.show()
plt.plot(x, y)
plt.grid(axis = 'y') #根据y轴划线
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
axis = ‘x’
axis = ‘y’
Set Line Properties for the Grid
grid(color = '*color*', linestyle = '*linestyle*', linewidth = *number*)
#example:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
#线的颜色 类型 粗细
plt.grid(color = 'green', linestyle = '--', linewidth = 0.5)
plt.show()
Matplotlib Subplot
Display Multiple Plots
subplot(nrows,ncols,index)
#example:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 3, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 3, 3)
plt.plot(x,y)
plt.show()
Title
title()
:
#example:
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
Super Title
suptitle()
:
#example:
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
plt.suptitle("MY SHOP")
plt.show()
Matplotlib Scatter 散点图
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='颜色图名称')
Creating Scatter Plots
scatter(x,y)
:
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Compare Plots
同样的图里面显示两个不同的样本的数据
#example:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
#day one, the age and speed of 13 cars:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
#day two, the age and speed of 15 cars:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
两个数据集的数据用的不同的颜色来显示
默认情况下是蓝色和橙色
color
color
关键词参数
scatter(x, y, color = '')
可以是颜色名词也可以是HEX
#example:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color = '#88c999')
plt.show()
Color Each Dot
can even set a specific color for each dot by using an array of colors as value for the c
argument 通过使用颜色数组作为参数值来为每个点设置特定颜色 c
#example:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
ColorMap
cmap
可以使用带有颜色图值的关键字参数指定颜色图 范围从0到100不等
每个颜色图值的关键字参数指定颜色图
#example:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
#颜色图值里面的每种颜色的值
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
#颜色图:viridis(颜色图的名称)
plt.scatter(x, y, c=colors, cmap='viridis')
plt.show()
plt.colorbar()
:在旁边显示颜色图
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.colorbar()
plt.show()
size
s=size
plt.scatter(x, y, s=sizes)
#example:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
plt.scatter(x, y, s=sizes)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Alpha 透明度
alpha= (floating)
:
整体结合运用:
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')
plt.colorbar()
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Matplotlib Bars 条形图
bar(x,y,color=””,width=float)
barh(x,y,color=””,height=float)
Creating Bars
bar(x,y)
:
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Horizontal Bars
barh()
:
#example:
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y)
plt.show()
Bar Color and Bar Width
color
parameter 可以用名称也可以用Hex
width[bar()]
and height[barh()]
parameter 设置宽度
Matplotlib Histograms 直方图
Create Histogram
hist()
:
#example:
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Matplotlib Pie Charts 饼状图
plt.pie(y, labels = mylabels, explode = myexplode, shadow = True/False, colors = mycolors)
Creating Pie Charts
pie()
:
#example:
y = np.array([35, 25, 25, 15])
plt.pie(y)
plt.show()
默认情况下是以x轴开始逆时针旋转着
Note: The size of each wedge is determined by comparing the value with all the other values, by using this formula:
The value divided by the sum of all values:
x/sum(x)
labels
label
:
#example:
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels = mylabels)
plt.show()
Start Angle 起始角
startangle
paramete 默认是0度 自定义旋转的角度
#example:
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels = mylabels, startangle = 90)
plt.show()
Explode
explode
parameter 设置每个梭形显示离中心的距离
#example:
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels = mylabels, explode = myexplode)
plt.show()
Shadows
shadow = True
parameter 默认情况下是False
Colors
colors
parameter 名称或Hex
#example:
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]
plt.pie(y, labels = mylabels, colors = mycolors)
plt.show()
颜色一一对应的
-
color shortcuts
'r'
- Red'g'
- Green'b'
- Blue'c'
- Cyan'm'
- Magenta'y'
- Yellow'k'
- Black'w'
- White
Legend
plt.legend(title="")
添加解释列表
#example:
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels = mylabels)
plt.legend(title = "Four Fruits:")
plt.show()