malplotlib绘图笔记

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import random
# 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   # 显示负号

单图

折线图

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')

在这里插入图片描述

柱状图

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()

在这里插入图片描述

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()
#x=range(len(name))
#plt.bar([i+0.3 for i in x],y2,width=0.3)
#设置列表range(len(name)),直接使用np.arange(len(name))转为数组更方便

在这里插入图片描述

直方图

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()

在这里插入图片描述

饼图

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()

在这里插入图片描述

散点图

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()

在这里插入图片描述

等高线

def f(x,y):
    # the height function
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
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

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 图像

from mpl_toolkits.mplot3d import Axes3D
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()

子图

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

图中图

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()

在这里插入图片描述

多坐标轴

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

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.加标注

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

from matplotlib import animation
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()

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值