pandas 绘图和可视化

1. matplotlib api 入门

matplotlib api 函数都位于maptplotlib.pyplot模块中

画图的各种方法:

  • Figure:画图窗口
  • Subplot/add_Subplot: 创建一个或多个子图
  • Subplots_adjust:调整subplot周围的间距
  • color/linestyle/marker: 线颜色,线型,标记
  • drawstyle:线型选项修改
  • xlim: 图表范围,有两个方法get_xlim和set_xlim
  • xticks:刻度位置,有两个方法get_xticks和set_xticks
  • xticklabels: 刻度标签,有两个方法get_xticklabels和set_xticklabels
  • legend: 添加图例。plt.legend(loc='best')


Figure和Subplot方法

Figure对象:matplotlib的图像都位于Figure对象中,可以用plt.figure创建一个新的Figure.

fig=plt.figure()
plt.show()
这时会出现一个空的窗口。figure有点类似于画图需要的画布

add_subplot:创建一个或多个子图,即在一个窗口中画好几个图形。

eg:ax2=fig.add_subplot(2,2,1) 
#这个的意思是:子图排列是应该是2X2个(即上下2个),最后一个1是指当前选中的是4个subplot中的第一个(编号从1开始的)。
如果如下:由窗口中会画3个图
 ax1=fig.add_subplot(2,2,1)  #选中第一个画子图
 ax2=fig.add_subplot(2,2,2)  #选中第二个画子图
 ax3=fig.add_subplot(2,2,3)  #选中第三个画子图
import json
from pandas import DataFrame,Series
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#不能通过空Figure绘图,必须用add_subplot创建一个或多个subplot才行。
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)

#"K--"是一个线型选项,用于告诉matplotlib绘制黑色虚线图
from numpy.random import randn
plt.plot(randn(50).cumsum(),'k--')
_=ax1.hist(randn(100),bins=20,color='k',alpha=0.3)  #柱形图:hist
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))  #点状图:scatter
plt.show()

plt.subplots:可以创建一个新的Figure,并返回一个含有已创建的subplot对象的Numpy数组

fig,axes=plt.subplots(2,3)
print axes
#输出结果如下:
# [[<matplotlib.axes.AxesSubplot object at 0x106f5dfd0>
#   <matplotlib.axes.AxesSubplot object at 0x109973890>
#   <matplotlib.axes.AxesSubplot object at 0x1099f9610>]
#  [<matplotlib.axes.AxesSubplot object at 0x109a60250>
#   <matplotlib.axes.AxesSubplot object at 0x10a13c290>
#   <matplotlib.axes.AxesSubplot object at 0x10a1c3050>]]

#这样可以轻松地对axes数组进行索引,就好像是一个二维数组一样。可以通过sharex和sharey指定
#subplot应该具有相同的X轴或Y轴。在比较相同范围的数据时,这也是非常实用的,否则,matplotlib
#会自动缩放各图表的界限
print axes[0,1]

pyplot.subplots的选项
参数            说明
nrows           subplot的行数
ncols           subplot的列数
sharex          所有subplot应该使用相同的X轴刻度(若调节xlim将会影响所有的subplot)
sharey          所有subplot应该使用相同的Y轴刻度(若调节ylim将会影响所有的subplot)
subplot_kw      用于创建各subplot的关键字字典
**fig_kw        创建figure时的其他关键字,如plt.subplots(2,2,figsize=(8,6))

Subplots_adjust方法

Subplots_adjust:调整subplot周围的间距

默认情况下,matplotlib会在subplot外围留下一定的边矩,并在subplot之间留下一定的间矩。
间矩跟图象的高度和宽度有关,因为,如果你调整了图像大小,间距也会自动调整。利用Figure的

subplots_adjust方法可以轻而易举地修改间矩。它也是个顶级函数。

subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
注:wspace和hspace用于控制宽度和高度的百分比,可以用作subplot之间的间距。
例:调整图片的间矩,各subplot间矩调为0
import json
from pandas import DataFrame,Series
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn

fig,axes=plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2): #行轴2个子图
    for j in range(2): #列轴2个子图
        axes[i,j].hist(randn(500),bins=50,color='k',alpha=0.5) #画每一个图,先从axes[1,1]即第一行第一列
plt.subplots_adjust(wspace=0,hspace=0)
plt.show()

颜色、标记和线型(color,linestyle,marker)

matplotlib的plot函数接受一组X和Y坐标,还可以接受一个表示颜色和线型的字符串缩写。

eg:根据x和y绘制绿色虚线
ax.plot(x,y,'g--')
或者:
ax.plot(x,y,linestyle='--',color='g')

#常用的颜色都有一个缩写词,要使用其他任意颜色则可以通过指定其RGB值的形式使用(例如:‘#通通CE’)
#完整的linestyle列表可以参见plot的文档。
#线型图还可以加上一些标记(marker),以强调实际的数据点。

from pandas import DataFrame,Series
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn

# fig=plt.figure()
plt.plot(randn(30).cumsum(),color='k',linestyle='dashed',marker='o')
plt.show()

drawstyle:选项修改

import matplotlib.pyplot as plt
from numpy.random import randn

# fig=plt.figure()
data=randn(30).cumsum()
plt.plot(data,'k--',label='Default')
plt.plot(data,'k-',drawstyle='steps-post',label='steps-post')
plt.show()

plt.legend(loc='best') #legend是加入图例。loc是告诉matplotlib要将图例放在哪,best是不错的选择,因为它会选择不碍事的位置。
要从图例中去除一个或多个元素,不传入label或传入label='_nolegend_'即可


刻度、标签、图例(xlim图表范围、xticks刻度位置、xticklabels刻度标签)

对于大多数的图表装饰项,其主要实现方式有二:使用过程型的pyplot接口以及更为面向对象的原生matplotlib API.

pyplot接口:xlim(图表的范围),xticks(刻度位置),xticklabels(刻度标签)。它们各自有两个方法,以xlim为例,

有ax.get_xlim,ax.set_xlim两个方法。

(1).在调用时不带参数,则返回当前的参数值。例:plt.xlim()返回当前的X轴绘图范围

  (2).调用时带参数,则设置参数值。plt.xlim([0,10])会将X轴的范围设置为0到10.

import matplotlib.pyplot as plt
from numpy.random import randn

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())

#修改X轴的刻度,最简单的办法是使用set_xticks和set_xticklabels
ticks=ax.set_xticks([0,250,500,750,1000]) #x轴刻度设置
labels=ax.set_xticklabels(['one','two','three','four','five'],
                          rotation=30,fontsize='small')  #x轴标签设置
#再用set_xlabel为x轴设置一个名称,并用set_title设置一个标题
ax.set_title('My First matplotlib plot')  #设置标题
ax.set_xlabel('Stages')   #设置x轴标签
plt.show()

添加图例(plt.legend(loc='best'))

图例是另一种用于标识图表元素的重要工具。添加图例的方式有二。
(1)最简单的是在添加subplot的时候传入label参数,然后调用ax.legend()或plt.legend()来自动创建图例

import matplotlib.pyplot as plt
from numpy.random import randn

#1.添加subplot的时候传入label参数来添加图例
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(),'k',label='one')
ax.plot(randn(1000).cumsum(),'k--',label='two')
ax.plot(randn(1000).cumsum(),'k.',label='three')
#或者调用ax.legend()来创建
# ax.legend(loc='best')
plt.show()

注解以及在subplot上绘图

# -*- encoding: UTF-8 -*- 
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import numpy.random as npr
from datetime import datetime


fig = plt.figure()
ax = fig.add_subplot(1,1,1)

data = pd.read_csv('E:\\spx.csv',index_col = 0,parse_dates = True)
spx = data['SPX']
spx.plot(ax = ax,style = 'k-')

crisis_data = [
(datetime(2007,10,11),'Peak of bull market'),
(datetime(2008,3,12),'Bear Stearns Fails'),
(datetime(2008,9,15),'Lehman Bankruptcy')
]

for date,label in crisis_data:
    ax.annotate(label,xy = (date,spx.asof(date) + 50),
        xytext = (date,spx.asof(date) + 200),
        arrowprops = dict(facecolor = 'black'),
        horizontalalignment = 'left',verticalalignment = 'top')
ax.set_xlim(['1/1/2007','1/1/2011'])
ax.set_ylim([600,1800])

ax.set_title('Important dates in 2008-2009 finacial crisis')
plt.show()
#更多关于注解的示例,请看文档

#图形的绘制要麻烦些,有一些常见的图形的对象,这些对象成为块(patch)
#如Rectangle 和 Circle,完整的块位于matplotlib.patches
#要绘制图形,需要创建一个块对象shp,然后通过ax.add_patch(shp)将其添加到subplot中

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

rect = plt.Rectangle((0.2,0.75),0.4,0.15,color = 'k',alpha = 0.3)
circ = plt.Circle((0.7,0.2),0.15,color = 'b',alpha = 0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color = 'g',alpha = 0.5)

ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)

plt.show()

将图表保存到文件(savefig)

plt.savefig可以将当前图表保存到文件。该方法相当于Figure对象的实例方法savefig.

文件类型是通过文件扩展名抢断出来的,例如你使用的是.pdf,就会得到一个pdf文件。
发布图片时最常用到两个重要的选项是dpi(控制“每英寸点数”分辨率)和bbox_inches(可以剪除当前图表周围的空白部分)。
例:要得到一张带有最小白边且分辨率为400dpi的PNG图片。可以如下:
plt.savefig('figpath.png',dpi=400,bbox_inches='tight')

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import numpy.random as npr
from datetime import datetime
from io import StringIO

#将图标保存到文件
#savefig函数可以保存图形文件,不同的扩展名保存为不同的格式
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

rect = plt.Rectangle((0.2,0.75),0.4,0.15,color = 'k',alpha = 0.3)
circ = plt.Circle((0.7,0.2),0.15,color = 'b',alpha = 0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color = 'g',alpha = 0.5)

ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)



#注意下面的dpi(每英寸点数)和bbox_inches(可以剪除当前图标周围的空白部分)(确实有效)
plt.savefig('figpath.png',dpi=400,bbox_inches='tight')

#不一定save到文件中,也可以写入任何文件型对象,比如StringIO:

# buffer = StringIO()
# plt.savefig(buffer)
# plot_data = buffer.getvalue()

#这对Web上提供动态生成的图片是很实用的
plt.show()
Figure.savefig的选项:
参数                    说明
fname                  含有文件路径的字符串或python的文件型对象。图像格式由文件扩展名推断得出。
dpi                    图像分辨率,默认为100
facecolor,edgecolor    图像的背景色,默认为“w”(白色)
format                 显式设置文件格式(“png”、“pdf”、“svg”、“ps”、“eps”......)

bbox_inches            图表需要保存的部分。如果设置为“tight”,则将尝试剪除图表周围的空白部分

matplotlib配置

matplotlib自带一些配色方案,以及为生成出版质量的图片而设定的默认配置信息。
subplot边矩、配色方案、字体大小、网格类型。操作matplotlib配置系统的方式主要有两种:
第一种是python编程方式,即利用rc方法。比如说,要将全局的图像默认大小设置为10X10,你可以执行如下:

plt.rc('figure',figsize=(10,10))

rc的第一个参数是希望自定义的对象,如‘figure’、‘axes’、‘xtick’、‘ytick’、‘grid’,'legend'等。
其后可以跟上一系列的关键字参数。最简单的方法是将这些选项写成一个字典:
font_options={'family':'monosapce',
              'weight':'bold',
              'size':'small'}
plt.rc('font',**font_options)



猜你喜欢

转载自blog.csdn.net/u012474716/article/details/80973920