Matplotlib学习笔记(一)

   matplotlib学习笔记

 

参考:Python数据科学入门教程

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]:
<Container object of 5 artists>
In [14]:
plt.xlabel('bar number')
plt.ylabel('bar count')
plt.title('Bar Plot')
Out[14]:
<matplotlib.text.Text at 0x1b1dc879160>
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]:
(array([ 1.,  0.,  3.,  1.,  7.,  2.,  2.,  1.,  1.,  1.,  1.,  4.,  4.]),
 array([  0,  10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 110, 120, 130]),
 <a list of 13 Patch objects>)
In [39]:
plt.xlabel('x')
plt.ylabel('y')
plt.title('Histogram Plot')
Out[39]:
<matplotlib.text.Text at 0x1b1dcbbb320>
In [40]:
plt.show()
 
 

散点图

In [42]:
plt.scatter(np.arange(10),np.random.randn(10),color = 'b')
Out[42]:
<matplotlib.collections.PathCollection at 0x1b1dcc99128>
In [43]:
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot')
Out[43]:
<matplotlib.text.Text at 0x1b1dcc69828>
In [44]:
plt.show()
 
 

注:标记颜色,大小和类型参考Matplotlib标记文档。

 

堆叠图

In [45]:
days = np.arange(1,6);days
Out[45]:
array([1, 2, 3, 4, 5])
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]:
[<matplotlib.collections.PolyCollection at 0x1b1de02b780>,
 <matplotlib.collections.PolyCollection at 0x1b1de0794e0>,
 <matplotlib.collections.PolyCollection at 0x1b1de079b70>,
 <matplotlib.collections.PolyCollection at 0x1b1de083240>]
In [65]:
plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot')
Out[65]:
<matplotlib.text.Text at 0x1b1de043f28>
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()
 
 

注:图例自动处理。

 

具体参数参考官方文档。

posted @ 2017-12-31 14:40  orange1002  阅读(431)  评论(0编辑  收藏  举报