Python - matplotlib 数据可视化

在许多实际问题中,常常要对给出的数据进行可视化,便于观察。html

今天专门针对Python中的数据可视化模块--matplotlib这块内容系统的整理,方便查找使用。

本文来自于对《利用python进行数据分析》以及网上一些博客的总结。

 

1  matplotlib简介

matplotlib是Pythom可视化程序库的泰斗,通过几十年它仍然是Python使用者最经常使用的画图库。有许多别的程序库都是创建在它的基础上或直接调用它,好比pandas和seaborn就是matplotlib的外包,
它们让你使用更少的代码去使用matplotlib的方法。 Gallery页面中有上百幅缩略图,打开以后都有源程序,很是适合学习matplotlib。
 

2  图和子图的创建

2.1  导入matplotlib

import matplotlib.pyplot as plt
import numpy as np

  

2.2  创建图和子图方式一

plt.plot( )会在最近的一个图上进行绘制

from numpy.random import randn  
fig = plt.figure(figsize = (8,4))    #设置图的大小  
ax1 = fig.add_subplot(2,2,1)  
ax2 = fig.add_subplot(2,2,2)  
ax3 = fig.add_subplot(2,1,2)  
ax3.plot(randn(50).cumsum(),'k--')   # plt.plot(randn(50).cumsum(),'k--')等效  
ax1.hist(randn(100),bins = 10, color = 'b', alpha = 0.3)      #bins 分红多少间隔   alpha 透明度  
ax2.scatter(np.arange(30),np.arange(30) + 3*randn(30))  
plt.show()

 

2.3 创建子图方式二

from numpy.random import randn  
fig, axes = plt.subplots(2,2)                               #以数组方式访问  
t = np.arange(0., 5., 0.2)  
axes[0,0].plot(t, t, 'r-o', t, t**2, 'bs', t, t**3, 'g^')   #同时绘制多条曲线  
axes[1,1].plot(randn(40).cumsum(),'b--')  
plt.show()

 

2.4 主题设置

使用style.use()函数python

df_iris = pd.read_csv('../input/iris.csv')  
plt.style.use('ggplot')    #'fivethirtyeight','ggplot','dark_background','bmh'  
df_iris.hist('sepal length')  
plt.show()

 

3  颜色、标记、线型、刻度、标签和图例

from numpy.random import randn  
fig = plt.figure()  
ax1 = fig.add_subplot(1,1,1)  
ax1.plot(randn(30).cumsum(),color = 'b',linestyle = '--',marker = 'o',label = '$cumsum$')  # 线型  能够直接'k--o'  
ax1.set_xlim(10,25)                                                                                     
ax1.set_title('My first plot')  
ax1.set_xlabel('Stages')  
plt.legend(loc = 'best')           #把图放在不碍事的地方  xticks([])设置刻度  
plt.show()

  

等价于下面的代码:数组

from numpy.random import randn  
fig = plt.figure()  
ax1 = fig.add_subplot(1,1,1)  
ax1.plot(randn(30).cumsum(),color = 'b',linestyle = '--',marker = 'o',label = '$cumsum$')   #图标可使用latex内嵌公式  
plt.xlim(10,25)                   #plt.axis([10,25,0,10])对x,y轴范围同时进行设置  
plt.title('My first plot')  
plt.xlabel('Stages')  
plt.legend(loc = 'best')  
plt.show()

  

4  pandas中的绘图函数

在pandas中,咱们具备行标签,列标签以及分组信息。这也就是说,要制做一张完整的图表,本来须要一大堆的matplotlib代码,如今只需一两条简洁的语句就能够了。
pandas有不少可以利用DataFrame对象数据组织特色来建立标准图表的高级绘图方法。
 

4.1  线型图

from numpy.random import randn  
fig, axes = plt.subplots(1,2)  
s = pd.Series(randn(10).cumsum(),index = np.arange(0,100,10))  
s.plot(ax = axes[0])   # ax参数选择子图  
  
df = pd.DataFrame(randn(10,3).cumsum(0),columns = ['A','B','C'],index = np.arange(0,100,10))  
df.plot(ax = axes[1])      
plt.show()

 

4.2 柱状图

from numpy.random import rand  
fig, axes = plt.subplots(1,2)  
data = pd.Series(rand(16),index = list('abcdefghijklmnop'))  
data.plot(kind = 'bar', ax = axes[0], color = 'b', alpha = 0.7)    #kind选择图表类型  'bar' 垂直柱状图  
data.plot(kind = 'barh', ax = axes[1], color = 'b', alpha = 0.7)   # 'barh' 水平柱状图  
plt.show()

  

from numpy.random import rand  
fig, axes = plt.subplots(1,2)  
data = pd.DataFrame(rand(6,4),  
                    index = ['one','two','three','four','five','six'],  
                    columns = pd.Index(['A','B','C','D'], name = 'Genus'))  
data.plot(kind = 'bar', ax = axes[0], alpha = 0.5)  
data.plot(kind = 'bar', ax = axes[1], stacked = True, alpha = 0.5)  
plt.show()

 

此外,柱状图有一个很是不错的用法,利用value_counts( )图形化显示Series中各值的出现几率,好比s.value_counts( ).plot(kind = 'bar')。dom

 

4.3 直方图和密度图

from numpy.random import randn  
fig, axes = plt.subplots(1,2)  
data = pd.Series(randn(100))  
data.hist(ax = axes[0], bins = 50)       #直方图  
data.plot(kind = 'kde', ax = axes[1])    #密度图  
plt.show()

 

其实能够一次性制做多个直方图,layout参数的意思是将两个图分红两行一列,若是没有这个参数,默认会将所有的图放在同一行。函数

 

df_iris = pd.read_csv('../input/iris.csv')  
columns = ['sepal length','sepal width','petal length','petal width']  
df_iris.hist(column=columns, layout=(2,2))  
plt.show()

  

4.4 箱型图
箱型图是基于五数归纳法(最小值,第一个四分位数,第一个四分位数(中位数),第三个四分位数,最大值)的数据的一个图形汇总,还须要用到四分位数间距IQR = 第三个四分位数 - 第一个四分位数。
df_iris = pd.read_csv('../input/iris.csv')  #['sepal length','sepal width','petal length','petal width','class']  
sample_size = df_iris[['petal width','class']]  
sample_size.boxplot(by='class')  
plt.xticks(rotation=90)                     #将X轴的坐标文字旋转90度,垂直显示  
plt.show()

  

5  参考资料连接

相关文章
相关标签/搜索