天天看点

Python数据可视化——matplotlib使用

Python数据可视化——matplotlib使用

总第57篇

01|Figure和Subplot:

matplotlib的图像都位于figure对象中,相当于一块画布。figure的属性figsize是用来设置figure的大小的。subplot是用来存放坐标系的,一个figure中可以有多个subplot。

%matplotlib inline

import matplotlib.pyplot as plt

from numpy.random import randn

import numpy as np

fig=plt.figure()

ax1=fig.add_subplot(2,2,1)#表示在figure中建立2*2个坐标系,ax1位于第一个坐标中

ax2=fig.add_subplot(2,2,2)

ax3=fig.add_subplot(2,2,3)

在程序开头加(%matplotlib)是为了显示figure,如果不加则不会跳出figure图框。而(%matplotlib inline)则是直接显示在编程界面,不重新跳出做图框。

Python数据可视化——matplotlib使用

如果我们没有指定在哪个ax上进行作图,matplotlib会默认选择最后一个(如果没有则创建一个)上进行绘制。下面这条命令就没有指定。

plt.plot(randn(50).cumsum(),"k--")
Python数据可视化——matplotlib使用

ax1.hist(randn(100),bins=20,color='k',alpha=0.3)#在ax1上作图

ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))#在ax2上作图

Python数据可视化——matplotlib使用

也可以直接一次性创建多个图框,然后在使用的时候进行索引使用就行,比如下面的subplots(2,3)就是一次性建立两行三列个坐标,而axes[0,1]则表示利用第0行第2列对应的图框。

fig,axes=plt.subplots(2,3)

_=axes[0,1].hist(randn(100),bins=20,color='k',alpha=0.3)#加“_=”视为让其不输出randn产生的随机数组

Python数据可视化——matplotlib使用

subplots的参数:除几行几列外,还有sharex和sharey,表示x(y)轴的刻度是否要保持相等的刻度。默认情况是False,即不相等。

调整subplot周围的间距:默认情况下,matlibplot会在subplot外围以及sbuplot之间留下一定的边距。图像的大小和间距是相关的,如果你调整了图像大小,间距也会自动调整。利用Figure的subplots_adjust方法可以用来修改间距。

plt.subplots_adjust(left=None,right=None,top=None,bottom=None,wspace=None,hspace=None)#分别表示左右上下边距,以及宽度和高度百分比。

02|颜色,标记和线型:

常用颜色用英文字母的首字母来代替。

b---blue c---cyan g---green k----black

m---magenta r---red w---white y----yellow

标记是用在线性图上来强调实际数据点的。

. Point marker

, Pixel marker

o Circle marker

v Triangle down marker

^ Triangle up marker

< Triangle left marker

> Triangle right marker

1 Tripod down marker

2 Tripod up marker

3 Tripod left marker

4 Tripod right marker

s Square marker

p Pentagon marker

* Star marker

h Hexagon marker

H Rotated hexagon D Diamond marker

d Thin diamond marker

| Vertical line (vlinesymbol) marker

_ Horizontal line (hline symbol) marker

+ Plus marker

x Cross (x) marker

线性是表示线的形状。

- 实线

-- 短线

-. 短点相间线

: 虚点线

plot(randn(30).cumsum(),color="k",linestyle="--",marker="o")
Python数据可视化——matplotlib使用

03|刻度、标签和标题:

fig=plt.figure()

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

ax.plot(randn(1000).cumsum())

ticks=ax.set_xticks([0,250,500,750,1000])#设置x轴的刻度,y轴把x换成y即可

lables=ax.set_xticklabels(["one","two","three","four","five"],rotation=30,fontsize="small")#设置x轴对应的标签,y轴把x换成y即可

ax.set_title("my first matplotlib plot")#为坐标轴设置标题

Python数据可视化——matplotlib使用

04|图例:

在添加subplot的时候传入label参数,然后调用ax.legend()或plt.legend()即可。

fig=plt.figure()

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

ax.plot(randn(1000).cumsum(),label="one")#创建label标签

ax.plot(randn(1000).cumsum(),label="two")#创建label标签

ax.plot(randn(1000).cumsum(),label="three")#创建label标签

ax.legend(loc="best")#loc是用来说明图例的放置位置

Python数据可视化——matplotlib使用

06|Pandas作图:

matplotlib是一种比较低级的工具,要组装一张图表,需要用到它的各种组件才可以,包括图表类型(线型图、柱状图、盒形图、散布图、等值线图等)、图例、标题、刻度标签以及其他注释信息。这是因为制作一张完整的图表都需要用到这些,但是matplotlib要实现这种功能需要很多行代码,而pandas可能只需要几行代码就可以搞定。

  1. 线型图:Series和DataFrame都有自己的plot方法,plot默认创建的是线形图,Series.plot()和DataFrame.plot()。
  2. 柱状图:需要给plot方法传入参数kind,其中kind="bar"表垂直柱状图、kind="barh"表水平柱状图。Series和DataFrame的索引将会被用作X(或Y)轴的刻度。柱状图中有个特例就是堆积柱状图,只需要给plot传入参数stacked="True"即可。还可以利用s.value_counts().plot(kind="bar")来图形化显示Series中各值出现的频率。
  3. 直方图:是一种可以对值频率离散化显示的柱状图。通过调用Series.hist()方法即可创建。
  4. 密度图:与直方图相关的一种类型图,是通过计算“可能会产生观测数据的连续概率分布的估计”而产生的,通过给plot传入参数kind="kde"即可。
  5. 散布图:是观测两个一维数据序列之间关系的有效手段,使用pd.scatter_matrix()即可建立。