Matplotlib学习笔记(一)
Python3.6.1
jupyter notebook
In [41]:
import matplotlib.pyplot as plt
import numpy as np
图例、标题和标签¶
In [3]:
x = [1,2,3]
y1 = [5,7,4]
y2 = [10,14,12]
In [10]:
plt.plot(x,y1,label = 'Line1') #线条标签
plt.plot(x,y2,label = 'Line2')
plt.xlabel('X axis') #坐标轴标签
plt.ylabel('Y axis')
plt.title('Line') #标题
plt.legend() #显示图例
plt.show() #显示图形
条形图和直方图¶
In [11]:
x1 = [1,3,5,7,9]
x2 = [2,4,6,8,10]
y1 = [3,5,7,8,10]
y2 = [4,6,9,10,15]
In [12]:
plt.bar(x1,y1,label = 'sample1',color = 'b')
plt.bar(x2,y2,label = 'sample2',color = 'r')
Out[12]:
In [14]:
plt.xlabel('bar number')
plt.ylabel('bar count')
plt.title('Bar Plot')
Out[14]:
In [15]:
plt.legend()
plt.show()
注:颜色可以用16进制颜色代码(sublime)
In [16]:
population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
In [17]:
bins = list(range(0,140,10))
In [38]:
plt.hist(population_ages,bins=bins,histtype='bar',color ='b',rwidth=.8)
Out[38]:
In [39]:
plt.xlabel('x')
plt.ylabel('y')
plt.title('Histogram Plot')
Out[39]:
In [40]:
plt.show()
散点图¶
In [42]:
plt.scatter(np.arange(10),np.random.randn(10),color = 'b')
Out[42]:
In [43]:
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot')
Out[43]:
In [44]:
plt.show()
注:标记颜色,大小和类型参考Matplotlib标记文档。
堆叠图¶
In [45]:
days = np.arange(1,6);days
Out[45]:
In [46]:
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
playing = [8,5,7,8,13]
尴尬。。。
In [64]:
plt.stackplot(days,sleeping,eating,working,playing,colors = ['m','c','r','k'])
Out[64]:
In [65]:
plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot')
Out[65]:
In [66]:
plt.show()
注:如何添加图例?
饼图¶
In [67]:
slices =[7,2,2,13]
act = ['sleeping','eating','working','playing']
colors = 'cmrb'
In [70]:
plt.pie(slices,labels=act,colors=colors,startangle=90,explode=(0,.1,0,0),shadow=True,autopct='%1.1f%%')
plt.title('Pie Plot')
plt.show()
注:图例自动处理。
具体参数参考官方文档。¶
Talk is cheap,show me your code!