
這是一段演示使用matplotlib繪制曲線圖的代碼,具體查看增加的注釋,可以繪制出上圖效果
# 導(dǎo)入使用的庫(kù)
import matplotlib.pyplot as plt
from matplotlib.collections import EventCollection
import numpy as np
# 設(shè)置隨機(jī)數(shù)種子
np.random.seed(19680801)
# 創(chuàng)建隨機(jī)數(shù)
xdata = np.random.random([2, 10])
# 分隔數(shù)據(jù)為兩部分
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
# 數(shù)據(jù)排序,繪制清晰的曲線
xdata1.sort()
xdata2.sort()
# 創(chuàng)建y軸點(diǎn)數(shù)據(jù)
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
# 繪制數(shù)據(jù)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(xdata1, ydata1, 'r', xdata2, ydata2, 'b')
# 創(chuàng)建標(biāo)記x數(shù)據(jù)點(diǎn)的事件
xevents1 = EventCollection(xdata1, color=[1, 0, 0], linelength=0.05)
xevents2 = EventCollection(xdata2, color=[0, 0, 1], linelength=0.05)
# 創(chuàng)建標(biāo)記y數(shù)據(jù)點(diǎn)的事件
yevents1 = EventCollection(ydata1, color=[1, 0, 0], linelength=0.05,
orientation='vertical')
yevents2 = EventCollection(ydata2, color=[0, 0, 1], linelength=0.05,
orientation='vertical')
# 增加事件到坐標(biāo)
ax.add_collection(xevents1)
ax.add_collection(xevents2)
ax.add_collection(yevents1)
ax.add_collection(yevents2)
# 設(shè)置坐標(biāo)上限
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_title('line plot with data points')
# 顯示繪制的圖形
plt.show()