matplotlib的基础操作
1. 绘制折线图
一条折线图
import matplotlib.pyplot as plt
import numpy as np
# plt.plot(x, y) # 绘制折线图
x = np.arange(2, 20)
y = 2 * x + np.random.randint(5, 20, 18)
plt.plot(x, y) # 正常显示
plt.show()
plt.plot(x, y, '*-', color='r') # 星点显示
plt.show()
plt.plot(x, y, '+-') # +号显示
plt.show()
多条折线图
# 多条折线显示
x = np.linspace(0, 1, 100)
y1 = np.power(x, 0.5)
y2 = x
y3 = np.power(x, 1.5)
plt.plot(x, y1, label='y=x^0.5')
plt.plot(x, y2, label='y=x')
plt.plot(x, y3, label='y=x^1.5')
plt.legend() # 显示图例
plt.xlabel('r') # x轴名称
plt.ylabel('s') # y轴名称
plt.grid() # 显示网格4
plt.xlim([0, 1.2]) # 限制x轴的范围
plt.ylim([0, 1.3]) # 限制y轴的范围
plt.show()
2. 绘制直方图
hist的参数非常多,但常用的有以下6个,只有第一个是必须的,后面5个可选
x: 作直方图所要用的数据,必须是一维数组。多维数组可以先进行扁平化再作图
bins: 直方图的柱数,可选项,默认为10
a = np.random.randint(0, 101, 1000)
plt.hist(a, rwidth=0.7, color='g')
plt.show()
b = np.arange(0, 100, 2)
plt.hist(a, bins=b, rwidth=0.8, color='gray')
plt.show()
完整代码
import matplotlib.pyplot as plt
import numpy as np
# plt.plot(x, y) # 绘制折线图
x = np.arange(2, 20)
y = 2 * x + np.random.randint(5, 20, 18)
plt.plot(x, y) # 正常显示
plt.show()
plt.plot(x, y, '*-', color='r') # 星点显示
plt.show()
plt.plot(x, y, '+-') # +号显示
plt.show()
# 多条折线显示
x = np.linspace(0, 1, 100)
y1 = np.power(x, 0.5)
y2 = x
y3 = np.power(x, 1.5)
plt.plot(x, y1, label='y=x^0.5')
plt.plot(x, y2, label='y=x')
plt.plot(x, y3, label='y=x^1.5')
plt.legend() # 显示图例
plt.xlabel('r') # x轴名称
plt.ylabel('s') # y轴名称
plt.grid() # 显示网格4
plt.xlim([0, 1.2]) # 限制x轴的范围
plt.ylim([0, 1.3]) # 限制y轴的范围
plt.show()
# plt.hist(array) # 绘制直方图
"""
hist的参数非常多,但常用的有以下6个,只有第一个是必须的,后面5个可选
x: 作直方图所要用的数据,必须是一维数组。多维数组可以先进行扁平化再作图
bins: 直方图的柱数,可选项,默认为10
"""
a = np.random.randint(0, 101, 1000)
plt.hist(a, rwidth=0.7, color='g')
plt.show()
b = np.arange(0, 100, 2)
plt.hist(a, bins=b, rwidth=0.8, color='gray')
plt.show()