Matplotlib data visualization (4)

1. Display formulas in plots

In Matplotlib, you can use LaTex commands to edit formulas, just add an 'r' in front of the string.

Example 1:

import numpy as np
import matplotlib.pyplot as plt
plt.xlim([1,4])
plt.ylim([1,3])
plt.text(2,2,r'$ \alpha \beta \pi \lambda \omega $',size=20)
plt.title(r'$ \sum_{n=1}^\infty -e^{n\pi} $',fontsize=15)
plt.show()

Result graph:

2. Drawing Text Annotation

When drawing, you can use the text function to add text annotations at the specified position (x, y), or you can use annotate() to implement text annotations with pointers in the graph. The function call format is as follows:

plt.text(x,y,s,fontdict=None,**kwargs)
plt.annotate(s,xy,*args,**kwargs)
#其中,x,y表示显示的文本的坐标位置,s表示显示的字符串

Example 2:

import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False 
%matplotlib inline
fig=plt.figure()
ax1=fig.add_subplot(121)
t=np.arange(0.0,5,0.01)
s=np.sin(2*np.pi*t)
ax1.plot(t,s,lw=2)
bbox=dict(boxstyle='round',fc='white')
plt.annotate('local max',xy=(2.3,1),xytext=(3,1.5),
arrowprops=dict(facecolor='black',edgecolor='red',headwidth=7,width=2),bbox=bbox)
#arrowstyle箭头类型,arrowstyle="->",connectionstyle="arc3"指的是xy与xytext之间的连接类型
bbox_prop=dict(fc='white')
ax1.set_ylabel('Y',fontsize=12)
ax1.set_xlabel('X',fontsize=12)
ax1.set_ylim(-2,2)
ax1.text(1,1.2,'max',fontsize=18)
ax1.text(1.2,-1.8,'$y=sin(2*np.pi*t)$',bbox=bbox,rotation=10,alpha=0.8)
ax2=fig.add_subplot(122)
x=np.linspace(0,10,200)
y=np.sin(x)
ax2.plot(x,y,linestyle='-.',color='purple')
ax2.annotate(s='Here I am',xy=(4.8,np.sin(4.8)),xytext=(3.7,-0.2),weight='bold',color='k',
             arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'),
            bbox=dict(boxstyle='round,pad=0.5',fc='yellow', ec='k',lw=1 ,alpha=0.8))
ax2.set_ylim(-1.5,1.5)
ax2.set_xlim(0,10)
bbox=dict(boxstyle='round',ec='red',fc='white')
ax2.text(6,-1.9,'$y=sin(x)$',bbox=dict(boxstyle='square',facecolor='white',ec='black'))
ax2.grid(ls=":",color='gray',alpha=0.5)
#设置水印(带方框的水印)
ax2.text(4.5,1,'NWNU',fontsize=15,alpha=0.3,color='gray',bbox=dict(fc="white",boxstyle='round',edgecolor='gray',alpha=0.3))
plt.show()

 Result graph:


Guess you like

Origin blog.csdn.net/m0_64087341/article/details/132364342