如果能帮到你可以点个赞和关注,一起学习
基本图形绘制
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
x = np.linspace(-5,5,51)
y = x**2
# 样式:'-', '--', '-.', ':', '.', ',', , o, ^, v, <, >, s, +, x, D, d, 1, 2, 3, 4, h, H, p, |, _
# 颜色:b(蓝色),g(绿色),r(红色),c(青色),m(品红),y(黄色),k(黑色),w(白色)
fig = plt.figure(figsize=(5,3),facecolor='white')
plt.plot(x,y,c='r',ls='--')
plt.plot(x,y,'b--')
plt.grid()
fig.savefig(fname='matplotlib/img/1.png')
绘图属性设置
Pyplot函数 | APi方法 | 描述 |
---|---|---|
text() | mpl.axes.Axes.text() | 在Axes对象的任意位置添加文字 |
xlabel() | mpl.axes.Axes.set_xlabel() | 为X轴添加标签 |
ylabel() | mpl.axes.Axes.set_ylabel() | 为Y轴添加标签 |
title() | mpl.axes.Axes.set_title() | 为Axes对象添加标题 |
legend() | mpl.axes.Axes.legend() | 为Axes对象添加图例 |
annnotate() | mpl.axes.Axes.annotate() | 为Axes对象添加注释(箭头可选) |
suptitle() | mpl.figure.Figure.suptitle() | 为Figure对象添加中心化的标题 |
subplot多图布局
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(6,4))
x = np.linspace(-np.pi,np.pi,30)
y = np.sin(x)
plt.subplot(221)
plt.plot(x,y,c='red',linestyle='--')
plt.subplot(222)
plt.plot(x,y,c='pink',linestyle=':')
plt.subplot(223)
plt.plot(x,y,c='green',linestyle='dashed')
plt.subplot(224)
plt.plot(x,y,c='yellow',linestyle='-.')
fig.savefig('matplotlib/img/2.png')
图例
loc, ncol
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0,2**np.pi)
ax = plt.subplot()
ax.plot(x,np.sin(x),label='sin')
ax.plot(x,np.cos(x),label='cos')
# help(ax.legend)
ax.legend(
fontsize=18,
loc='center',
ncol=2,
bbox_to_anchor=[0,1,1,0.2]
)
plt.savefig('matplotlib/img/3.png')
线条属性
短名 | 全名 | 功能 | 示例值 |
---|---|---|---|
c | color | 线条/标记颜色 | ‘red’, ‘#FF0000’, ‘g’ |
marker | marker | 数据点标记样式 | ‘o’, ‘s’, ‘^’, ‘x’ |
ls | linestyle | 线条样式 | ‘-’, ‘–’, ‘:’, ‘None’ |
lw | linewidth | 线条宽度 | 2.0, 3.5 |
label | label | 图例标签 | ‘Data Series 1’ |
mfc | markerfacecolor | 标记内部填充颜色 | ‘blue’, ‘none’ |
ms | markersize | 标记大小 | 8, 10.5 |
mec | markeredgecolor | 标记边缘颜色 | ‘black’, ‘#333333’ |
mew | markeredgewidth | 标记边缘宽度 | 1.0, 2.5 |
alpha | alpha | 透明度(0: 透明, 1: 不透明) | 0.5 |
- 线条属性
- 线条:color、linestyle、linewidth、alpha
- 标记点:marker、markerfacecolor、markersize、markeredgecolor、markeredgewidth
- 图例:label
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(6,4))
ax = plt.subplot()
x = np.linspace(0,2*np.pi,100)
line = plt.Line2D(
x,
np.sin(x),
color='pink',
marker='o',
linestyle='--',
linewidth=2,
label='sin',
markerfacecolor='pink',
markersize=2,
markeredgecolor='black',
markeredgewidth=2,
alpha=0.5,
)
ax.add_line(line)
ax.legend(
loc='upper left'
)
plt.savefig('matplotlib/img/4.png')
坐标轴刻度
plt.xticks
- ticks=np.arange(0,11,1):刻度值列表
- labels=[‘min’,‘0’,‘max’]:数值标签
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(6,4))
ax = plt.subplot()
x = np.linspace(0,10)
y = np.sin(x)
line = plt.Line2D(
x,
y,
color='red'
)
ax.add_line(line)
plt.xticks(
np.arange(0,11,1),
fontsize=20,
color='red'
)
plt.yticks(
[-1,0,1],
labels=['min','0','max'],
fontsize=20,
color='blue',
ha='right',
# from matplotlib.text import Text 可以通过Text看到提示
)
plt.savefig('matplotlib/img/5.png')
坐标轴范围和配置
- xlim
- ylim
- axis
plt.figure(figsize=(5,3))
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x,y,c='r')
#设置坐标轴范围:axis([xmin, xmax, ymin, ymax])
# plt.axis([-2,8,-2,2])
#option
#off: 不显示坐标轴
#equal: 让x轴和y轴刻度距离相等
#*scaled*: 自动缩放坐标轴和图片匹配
#tight: 紧凑型自动适配图片
#square: 让画布呈现正方形,x轴和y轴宽高一致
plt.axis('square')
plt.show()
标题和网格
- title
- grid
import numpy as np
from matplotlib import pyplot as plt
ax = plt.subplot()
x = np.linspace(0,10)
y = np.sin(x)
plt.plot(x,y)
plt.title(
'title',
loc='center',
fontsize=20,
)
plt.suptitle(
'subtitle',
y=1.1,
fontsize=26,
)
ax.grid(ls='--',lw=0.5,color='grey',axis='x')
ax.axis('equal')
plt.savefig('matplotlib/img/6.png',bbox_inches='tight')
标签
- xlabel
import numpy as np
from matplotlib import pyplot as plt
# from matplotlib.text import Text # 方便看到提示
plt.figure(figsize=(8,4))
ax = plt.subplot()
x = np.linspace(0,10)
y = np.sin(x)
plt.plot(x,y)
# Text(rotation=45,horizontalalignment='right')
plt.xlabel('y=sin(x)',fontsize=20,rotation=45,color='red')
plt.ylabel('y=sin(x)',fontsize=20,color='green',horizontalalignment='right')
plt.title('sin')
plt.axis('equal')
plt.savefig('matplotlib/img/7.png', bbox_inches='tight')
文字
- x:x坐标
- y:y坐标
- s:文字
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.text import Text
ax = plt.subplot()
x = np.linspace(1,10,10)
y = np.array([60,30,20,90,40,60,50,80,70,30])
plt.plot(x,y,ls='--',marker='o')
Text(color='r')
for a,b in zip(x,y):
ax.text(
a-0.2,
b,
b,
fontsize=12,
color='r',
ha='center',
va='center'
)
plt.savefig(
'matplotlib/img/8.png',
bbox_inches='tight'
)
常用视图
- bar柱状图:width,bottom
- barh条形图
- hist直方图:bins, density
- boxplot箱型图:notch, sym
- scatter散点图
- hexbin六边形图
- pie饼图:autopct=‘%.1f%%’,pctdistance,labeldistance,textprops,explode
- stackplot面积图
- imshow热力图:cmap
- 极坐标图、雷达图:polar=True
柱形图
- width
- bottom
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(5,3))
x, y = np.arange(2014,2021),np.array([1962035,2838693,2317447,2335002,2438570,1675591,3568120])
ax = plt.subplot()
ax.bar(
x,
y
)
plt.title('sale')
plt.xlabel('year')
plt.ylabel('salery',rotation=0,horizontalalignment='right')
for a,b in zip(x,y):
ax.text(
a,
b + 0.2,
'{:.2f}M'.format(b/1000000),
ha='center'
)
plt.savefig(
'matplotlib/img/9.png',
bbox_inches='tight'
)
簇型柱状图
import numpy as np
from matplotlib import pyplot as plt
ax = plt.subplot()
x, y1, y2, y3 = np.arange(2014,2021),np.array([634704,1218844,1013322,1068521,419352,1190076,695421]),np.array([534917,746554,904058,12269,526985,117510,1433961]),np.array([792414,873295,400067,1254212,1492233,368005,138738])
i = 0.2
ax.bar(x-i,y1,label='y1',width=i)
ax.bar(x,y2,label='y2',width=i)
ax.bar(x+i,y3,label='y3',width=i)
ax.legend(loc='upper right')
plt.savefig('matplotlib/img/10.png', bbox_inches='tight')
堆叠柱状图
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(5,3))
x, y1, y2, y3 = np.arange(2014,2021),np.array([634704,1218844,1013322,1068521,419352,1190076,695421]),np.array([534917,746554,904058,12269,526985,117510,1433961]),np.array([792414,873295,400067,1254212,1492233,368005,138738])
plt.bar(x,y1,label='y1')
plt.bar(x,y2,bottom=y1,label='y2')
plt.bar(x,y3,bottom=y1+y2,label='y3')
plt.title('bar')
plt.legend()
plt.savefig('matplotlib/img/11.png',bbox_inches='tight')
直方图
- density:归一化
- bins:组
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
x = np.random.randint(0,10,100)
#统计每个数出现的次数
print(pd.Series(x).value_counts().sort_index())
#直方图
plt.xticks(range(10))
# bins: 组数
# plt.hist(x,bins=5)
plt.hist(x,bins=[0,3,6,9,10],facecolor='blue',alpha=0.4,edgecolor='k',density=True)
plt.savefig('matplotlib/img/12.png', bbox_inches='tight')
箱型图
- data:一维或二维列表
- labels:字符串或者列表,也可以通过xticks设置
data = np.random.normal(size=(500,4))
labels = ['A','B','C','D']
plt.boxplot(data,
labels=labels,
notch=True,# 箱型图样式
sym='r*' # 颜色+marker
)
plt.show()
散点图
x = range(1,7,1)
y = range(10,70,10)
plt.scatter(x,y)
饼图
autopct='%.1f%%'
:显示百分比(1位)- pctdistance:百分比文字的位置
- labels:标签
- testprops:传入字典,文字样式
- explode:传入列表,分裂效果
- shadow:是否有阴影
from matplotlib import pyplot as plt
plt.figure(figsize=(10,10))
x = [12932,9622,9505,7898,7675,7315,5164,5132,4885,4468]
citys = ['Guangdong', 'Shandong', 'Hubei', 'Jiangsu', 'Zhejiang', 'Hebei', 'Guangxi', 'Shanghai', 'Beijing', 'Sichuan']
plt.pie(x,
autopct='%.1f%%', # 显示百分比
pctdistance=0.8, # 百分比文字的位置
labels=citys, # 标签
labeldistance=1, # 标签的位置
#shadow=True,
textprops={'fontsize':14,'color':'blue'}, # 文字样式
explode=[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.1] #分裂效果
)
plt.legend()
plt.savefig('matplotlib/img/13.png', bbox_inches='tight')
面积图
from matplotlib import pyplot as plt
x = [2014,2015,2016,2017,2018,2019,2020]
y = [1962035,2838693,2317447,2335002,2438570,1675591,3568120]
plt.figure(figsize=(5,3))
plt.stackplot(x,y)
plt.plot(x,y)
plt.savefig('matplotlib/img/14.png', bbox_inches='tight')
热力图
- data:二维数组
- cmap:颜色映射
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame({
'Province': ['Guangdong', 'Guangxi', 'Hunan', 'Hubei', 'Jiangxi', 'Sichuan', 'Fujian', 'Jiangsu', 'Henan', 'Hebei', 'Shandong', 'Shanxi'],
'A': [9275, 9849, 5413, 7425, 1159, 8869, 4189, 5818, 9914, 1374, 7908, 8703],
'B': [8498, 8413, 7855, 9862, 1334, 8405, 2610, 7852, 8509, 7141, 4466, 2270],
'C': [5019, 9222, 2973, 3341, 1927, 8244, 2293, 3670, 3010, 9549, 3310, 5979],
'D': [4468, 6162, 1597, 7923, 9884, 5410, 8297, 8593, 8881, 9895, 7333, 9614],
'E': [3637, 3401, 1078, 4348, 8205, 8609, 2708, 1827, 1950, 7170, 7452, 9307],
'F': [5997, 4045, 4316, 3878, 5933, 3332, 2305, 5824, 7763, 3065, 4683, 2951],
'G': [8307, 1983, 6213, 3065, 6321, 8103, 9252, 4199, 2435, 7211, 2780, 6253]
})
y = df.Province
data = df.drop(columns='Province').values
x = df.drop(columns='Province').columns
plt.figure(figsize=(8,6))
# 热力图
plt.imshow(data,cmap='Blues') # print(plt.colormaps())
# 修改刻度
plt.xticks(range(len(x)),x)
plt.yticks(range(len(y)),y)
# 添加文字
for i in range(len(x)):
for j in range(len(y)):
plt.text(
x=i,
y=j,
s=data[j,i],
ha='center',
va='center',
fontsize=10
)
#颜色条
plt.colorbar()
plt.savefig('matplotlib/img/15.png', bbox_inches='tight')
极坐标图
- 设置projection或者polar好像都是一样的效果
import numpy as np
from matplotlib import pyplot as plt
N = 8
x = np.linspace(0,2*np.pi,N,endpoint=False)
height = np.random.randint(3,15,size=N)
width = 2*np.pi / N
color = np.random.rand(8,3) # 随机颜色
#画图
# polar:极坐标
axes = plt.subplot(111,projection='polar')
axes.bar(x=x,height=height,width=width,bottom=0,color=color)
plt.savefig('matplotlib/img/16.png', bbox_inches='tight')
雷达图
plt.figure(figsize=(5,8))
x = np.linspace(0,2*np.pi,6,endpoint=False)
y = [80,60,90,70,70,100]
# 首尾相连
x = np.concatenate((x,[x[0]]))
y = np.concatenate((y,[y[0]]))
axes = plt.subplot(111,polar=True)
axes.plot(x,y,'o-',lw=2) # 连线
axes.fill(x,y,alpha=0.3) # 填充
#显示刻度
axes.set_rgrids([20,40,60,80,100],fontsize=12)
plt.show()