matplotlib是一个用于绘制2D图的python库,下面是绘制各种类型图的一个示例。


下图是一个绘制点线图的示例:
import numpy as npimport mathimport matplotlib.pyplot as pltfig, ax = plt.subplots(figsize=(8, 4))xData = np.arange(-5, 5, 0.5)yData1 = np.arange(-5, 5, 0.5) # sigmodyData2 = np.arange(-5, 5, 0.5) # ReluyData3 = np.arange(-5, 5, 0.5) # Softplusfor idx in range(0, xData.__len__()): yData1[idx] = 1.0/(1 + math.exp(-1 * yData1[idx])) yData2[idx] = max(0, yData2[idx]) yData3[idx] = math.log(1 + math.exp(yData3[idx]))ax.plot(xData, yData1, color = '#7B68EE', linestyle = '--', marker = 'o', linewidth=1, label='Sigmod')ax.plot(xData, yData2, color = '#40E0D0', linestyle = '--', marker = 'o', linewidth=1, label='ReLu')ax.plot(xData, yData3, color = '#F4A460', linestyle = '--', marker = 'o', linewidth=1, label='Softplus')ax.grid()ax.set_xticks(xData)ax.set_yticks(np.arange(0, 5, 0.5))ax.set_xlabel('X')ax.set_ylabel('Y')ax.legend()# plt.savefig('./fig.png', dpi=100)plt.show()
输出的结果如下:

下面是绘制柱状图的示例:
import numpy as npimport matplotlib.pyplot as pltfig, ax = plt.subplots()people = ('Marry', 'Tom', 'Harry', 'Slim', 'Jim')y_pos = np.arange(len(people))performance = 3 + 10 * np.random.rand(len(people))error = np.random.rand(len(people))ax.barh(y_pos, performance, xerr=error, align='center', color='#7B68EE', ecolor='black')ax.set_yticks(y_pos)ax.set_xticks(np.arange(0, max(performance), 1))ax.set_yticklabels(people)ax.invert_yaxis() # labels read top-to-bottomax.set_xlabel('Performance')ax.set_ylabel('People')ax.set_title('How long do you want to go today?')ax.grid()ax.legend()plt.show()
输出的结果如下图所示:

下面是绘制填充图的示例:
import numpy as npimport matplotlib.pyplot as pltfig, ax = plt.subplots()x = np.linspace(0, 1, 500)y = -1 * np.sin(4 * np.pi * x) * np.exp(-4 * (x-10))ax.fill(x, y, '#7B68EE', zorder=10)ax.grid(True, zorder=5)ax.legend()plt.show()
输出的结果如下图所示:

其中色彩的设置可以通过参数 color = '?' 来设定,颜色的常用代码如下,此外,还可以通过RGB值设定,如蓝色Blue(0, 0, 255)对应的值为'#0000FF'

绘制点线图时,需要设置点和线的形状,其中点的形状通过参数marker设置,线的形状通过参数linestyle设定,他们可取的值如下:
