一. 简单使用
1. 代码
import matplotlib.pyplot as plt
import numpy as np
"""
此段代码介绍了matplotlib模块的简单应用
"""
x = np.linspace(-1,1,50)
print(x)
print(x.ctypes)
# y = 2*x + 1
y = x**2 + 1
plt.plot(x,y) # 按照x,y画出直线
plt.show() # 展示出来
运行结果:
二. figure讲解
1. 代码
import matplotlib.pyplot as plt
import numpy as np
"""
此段代码讲述的是figure的用法
"""
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure() # 这是第一张figure,下面出现的都会在第一张figure上
plt.plot(x, y1)
plt.figure(num=3, figsize=(8, 5)) # 这是第二章figure,下面出现的都会在第二章figure上
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=5, linestyle='--') # color是颜色,linewidth是线的宽度,linestyle是线的类型,这里我们定义为虚线
plt.show()
运行结果:
三. 坐标轴设置
1. 代码
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.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# set x limits
plt.xlim((-1, 2)) # x轴设置范围(-1,2)
plt.ylim((-2, 3)) # y轴设置范围(-2,3)
plt.xlabel('I am x') # 给x轴打上标签
plt.ylabel('I am y') # 给y轴打上标签
# set new sticks
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks) # 在轴上显示出我们想要的东西,比如这里就会在轴上显示出(-1,2)的5个点
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()
运行结果:
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.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=5.0, linestyle='--')
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# set new ticks
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])
# to use '$ $' for math text and nice looking, e.g. '$\pi$'
# gca = 'get current axis'获得当前的轴
ax = plt.gca()
ax.spines['right'].set_color('none') # 将右边和上面的黑色边界去掉
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
# 能够接受的参数: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
ax.spines['bottom'].set_position(('data', 0)) # 将x轴的原点设置在y为0的地方
# the 1st is in 'outward' | 'axes' | 'data'
# axes: percentage of y axis
# data: depend on y data
ax.yaxis.set_ticks_position('left')
# 能够接受的参数: [ 'left' | 'right' | 'both' | 'default' | 'none' ]
ax.spines['left'].set_position(('data',0)) # 将y轴设置在x为0的地方,如果我们不这么设置,y轴应该就是在-1的位置。
plt.show()