导入库
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline
生成数据
#define some data
x = np.linspace(0,10,100) # 100 points starting from 0
mu, sigma = 0, 0.1 # mean and standard deviation
y = np.random.normal(mu, sigma, 100) # creating data of normal distribution
折线数据绘图
plt.plot(x, y)
存储图片
plt.savefig('PlotA.png') # saving images on local machine
自定义轴、标题
# plot (Time Series)
fig, ax = plt.subplots()
ax.plot(x, y, color='red')
ax.grid()
ax.set_xlabel('Time (in Minute)')
ax.set_ylabel(' Stock Price')
ax.set_title(' Stock Price Movement')
饼图绘制
# Pie Chart
import numpy as np
import matplotlib.pyplot as plt
n = 6
Z = np.random.uniform(0,1,n)
plt.pie(Z)
plt.show()
直方图绘制
n1 = np.random.randn(1000)
n2 = np.random.uniform(-1,5,800)
fig, axes = plt.subplots(1, 2, figsize=(10,4)) #One row, Two columns for position of plots
axes[0].hist(n1)
axes[0].set_title("Histogram: Normal Distribution")
axes[0].set_xlim((min(n1), max(n1)))
axes[1].hist(n2)
axes[1].set_title("Histogram: Uniform Distribution")
axes[1].set_xlim((min(n2), max(n2)));
箱型图绘制
# Boxplots
# Create data
np.random.seed(10)
client_1 = np.random.normal(40, 8, 50)
client_2 = np.random.normal(50, 10, 50)
client_3 = np.random.normal(50, 15, 50)
client_4 = np.random.normal(60, 25, 50)
## combine these different collections into a list
data_to_plot = [client_1, client_2, client_3, client_4]
# Create a figure instance
fig = plt.figure(1, figsize=(9, 6))
# Create an axes instance
ax = fig.add_subplot(111)
# Create the boxplot
bp = ax.boxplot(data_to_plot)
# Save the figure
fig.savefig('Client_Comparison.png', bbox_inches='tight')
ax.set_xticklabels(['client1', 'client2', 'client3', 'client4'])
多条数据绘制
# Multiple plots in a single diagram
t = np.arange(0,50)
fig, ax = plt.subplots()
plt.plot(t,client_1,'r') # plotting t,a separately
plt.plot(t,client_2,'b') # plotting t,b separately
plt.plot(t,client_3,'g') # plotting t,c separately
#plt.set_title("KPI")
plt.show()