简单的绘图:
import matplotlib.pyplot as plt #也可以写成:from matplotlib import pyplot as plt
x = [5,6,7,8]
y = [7,8,5,6]
plt.plot(x,y) #也可以直接plt.plot([5,6,7,8],[7,8,5,6])
plt.title('First Chart') #中文会乱码
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.show() #显示
添加元素:
import matplotlib.pyplot as plt
x = [5,6,7,8]
y = [7,8,5,6]
x1 = [2,5,3,9]
y1 = [5,2,9,3]
plt.plot(x,y,'b',linewidth = 2, label = 'Line1') #颜色有g r y b k(黑) linewidth设置线条粗细,color='b'可简写‘b’
plt.plot(x1,y1,'r',linewidth = 3, label = 'Line2') #要添加图列必须给绘制的这条线命名,否则无法添加图例
plt.title('First Chart')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend() #添加图例
plt.grid() #添加网格,加颜色写成plt.grid(color='k'),color=不可省略,什么都不写默认灰色,grid()等于grid(True),去除网格grid(False)
plt.show()
效果(大多图像元素也可以直接在图片选项中直接修改):
散点图:
import matplotlib.pyplot as plt
x = [5,6,7,8]
y = [7,8,5,6]
x1 = [2,5,3,9]
y1 = [5,2,9,3]
plt.scatter(x,y,color='b',label = 'Line1') #使用scatter命令,改变颜色必须使用color=
plt.scatter(x1,y1,color='r',label = 'Line2')
plt.title('First Chart')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend()
#plt.grid()
plt.show()
绘制柱状图:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [7,8,5,6]
x1 = [5,6,7,8]
y1 = [5,2,9,3]
plt.bar(x,y,color='b',label = 'Line1') #使用bar命令 改变颜色必须color=
plt.bar(x1,y1,color='r',label = 'Line2')
plt.title('First Chart')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend()
#plt.grid()
plt.show()