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()
相关推荐
CCSBRIDGE2 小时前
Magento2项目部署笔记
笔记
亦枫Leonlew3 小时前
微积分复习笔记 Calculus Volume 2 - 5.1 Sequences
笔记·数学·微积分
爱码小白4 小时前
网络编程(王铭东老师)笔记
服务器·网络·笔记
LuH11244 小时前
【论文阅读笔记】Learning to sample
论文阅读·笔记·图形渲染·点云
一棵开花的树,枝芽无限靠近你5 小时前
【PPTist】组件结构设计、主题切换
前端·笔记·学习·编辑器
犬余6 小时前
设计模式之桥接模式:抽象与实现之间的分离艺术
笔记·学习·设计模式·桥接模式
数据爬坡ing7 小时前
小白考研历程:跌跌撞撞,起起伏伏,五个月备战历程!!!
大数据·笔记·考研·数据分析
咖肥猫7 小时前
【ue5学习笔记2】在场景放入一个物体的蓝图输入事件无效?
笔记·学习·ue5
郭尘帅6668 小时前
Ajax学习笔记
笔记·学习·ajax
我叫啥都行9 小时前
计算机基础复习12.23
java·开发语言·笔记·后端·学习