Reprinted from: Matplotlib data visualization from entry to mastery
table of Contents
Third, how to add annotations-annotate
Fourth, how to set the axis name-xlabel / ylabel
Five, how to add a legend-legend
Seven, how to switch the line style-marker
Eight, how to display mathematical formulas-mathtext
Nine, how to display the grid-grid
Ten, how to adjust the axis scale -locator_params
11. How to adjust the coordinate axis range-axis / xlim / ylim
Twelve, how to adjust the date adaptive -autofmt_xdate
Thirteen, how to add coordinate axis-twinx
Fourteen, how to fill the area -fill / fill_beween
Fifteen, how to draw a filled shape-matplotlib.patche
16. How to switch styles-plt.style.use
Foreword
Matplotlib is a powerful visualization tool. It is a Python drawing library. It can be used with NumPy. It provides an effective MatLab open source alternative. It is really not too fragrant for drawing!
The following summarizes commonly used operations and techniques to ensure that the code of each example can be directly used to run. For more information, please check the official website
1. How to add a title
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,10)
plt.title('chenqionghe')
plt.plot(x,x*x)
plt.show()
Second, how to add text-text
Official document
Set the coordinates and text
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-10,11,1)
y=x*x
plt.plot(x,y)
plt.title('chenqionghe')
plt.text(-2.5,30,'function y=x*x')
plt.show()
Third, how to add annotations-annotate
- xy: coordinate point for remarks
- xytext: the coordinates of the memo text (default is xy position)
- arrowprops: draw an arrow between xy and xytext
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-10,11,1)
y=x*x
plt.title('chenqionghe')
plt.plot(x,y)
plt.annotate('chenqionghe is a kind man',xy=(0,1),xytext=(-4,20),arrowprops={'headwidth':10,'facecolor':'r'})
plt.show()
Fourth, how to set the axis name-xlabel / ylabel
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,20)
plt.xlabel('chenqionghe')
plt.ylabel('muscle')
plt.plot(x,x*x)
plt.show()
Five, how to add a legend-legend
import numpy as np
import matplotlib.pyplot as plt
plt.plot(x,x)
plt.plot(x,x*2)
plt.plot(x,x*3)
plt.plot(x,x*4)
# 直接传入legend
plt.legend(['chenqionghe','light','weight','baby'])
plt.show()
Six, how to adjust the color
Pass color parameters, support the following methods
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,5)
#颜色的几种方式
plt.plot(x,color='g')
plt.plot(x+1,color='0.5')
plt.plot(x+2,color='#FF00FF')
plt.plot(x+3,color=(0.1,0.2,0.3))
plt.show()
Seven, how to switch the line style-marker
Check the official documentation for more styles
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,5)
plt.plot(x,marker='o')
plt.plot(x+1,marker='>')
plt.plot(x+2,marker='s')
plt.show()
Eight, how to display mathematical formulas-mathtext
All formula symbols have the
following format:
as the start and end symbols, such as the start and end symbols, such as \ omega $, the symbols in the formula will be parsed in the middle
import numpy as np
import matplotlib.pyplot as plt
plt.title('chenqionghe')
plt.xlim([1,8])
plt.ylim([1,5])
plt.text(2,4,r'$ \alpha \beta \pi \lambda \omega $',size=25)
plt.text(4,4,r'$ \sin(0)=\cos(\frac{\pi}{2}) $',size=25)
plt.text(2,2,r'$ \lim_{x \rightarrow y} \frac{1}{x^3} $',size=25)
plt.text(4,2,r'$ \sqrt[4]{x}=\sqrt{y} $',size=25)
plt.show()
Nine, how to display the grid-grid
import numpy as np
import matplotlib.pyplot as plt
x='chenqionghe','light','weigtht','baby'
y=[15,30,45,10]
plt.grid()
# 也可以设置颜色、线条宽度、线条样式
# plt.grid(color='g',linewidth='1',linestyle='-.')
plt.plot(x,y)
plt.show()
Ten, how to adjust the axis scale -locator_params
Adjust the x-axis and y-axis at the same time: plt.locator_params (nbins = 20)
only adjust the x-axis: plt.locator_params ('' x ', nbins = 20)
only adjust the y-axis: plt.locator_params (' 'y', nbins = 20)
Sample code
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,30,1)
plt.plot(x,x)
# x轴和y轴分别显示20个
plt.locator_params(nbins=20)
plt.show()
11. How to adjust the coordinate axis range-axis / xlim / ylim
- axis: [0,5,0,10], x from 0 to 5, y from 0 to 10
- xlim: the corresponding parameters are xmin and xmax, which can adjust the maximum and minimum respectively
- ylim: Same as xlim usage
Sample code
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,30,1)
plt.plot(x,x*x)
#显示坐标轴,plt.axis(),4个数字分别代表x轴和y轴的最小坐标,最大坐标
#调整x为10到25
plt.xlim(xmin=10,xmax=25)
plt.plot(x,x*x)
plt.show()
Twelve, how to adjust the date adaptive -autofmt_xdate
Sometimes the display date will overlap, which is very unfriendly. Call plt.gcf (). Autofmt_xdate (), the angle will be adjusted automatically
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x=pd.date_range('2020/01/01',periods=30)
y=np.arange(0,30,1)
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()
Thirteen, how to add coordinate axis-twinx
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,20)
y1=x*x
y2=np.log(x)
plt.plot(x,y1)
# 添加一个坐标轴,默认0到1
plt.twinx()
plt.plot(x,y2,'r')
plt.show()
Fourteen, how to fill the area -fill / fill_beween
fill function area
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
plt.plot(x,y1)
plt.plot(x,y2)
plt.fill(x,y1,'g')
plt.fill(x,y2,'r')
plt.title('chenqionghe')
plt.show()
fill_beween fill function intersection area
import numpy as np
import matplotlib.pyplot as plt
plt.title('chenqionghe')
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
plt.plot(x,y1)
plt.plot(x,y2)
plt.fill_between(x,y1,y2,where=y1>y2,interpolate=True)
plt.show()
Fifteen, how to draw a filled shape-matplotlib.patche
Refer to official documents for various shapes
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mptaches
xy1=np.array([0.2,0.2])
xy2=np.array([0.2,0.8])
xy3=np.array([0.8,0.2])
xy4=np.array([0.8,0.8])
fig,ax=plt.subplots()
#圆形,指定坐标和半径
circle=mptaches.Circle(xy1,0.15)
ax.add_patch(circle)
#长方形
rect=mptaches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)
#多边形
polygon=mptaches.RegularPolygon(xy3,6,0.1,color='g')
ax.add_patch(polygon)
# 椭圆
ellipse=mptaches.Ellipse(xy4,0.4,0.2,color='c')
ax.add_patch(ellipse)
ax.axis('equal')
plt.show()
16. How to switch styles-plt.style.use
matplotlib supports multiple styles, you can switch styles through plt.style.use, for example:
plt.style.use('ggplot')
Enter plt.style.available
to view all styles
plt.style.available
['seaborn-dark',
'seaborn-darkgrid',
'seaborn-ticks',
'fivethirtyeight',
'seaborn-whitegrid',
'classic',
'_classic_test',
'fast',
'seaborn-talk',
'seaborn-dark-palette',
'seaborn-bright',
'seaborn-pastel',
'grayscale',
'seaborn-notebook',
'ggplot',
'seaborn-colorblind',
'seaborn-muted',
'seaborn',
'Solarize_Light2',
'seaborn-paper',
'bmh',
'tableau-colorblind10',
'seaborn-white',
'dark_background',
'seaborn-poster',
'seaborn-deep']
Sample code
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mptaches
plt.style.use('ggplot')
# 新建4个子图
fig,axes=plt.subplots(2,2)
ax1,ax2,ax3,ax4=axes.ravel()
# 第一个图
x,y=np.random.normal(size=(2,100))
ax1.plot(x,y,'o')
# 第二个图
x=np.arange(0,10)
y=np.arange(0,10)
colors=plt.rcParams['axes.prop_cycle']
length=np.linspace(0,10,len(colors))
for s in length:
ax2.plot(x,y+s,'-')
# 第三个图
x=np.arange(5)
y1,y2,y3=np.random.randint(1,25,size=(3,5))
width=0.25
ax3.bar(x,y1,width)
ax3.bar(x+width,y2,width)
ax3.bar(x+2*width,y3,width)
# 第四个图
for i,color in enumerate(colors):
xy=np.random.normal(size=2)
ax4.add_patch(plt.Circle(xy,radius=0.3,color=color['color']))
ax4.axis('equal')
plt.show()
Default style
After switching to ggplot style
More tips
At this point, the commonly used techniques are almost the same. It is recommended that you run it yourself to deepen the impression. For more techniques, you can check the following article