导入matplotlib库
import matplotlib.pyplot as plt
import numpy as np
基本用法
1、制作所需图像及设置其线条的颜色,间隔,形式,以及为该线条命名: plt.plot()
2、显示图像:plt.show()
最基本应用案例:
x = np.linspace(-9,6,45)
y= 2*x+1
plt.plot(x,y)
plt.show()
figure图像
运用:
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x, y1)
plt.figure(num=3, figsize=(8, 5),)
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()
设置坐标轴
plt.xlim((-5,8)) #设置x轴的取值范围
plt.ylim((-9,9)) #设置y轴的取值范围
plt.xlabel('i an x') #对于x轴的描述
plt.ylabel('i am y') #对于y轴的描述
new_ticks = np.linspace(-5,5,20)
print(new_ticks)
plt.xticks(new_ticks) #设置x轴的的刻度
plt.yticks([-5,-1,0,1,5],['really bad','bad','normal','good','really good'])
# 设置y轴的刻度,本次是将原-5处改名为really bad等
# 改变你所需的字体:如在bad前后都填加¥符号,可以将其改变为机械可以读取的数字形式的字体,如其中有空格读取不了,需要在空格前加转字符\符号
# \alpha可以表示为数学形式的阿尔法
ax = plt.gca() #将坐标轴拿出来
ax.spines['right'].set_color('none') #将右边的坐标轴的颜色设置为没有
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') #用bottom表示x坐标轴(名称)
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_positin(('data',0)) #将bottom对齐到0的位置 除了data(定位到具体的数字)还有axes(定位到百分比的地方)和outward
ax.spines['left'].set_position(('data',0)) #将left对齐到0的位置
legend图例
plt.legend(handles=[l1,l2],labels=['aaa','bbb'],loc='best')
#设置图例的的名字(labels)和所在位置(loc),如不想显示某一图例,比方说l2的图例只需在labels和handles中将其删除即可 eg:handles[l1]labels['aaa']就只显示l1的图例
annotation标注注解
*scatter设置某一点的状态
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
plt.scatter([x0, ], [y0, ], s=50, color='b')
1、方法一:plt.annotate()
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
#设置标注的内容,要标注东西所在的位置既坐标(用xycoords='data'表示所标注点的位置是在坐标轴中的位置),标注的内容所在的位置,字体的大小,还可以设置箭头
2、方法二:
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
#设置文字标注的字体,颜色等