python绘图—— matplotlib
1.模块导入
from matplotlib import pyplot as plt
from matplotlib import font_manager
import numpy as np
from math import floor,ceil
2.折线图绘制
2.1 设置画布大小
plt.figure(figsize=(20,8),dpi = 72)
2.2画图
x = list(np.arange(1,21))
y = np.random.randint(2,high=10,size=20)
plt.plot(x,y,color = 'red',alpha = 0.9,linestyle = ':',linewidth = 1,
marker = 's',markersize = 5,markeredgecolor = 'r',
markeredgewidth = 2,label = '第一条曲线')
"""linestyle: '-'is solid line, '--' is dashed line, '-.' is dash-dot line, ':' is dotted line
alpha: its range is 0-1
marker: 'o' is circle, '*' is star, '1-4' is tri_direction, 'v', '^', '<', '>', 's', 'P' is add.
label:图例内容
"""
x1 = list(np.arange(1,21))
y1 = np.random.randint(2,high=10,size=20)
plt.plot(x1,y1,color = 'blue',alpha = 0.9,linestyle = ':',linewidth = 1,
marker = 'v',markersize = 5,markeredgecolor = 'b',
markeredgewidth = 1.5,label = '第二条曲线')
2.3 设置显示中文
fp = font_manager.FontProperties(fname = 'C:\Windows\Fonts\simsun.ttc',size = 18)
2.4 设置标题
name = '折线图的标题'
plt.title(name,color = 'r',fontproperties = fp,size = 30)
2.5 设置图例
l = plt.legend(prop = fp,loc = 'upper left',title = 'legend')
2.6 设置坐标轴刻度和刻度标签
ticks_range = range(floor(min(x)),floor(max(x))+1,ceil((max(x)-min(x))/10))
ticks_label = [str(value)+'Kpa' for value in ticks_range]
plt.xticks(ticks_range,ticks_label,fontproperties = fp,rotation = 45,color = 'red')
ticks_range = range(floor(min(y)),floor(max(y))+1,ceil((max(y)-min(y))/10))
ticks_label = [str(value)+'℃' for value in ticks_range]
plt.yticks(ticks_range,ticks_label,fontproperties = fp,rotation = 0,color = 'blue')
2.7 设置坐标轴范围
plt.xlim([-1,21]) #plt.xlim(xmin = -1,xmax = 21)
plt.ylim([0,12])
2.8 设置坐标轴标题
plt.xlabel('个数',fontproperties = fp,horizontalalignment = 'right' )
"""fontsize:可以给一个数字
verticalalignment:’top’, ‘bottom’, ‘center’, ‘baseline’
horizontalalignment:’center’, ‘right’, ‘left’
rotation: ‘vertical’,’horizontal’,’vertical’
"""
plt.ylabel('个数',fontproperties = fp,verticalalignment = 'top' )
2.9 改变坐标轴的默认显示方式
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('black')
ax.spines['left'].set_color('b')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',10)) # position is tuple
ax.spines['bottom'].set_position(('data',5))
2.10 图片保存
plt.savefig('./zx.svg')
plt.show
3 散点图
from matplotlib import pyplot as plt
import numpy as np
from math import floor,ceil
from matplotlib import font_manager
plt.figure(figsize = (20,8),dpi = 72)
fp = font_manager.FontProperties(fname = 'C:\Windows\Fonts\simsun.ttc',size = 18)
x = list(np.arange(1,31))
y = np.random.randint(20,high = 40 ,size = 30)
# 散点图
plt.scatter(x,y,color = 'r',marker = '*',s = 1000,label = '第一类原料油')
"""
s : size of marker
"""
x1 = list(np.arange(1,31))
y1 = np.random.randint(20,high = 40 ,size = 30)
plt.scatter(x1,y1,color = 'b', marker = '1')
plt.legend(prop = fp)
plt.savefig('./sd.svg')
plt.show()
4 条形图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import font_manager
from math import floor,ceil
plt.figure(figsize = (20,8),dpi = 72)
# 加载中文字体
fp = font_manager.FontProperties(fname = 'c:\Windows\Fonts\simsun.ttc',size = 18)
# 准备数据
x = ["数学","语文","英语","化学","物理"]
y = [100,96,95,89,79]
z = [20,50,30,46,28]
# 作条形图
plt.bar(np.arange(len(x)),y,width = 0.3,color = ['r','b','g','black','yellow'])
figbar = plt.bar(np.arange(len(x)),z,width = 0.3,color = 'darkgreen',bottom = y)
# x刻度标签
plt.xticks(np.arange(len(x)),["({})".format(value) for value in x],fontproperties = fp,size = 20)
# 在条形图上加标注 (水平居中)
i = 0
for each in figbar:
height = each.get_height()
plt.text(each.get_x()+each.get_width()/2, height+0.5+y[i],str(height+y[i]),ha = 'center',size = 20)
i += 1
plt.close()
# ****************** 横向条形图 ************************
plt.figure(figsize = (20,10),dpi = 72)
barh = plt.barh(np.arange(len(x)),y,height = 0.3,color = ['r','b','g','black','yellow'])
plt.yticks(np.arange(len(x)),['科目_{}'.format(i) for i in x],fontproperties = fp,rotation = 45)
for each in barh:
width = each.get_width()
plt.text(width,each.get_y()+0.3/2,str(width),va = 'center',size = 20)
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.savefig('./txt.svg')
plt.show()
5 直方图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import font_manager
from math import floor,ceil
ft = font_manager.FontProperties(fname = 'C:\Wondows\Fonts\simsun.ttc',size = 18)
plt.figure(figsize = (20,8),dpi = 72)
data = np.random.randint(120,high = 200,size = 1000000)
# 绘制直方图
distance = 10
number = floor((max(data)-min(data))/distance)
plt.hist(data,number,color = 'r')
plt.grid(linestyle = '--', alpha = 0.5)
6 饼图
from matplotlib import pyplot as plt
from matplotlib import font_manager
import numpy as np
from math import floor,ceil
fp = font_manager.FontProperties(fname = 'C:\Windows\Fonts\simsun.ttc',size = 18)
# 绘制饼图
data = [30,20,50]
patches,l_text,p_text = plt.pie(data,
explode = [0,0.05,0],
colors = ["red","blue","green"],
labels = ['第一类','第二类','第三类'],
labeldistance = 1.1,
autopct = "%1.1f%%",
shadow = False,
startangle = 90,
pctdistance = 0.6
)
"""
data: 为绘制数据
explode: 为各扇形部分突出
colors:
labels: 为各扇形部分标签
labeldistance: 标签距离圆心距离
autopct: 为各部分百分数
shadow: 是否显示阴影
startangle: 开始角度
pctdistance: 百分数距离圆心距离
"""
for i in l_text:
i.set_fontproperties(fp)
for i in p_text:
i.set_fontproperties(fp)
plt.legend(prop = fp,loc = 'upper right',)
plt.show()
7 一图多子图
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import font_manager
from math import ceil,floor
x = np.arange(1,101)
fig = plt.figure(figsize = (20,10),dpi = 72)
fig.add_subplot(2,3,1)
plt.plot(x,x**2)
plt.grid(linestyle = "--", linewidth = 1,alpha = 0.5,color = 'r')
fig.add_subplot(2,3,4)
plt.barh(x,x**3)
by CyrusMay 2022 04 05