matplotlib(1)
matplotlib的使用
下载模块:pip install matplotlib(终端CMD)
官方文档:https://matplotlib.org
导入模块:import matplotlib.pyplot as plt
matplotlib颜色-线条-标记等参数控制:
(1)线条(linestyle):
'-' '--' '-.' ':'
额外设置:linewidth
(2)标记(marker):
'.' '^' 'o' 's' '<' '>' '*' '+' 'x'
额外设置:markersize(标记大小)+标记颜色(mfc)
(3)线条颜色(color):
额外设置:alpha(透明度)
(一)设置标题和文本
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(1000)
fig,ax = plt.subplots()
ax.plot(np.random.rand(10),'-o',linewidth=1,markersize=10,mfc='red',color='green',alpha=0.6)
ax.set_title('plot with watermark')
fig.text(0.75,0.6,'property of MPL',fontsize=25,color='gray',
ha='right',alpha=0.5)
ax.grid()
注释:
ax.set_title()相关参数设置:
string --> 标题文本内容
fontsize --> 字体大小[默认12]
fontweight --> 字体粗细[light|normal|bold|heavy]
loc --> 字体位置[left|center|right]
rotation --> 旋转角度
color --> 字体颜色
alpha --> 透明度
backgroundcolor --> 标题背景色
fig.text()/plt.text()相关参数设置:
x,y --> 位置坐标
string --> 本文内容
fontsize --> 字体大小
va --> 垂直对齐方式[top|center|bottom]
ha --> 水平对齐方式[left|center|right]
注:left(表示本文的左端位于x处) + right(表示本文的右端位于x处)
color --> 字体颜色
alpha --> 透明度
rotation --> 旋转角度
(二)设置标注
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x**2
plt.plot(x,y,'-o',color='gray',mfc='purple',markersize=8)
plt.grid()
for xy in zip(x,y):
plt.annotate('(%s,%s)' %xy,xy=xy,xytext=(-10,10),textcoords='offset points')
plt.show()
注释:
annotate()相关参数设置:
str --> 注释本文内容
xy = (x,y)--> 注释的坐标点
xytext --> 注释文字的坐标位置
(三)设置图例和网格
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
a = np.arange(0,3,0.01)
b = np.exp(a)
c = np.sin(a)*5+np.cos(a)*3-1
fig,ax = plt.subplots()
ax.plot(a,b,'--',color='violet')
ax.plot(a,c,'-',color='lime',lw=2)
plt.grid(linestyle='--',color='gray')
plt.legend(['one','two'],loc='best',fontsize=15,edgecolor='pink',facecolor='silver')
注释:
plt.legend()相关参数设置:
loc --> 图例位置['best'|'upper right'|'upper left'|'lower left'|'lower right'
'center left'|'center right'|'center'|'left'|'right'
'lower center'|'upper center']
fontsize --> 字体大小
edgecolor --> 图例边框颜色
facecolor --> 图例背景颜色
plt.grid()相关参数设置:
linestyle --> 线条类型['-'|'--']
linewidth --> 线条宽度
color --> 线条颜色