malplotlib绘图笔记

python 复制代码
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import random
python 复制代码
# params={'font.family':'DeJavu Serif',
#         'font.serif':'Times New Roman',
#         'font.style':'normal',
#         'font.weight':'normal' #or 'blod'
#         }
import matplotlib.font_manager

mpl.rcParams['font.family']='DejaVu serif'
mpl.rcParams['font.serif']='Times New Roman'
mpl.rcParams['axes.unicode_minus'] = False   # 显示负号

params={'font.family':'DejaVu Sans',
        'font.sans-serif':'Arial',
        'font.style':'normal',
        'font.weight':'normal' #or 'blod'
        }
plt.rcParams.update(params)
plt.rcParams['axes.unicode_minus'] = False   # 显示负号

单图

折线图

python 复制代码
plt.figure(figsize=(5,3.8),dpi=60)

x = range(60)
y = [random.uniform(15,18) for i in range(60)]
y1 = [random.uniform(5,8) for i in range(60)]

plt.plot(x,y,label='Shanghai')
plt.plot(x,y1,color='r',linestyle='--',label='Beijing')

#轴刻度
x_ch = ['11:{:02d}'.format(i) for i in x]
plt.xticks(x[::5],x_ch[::5],fontsize=6)

y_ticks=range(40)
plt.yticks(y_ticks[::5],fontsize=6)

#轴信息
plt.xlabel('time',fontsize=8)
plt.ylabel('temperature',fontsize=8)
plt.title('Temprature 11:00-12:00',fontsize=10)

plt.legend(loc=0,fontsize=8)
# plt.legend(loc=2, frameon=False, fontsize=7, bbox_to_anchor=(0.0,1.025))

plt.show()

matplotlib.rc('pdf', fonttype=42)
plt.savefig('RMSE_1010.pdf',format='pdf',bbox_inches='tight')
plt.rcParams['svg.fonttype'] = 'none'
plt.savefig('RMSE_1010.svg',format='svg',bbox_inches='tight')

柱状图

python 复制代码
plt.figure(figsize=(5,3.8),dpi=60)

name=['A','B','C','D']
y = [3,6,5,8]
x = np.arange(len(name))

plt.bar(x,y,width=0.3,color=['r','g','b','y'])
plt.xticks(x,name,fontsize=6)

y_ticks=np.arange(0,10)
plt.yticks(y_ticks[::2],fontsize=6)

plt.show()
python 复制代码
plt.figure(figsize=(5,3.8),dpi=60)

name=['A','B','C','D']
y1 = [3,6,5,8]
y2 = [7,8,4,2]
x = np.arange(len(name))
bar_width=0.3
plt.bar(x,y1,width=bar_width,facecolor='r',edgecolor='white',label='BJ')
plt.bar(x+bar_width,y2,width=bar_width,facecolor='g',edgecolor='white',label='SH')
plt.xticks(x+bar_width/2,name,fontsize=6)
for x,y in zip(x,y1):
    # ha: horizontal alignment
    # va: vertical alignment
    plt.text(x,y+0.05,'%.2f'%y,ha='center',va='bottom')

y_ticks=np.arange(0,10)
plt.yticks(y_ticks[::2],fontsize=6)

plt.legend(loc=0,fontsize=8)
plt.show()
python 复制代码
#x=range(len(name))
#plt.bar([i+0.3 for i in x],y2,width=0.3)
#设置列表range(len(name)),直接使用np.arange(len(name))转为数组更方便

直方图

python 复制代码
plt.figure(figsize=(5,2.8),dpi=60)
score = [x if x <=100 else 100 for x in np.random.randn(200)*10+80]
plt.hist(score,bins=20,density=True)
plt.grid(True,linestyle='--',alpha=0.5)
plt.show()

饼图

python 复制代码
plt.figure(figsize=(5,2.8),dpi=60)
x=[50,60,70]
name=['A','B','C']
plt.pie(x,labels=name,autopct='%.2f%%')
plt.axis('equal')
plt.legend(loc=0)
plt.show()

散点图

python 复制代码
x = np.random.normal(0,1,1000)
y = np.random.normal(0,1,1000)
z = np.arctan2(x,y) #for color value

plt.figure(figsize=(5,2.8),dpi=60)

plt.scatter(x,y,s=50,c=z,alpha=0.5)
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
plt.xticks([])
plt.yticks([])
plt.show()

等高线

python 复制代码
def f(x,y):
    # the height function
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
python 复制代码
x = np.linspace(-3,3,201)
y = np.linspace(-3,3,201)
X,Y = np.meshgrid(x,y)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
C=plt.contour(X,Y,f(X,Y),8,colors='black',linewidths=0.5)
plt.clabel(C,inline=True,fontsize=10)
plt.show()

图像 image data

python 复制代码
a = np.random.random_sample(25).reshape((5,5))
plt.imshow(a,interpolation='nearest',cmap='bone',origin='upper')
plt.colorbar(shrink=0.9)
plt.show()

3D 图像

python 复制代码
from mpl_toolkits.mplot3d import Axes3D
python 复制代码
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4,4,0.25)
Y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)
R = np.sqrt(X**2+Y**2)

#high value
Z = np.sin(R)

ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)
plt.show()

子图

python 复制代码
fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(10,5),dpi=60)

x = range(60)
y = [random.uniform(15,18) for i in range(60)]
y1 = [random.uniform(5,8) for i in range(60)]

ax[0].plot(x,y,label='Shanghai')
ax[1].plot(x,y1,color='r',linestyle='--',label='Beijing')

#对每个坐标系做处理

#轴刻度
x_ch = ['11:{:02d}'.format(i) for i in x]
ax[0].set_xticks(x[::5])                      ### sets only the positions
ax[0].set_xticklabels(x_ch[::5],fontsize=3)  ### set ticklabel and fontsize  ax.tick_params()

y_ticks=range(40)
ax[0].set_yticks(y_ticks[::5])
ax[0].set_yticklabels(y_ticks[::5],fontsize=3)

#轴信息
ax[0].set_xlabel('time',fontsize=3)
ax[0].set_ylabel('temperature',fontsize=3)

ax[0].set_title('Temprature 11:00-12:00',fontsize=10)
ax[0].legend(loc=0,fontsize=8)

fig.tight_layout()
plt.show()

mark

  1. In those cases the easiest way to set the fontsize is to use .tick_params

    ref: https://github.com/matplotlib/matplotlib/issues/12318

  2. matplotlib.pyplot.subplots_adjust() function reshape the design of the subplot by changing its positions.

  3. matplotlib.pyplot.tight_layout() function adjusts the subplots so it fits into the figure area perfectly.

    fig.tight_layout()

    plt.show()

    ref:https://pythonguides.com/matplotlib-subplots_adjust/?msclkid=1d6c7de8b32411ecb78001291c5b9e9f

图中图

python 复制代码
fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,4,7,2,5,8,6]

#left,bottom, width, height = 0.1,0.1,0.8,0.8 #都是百分比
left,bottom, width, height = 0.1,0.1,0.8,0.8
ax1 = fig.add_axes([left,bottom, width, height])
ax1.plot(x,y)
ax1.set_title('title')


left,bottom, width, height = 0.2,0.6,0.25,0.25
ax2 = fig.add_axes([left,bottom, width, height])
ax2.plot(x,y,'r:')
ax2.set_title('inside 1')


left,bottom, width, height = 0.6,0.2,0.25,0.25
plt.axes([left,bottom, width, height]) #这种方式,以下的脚步都只针对这个坐标系
plt.plot(x,y,'bo')
plt.title('inside 2')

plt.show()

多坐标轴

python 复制代码
x = np.arange(0,5,0.5)
y1 = 0.5*x**2
y2 = -y1

fig,ax1= plt.subplots()
ax1.plot(x,y1,'g-')
ax1.set_ylabel("data y1",color='g')



ax2 = ax1.twinx()
ax2.plot(x,y2,'r--')
ax2.set_ylabel('data y2',color='r')

plt.show()

微调

1.设置轴

2.自定义legend

python 复制代码
plt.figure(figsize=(5,3.8),dpi=100)

x = range(60)
y = [random.uniform(15,18) for i in range(60)]
y1 = [random.uniform(5,8) for i in range(60)]

l1, = plt.plot(x,y,label='Shanghai')
l2, = plt.plot(x,y1,color='r',linestyle='--',label='Beijing')

##gca='get current axis'
ax=plt.gca()
#边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',10))
ax.spines['left'].set_position(('data',10))

#轴信息
plt.xlabel('time',fontsize=8)
plt.ylabel('temperature',fontsize=8)
plt.title('Temprature 11:00-12:00',fontsize=10)

# plt.legend(loc=0,fontsize=8)
plt.legend(handles=[l1,l2,],labels=['SH','BJ'],fontsize=8)
plt.show()

3.加标注

python 复制代码
plt.figure(figsize=(5,3.8),dpi=100)

x = np.linspace(0,2,11)
y = x**2
plt.plot(x,y,label='Shanghai')

x0=1.5
y0=x0**2
plt.scatter(x0,y0,s=50,color='r')
plt.plot([x0,x0],[0,x0**2],'k--',lw=2.0)

#method 1 :annotate
plt.annotate(r'$annotate1$',xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',
            fontsize=10,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))

plt.annotate(r'$annotate2$',xy=(x0,y0),xytext=(2,2),
            fontsize=10,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))


#method 2 :plt.text

plt.text(0.25,3.0,r'$This\ is\ x^2=y$',fontdict={'size':16,'color':'r'})

ax = plt.gca()
plt.text(0.1,0.2, "text", fontsize = 20, transform = ax.transAxes) #相对位置

#轴信息
plt.xlabel('time',fontsize=8)
plt.ylabel('temperature',fontsize=8)
plt.title('Temprature 11:00-12:00',fontsize=10)

# plt.legend(loc=0,fontsize=8)
plt.legend(handles=[l1,l2,],labels=['SH','BJ'],fontsize=8)
plt.show()

动画 Animation

python 复制代码
from matplotlib import animation
python 复制代码
fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))

def animate(i):
    #animation update
    line.set_ydata(np.sin(x+i/10))
    return line,

def init():
    line.set_ydata(np.sin(x))
    return line,

ani = animation.FuncAnimation(fig=fig,func=animate, frames=100,init_func=init, interval=20,blit=False)

plt.show()
相关推荐
非概念30 分钟前
stm32学习笔记----51单片机和stm32单片机的区别
笔记·stm32·单片机·学习·51单片机
青椒大仙KI113 小时前
24/11/13 算法笔记<强化学习> DQN算法
笔记·算法
promise-render3 小时前
npm、yarn、pnpm 切换查看镜像源笔记
前端·笔记·npm
夜流冰3 小时前
知识见闻 - 苹果手机拨号键长按
笔记
IT19959 小时前
Linux笔记-对Linux环境变量的进一步认识(2024-08-09)
linux·运维·笔记·运维开发
TeYiToKu13 小时前
笔记整理—linux驱动开发部分(8)framebuffer类设备
linux·驱动开发·笔记·嵌入式硬件·arm
陈奕迅本讯15 小时前
数据结构-归并排序笔记
数据结构·笔记
猫爪笔记15 小时前
MySQL数据库: 初始MySQL +Navicat (学习笔记)
数据库·笔记·mysql·navicat
sealaugh3215 小时前
aws(学习笔记第十二课) 使用AWS的RDS-MySQL
笔记·学习·aws
dal118网工任子仪15 小时前
xss的过滤和绕过(2)
笔记·学习·计算机网络·网络安全·xss