对Python matplotlib 的使用进行了总结注释,学习内容来自B站up主莫烦Python,推荐!!!
代码:
import matplotlib.pyplot as plt
import numpy as np
# 不同的方法解决图例问题
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.xlim(-1, 2)
plt.ylim(-2, 3)
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1, 0, 1, 2], [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
l1, = plt.plot(x, y2, label='up')
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='down')
# plt.legend()
# loc 是legend放的位置,取值best,upper right, upper left, center right,center left, lower right, lower left
plt.legend(handles=[l1, l2], labels=['aaa', 'bbb'], loc='best')
plt.show()
# 在图片中添加注解Annotation
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0, y0, s=50, color='b') # 设置点的参数,s为大小
plt.plot([x0, x0], [0, y0], 'k--', lw=2.5) # 两个点之间画一条线
# method 1
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), color='red', xycoords='data', xytext=(+30, -30), textcoords='offset points'
, fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2', color='red'))
# 参数解释:xy表示注释的起始参考位置点, xycoords表示坐标是基于data这个数据的,xytext表示偏移量,基于xy向右偏移30,向下偏移30
# arrowprops用于设置箭头的信息:arc3, rad=.2表示弯曲弧度
# method 2
plt.text(-3.2, 3, r'$This\ is\ the\ some\ text.\ \mu\ \sigma_i\ \alpha_t$', fontdict={'size': 16, 'color': 'orange'})
plt.show()
代码运行结果:
# tick能见度,处理标签被挡住的问题
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
plt.plot(x, y, linewidth=20, zorder=1)
plt.xlim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 坐标轴刻度的label设置参数
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
# label有背景色bbox, edgecolor边的颜色,alpha用于设置透明度
label.set_bbox(dict(facecolor='w', edgecolor='None', alpha=0.7))
plt.show()
代码运行结果: