Matplotlib 是Python提供的一个二维绘图库,所有类型的平面图,包括直方图、散点图、折线图、热图以及其他各种类型,都能由Python制作处理。本节我们使用pyplot的基础绘图框架。
示例代码:
import numpy as np
#使用pyplot之前,我们必须导入numpy库
import matplotlib.pyplot as plt
def simple_line_plot(x,y,figure_no):
#首先使用pyplot的figure函数编号标示图形。
plt.figure(figure_no)
#然后,给定x,y值就能轻松调用plt.plot()函数
plt.plot(x,y)
#分别通过 xlabel、ylabel函数给x轴和y轴命名。
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('Simple Line')
#图形绘制完毕,但是图形不会自动显示,必须通过调用show()函数才能显示。
def simple_dots(x,y,figure_no):
plt.figure(figure_no)
#这个'or'参数说明我们需要的是点(o),这个点的颜色是红色(r)
plt.plot(x,y,'or')
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('Simple Dots')
def simple_scatter(x,y,figure_no):
plt.figure(figure_no)
plt.scatter(x,y)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('Simple Scatter')
def scatter_with_color(x,y,labels,figure_no):
plt.figure(figure_no)
#labels的不同值,对应不同的颜色
plt.scatter(x,y,c=labels)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('Scatter with color')
if __name__ == '__main__':
#之前的程序可能已经绘制了一些图形,先把他们全部关闭是一个好习惯。同时,程序可能也需要更多的绘图资源。
plt.close('all')
#1.figure1
#x、y样例数据生成折线图和简单的点图
x = np.arange(1,100,dtype=float)
#np.power(xx,2)表示 对xx求平方
y = np.array([np.power(xx,2) for xx in x])
#当程序中有多个图形的时候,最好用figure_no变量给每个图形设置一个编号。
figure_no = 1
#2.figure2
simple_line_plot(x,y,figure_no)
figure_no += 1
simple_dots(x,y,figure_no)
#3.figure3
#x、y样例数据生成散点图
#np.random.uniform(size=100) 生成0-1的100个随机数
x = np.random.uniform(size=100)
y = np.random.uniform(size=100)
figure_no += 1
simple_scatter(x,y,figure_no)
#4.figure4
figure_no += 1
#随机地给点加入一些标签,内容是0或1,最后再用这些x,y和标签的变量作为参数来调用scatter_with_color函数
#np.random.randint(2,size=100) 随机生成2以内的正整数,也就是0和1,100个
label = np.random.randint(3,size=100)
scatter_with_color(x,y,label,figure_no)
plt.show()
示例代码2:生成热图、给x和y轴添加标签
#热图及轴标签
import numpy as np
import matplotlib.pyplot as plt
def x_y_axis_labeling(x,y,x_labels,y_labels,figure_no):
plt.figure(figure_no)
#采用pyplot的plot函数来绘制一张简单的点图。这次我们采用"+"来表示点,r代表红色
plt.plot(x,y,'+r')
plt.margins(0.2)
#使用xticks函数传递x的值和它们的标签,此外,我们还要将文本进行垂直翻转以避免相互遮挡。
plt.xticks(x,x_labels,rotation='vertical')
plt.yticks(y,y_labels,)
def plot_heat_map(x,figure_no):
plt.figure(figure_no)
#调用pcolor函数来创建热图
plt.pcolor(x)
#colorbar函数用来控制渐变色的颜色范围。
plt.colorbar()
if __name__ == "__main__":
plt.close('all')
x = np.array(range(1,6))
y = np.array(range(100,600,100))
x_labels = ['element1' , 'element2' ,'element3' ,'element4' ,'element5']
y_labels = ['weight1' ,'weight2' ,'weight3' ,'weight4' ,'weight5']
#给x轴和y轴添上标签
x_y_axis_labeling(x,y,x_labels,y_labels,1)
#使用pyplot生成热图
x = np.random.normal(loc=0.5, scale=0.2, size=(10,10))
#第二个参数2 是图形的编号
plot_heat_map(x,2)
plt.show()