matplotlib使用笔记

1. 关闭坐标刻度,坐标轴不可见

plt.xticks([])
plt.yticks([])
plt.axis('off')
frame = plt.gca()
# y 轴不可见
frame.axes.get_yaxis().set_visible(False)
# x 轴不可见
frame.axes.get_xaxis().set_visible(False)

注意,类似的这些操作若想起作用,需要将其置于 plt.show() 之前,plt.imshow() 之后。

2. 保存矢量图

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x1 = np.random.uniform(-10, 10, size=20)
x2 = np.random.uniform(-10, 10, size=20)
#print(x1)
#print(x2)
number = []
x11 = []
x12 = []
for i in range(20):
    number.append(i+1)
    x11.append(i+1)
    x12.append(i+1)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(number, x1, 'bo', markersize=20,label='a')  # blue circle with size 20
plt.plot(number, x2, 'ro', ms=10,label='b')  # ms is just an alias for markersize
 
lgnd=plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0,numpoints=1,fontsize=10)
lgnd.legendHandles[0]._legmarker.set_markersize(16)
lgnd.legendHandles[1]._legmarker.set_markersize(10)
 
plt.show()
 
fig.savefig('scatter.eps',dpi=600,format='eps')

3. 双y轴

import numpy as np
import matplotlib.pyplot as plt
**#设置随机数**
time=np.arange(10)
temp=np.random.random(10)*30
Swdown=np.random.random(10)*100-10
Rn=np.random.random(10)*100-10

fig=plt.figure(figsize=(10,8))
ax=fig.add_subplot(1,1,1)
ax.plot(time,Swdown,'-',alpha=.5,label='Swdown')
ax.plot(time,Rn,'-',label='Rn')
ax2=ax.twinx()   ****#关键一步,建立ax2子图与ax同x轴****
ax2.plot(time,temp,'-r',label='temp')
ax.grid()
ax.set_xlabel('Time(h)')
ax.set_ylabel(r'Radiation($MJ\,m^{-2}\,d^{-1}$)')
ax2.set_ylabel(r'Temperature($^\circ$C)')
ax2.set_ylim(0,35)
ax.set_ylim(-20,100)

4. 利用matplotlib.animation动画显示

5. 局部放大图

5.1 简单粗暴法

利用plt.axis设置局部坐标,可以实现局部细节放大。但是,有时候我们想把局部放大的子图放在母图中。这种方法就无法做到了。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch

def f1(t):
    return np.exp(-t)*np.cos(2*np.pi*t)

def f11(t):
    return np.exp(-t)*np.cos(2*np.pi*t+0.2)

def f111(t):
    return np.exp(-t+0.2)*np.cos(2*np.pi*t)

t = np.arange(0.0,5.0,0.02)

plt.figure(figsize=(16,8),dpi=98)
p1 = plt.subplot(121,aspect=5/2.5)
p2 = plt.subplot(122,aspect=0.5/0.05)

label_f0 = r"$f(t)=e^{-t+\alpha} \cos (2 \pi t+\beta)$"
label_f1 = r"$\alpha=0,\beta=0$"
label_f11 = r"$\alpha=0,\beta=0.2$"
label_f111 = r"$\alpha=0.2,\beta=0$"

p1.plot(t,f1(t),"g",label=label_f1,linewidth=2)
p1.plot(t,f11(t),"r-.",label=label_f11,linewidth=2)
p1.plot(t,f111(t),"b:",label=label_f111,linewidth=2)
p2.plot(t,f1(t),"g",label=label_f1,linewidth=2)
p2.plot(t,f11(t),"r-.",label=label_f11,linewidth=2)
p2.plot(t,f111(t),"b:",label=label_f111,linewidth=2)

p1.axis([0.0,5.01,-1.0,1.5])

p1.set_ylabel("v",fontsize=14)
p1.set_xlabel("t",fontsize=14)
#p1.set_title("A simple example",fontsize=18)
p1.grid(True)
p1.legend()

tx = 0.5
ty = 0.9
p1.text(tx,ty,label_f0,fontsize=15,verticalalignment="top",horizontalalignment="left")

p2.axis([4,4.5,-0.02,0.03])
p2.set_ylabel("v",fontsize=14)
p2.set_xlabel("t",fontsize=14)
p2.grid(True)
p2.legend()

# plot the box
tx0 = 4
tx1 = 4.5
ty0 = -0.1
ty1 = 0.1
sx = [tx0,tx1,tx1,tx0,tx0]
sy = [ty0,ty0,ty1,ty1,ty0]
p1.plot(sx,sy,"purple")

# plot patch lines
xy=(4.45,0.09)
xy2 = (4.02,0.026)
con = ConnectionPatch(xyA=xy2,xyB=xy,coordsA="data",coordsB="data",
        axesA=p2,axesB=p1)
p2.add_artist(con)

xy = (4.45,-0.09)
xy2 = (4.02,-0.018)
con = ConnectionPatch(xyA=xy2,xyB=xy,coordsA="data",coordsB="data",
        axesA=p2,axesB=p1)
p2.add_artist(con)

plt.show()

在这里插入图片描述

5.2 zoomed_inset_axes and mark_inset

该方法能够实现母图内放局部图,但是却无法调整局部的长宽比。这导致很多时候会出现问题。

import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

import numpy as np

fig, ax = plt.subplots(figsize=[5, 4])
x = range(-20,20)
y = np.sin(x)
ax.plot(x,y)
extent = [-3, 4, -4, 3]



axins = zoomed_inset_axes(ax, 2, loc=1)  # zoom = 6
axins.plot(x,y)

# sub region of the original image
x1, x2, y1, y2 = 2.5, 7.5, -0.5, 0
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
# fix the number of ticks on the inset axes
axins.yaxis.get_major_locator().set_params(nbins=10)
axins.xaxis.get_major_locator().set_params(nbins=10)

plt.xticks(visible=True)
plt.yticks(visible=True)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

plt.draw()
plt.show()

在这里插入图片描述

5.3 inset_axes

通过Inset_axes函数可以实现母图内显示局部图,并随意调整局部图的长与宽,非常人性化。但是,该方法也存在一个问题:局部图放置的位置只有规定的9种,也即中间、上、下、左、右、左上、左下、右上、右下。有时候会出现遮挡母图,这时候就很蛋疼,又不能微调。(目前发现这个问题,也可能是我没找到相应的函数,以后解决了再补充。)

from mpl_toolkits.axes_grid.inset_locator import inset_axes

a1 = [44.1828, 36.5252, 6.9678, 0.0122]
a2 = [1.3079, 0.8202, 0.7755, 0.2789]
a3 = [0.0112, 0.0110, 0.0103, 0.0117]
scale_ls = range(4)
index_ls = ['$S_{1}$','$S_{2}}$','$S_{3}$','$S_{4}$']
fig=plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1)
ax.plot(scale_ls, a1,marker='s', c='dodgerblue',ls = '--',lw=3,markersize=10)
ax.plot(scale_ls, a2,marker='h', c='gold',ls = '-.',lw=3,markersize=10)
ax.plot(scale_ls, a3,marker='o', c='deeppink',ls = '-',lw=3,markersize=10)
# ax.set_xticks([])
# ax.set_yticks([])
plt.xticks(scale_ls,index_ls)
ax.tick_params(labelsize=20)
ax.grid()

scale_ls1 = range(3)
index_ls1 = ['$S_{1}$','$S_{2}}$','$S_{3}$']

axins = inset_axes(ax, width="30%", height="30%",loc=1)
axins.plot(scale_ls, a1,marker='s', c='dodgerblue',ls = '--',lw=3,markersize=10)
axins.plot(scale_ls, a2,marker='h', c='gold',ls = '-.',lw=3,markersize=10)
axins.plot(scale_ls, a3,marker='o', c='deeppink',ls = '-',lw=3,markersize=10)
axins.axis([0, 2, -0.1, 1.5])
plt.xticks(scale_ls1,index_ls1)
axins.tick_params(labelsize=20)
axins.grid()
plt.show()

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

windSeS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值