《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图

matplotlib实际上是一种比较低级的工具。要绘制一张图表,你组装一些基本组件就行:数据展示(即图表类型:线型图、柱状图、盒形图、散布图、等值线图等)、图例、标题、刻度标签以及其他注解型信息。

在pandas中,我们有多列数据,还有行和列标签。pandas自身就有内置的方法,用于简化从DataFrame和Series绘制图形。另一个库seaborn(https://seaborn.pydata.org/),由Michael Waskom创建的静态图形库。Seaborn简化了许多常见可视类型的创建。

In [194]: import matplotlib.pyplot as plt

In [195]: plt.figure()
Out[195]: <Figure size 640x480 with 0 Axes>

In [196]:  s = pd.Series(np.random.randn(10).cumsum(),index = np.arange(0,100,10))

In [197]: s.plot()
Out[197]: <matplotlib.axes._subplots.AxesSubplot at 0x2b351dd8d30>

In [198]: plt.show()

In [186]: plt.show()

注:在ipython中要写成如下代码才会显示图像:

import matplotlib.pyplot as plt
plt.figure() 
df.plot()
plt.show()

《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图
该Series对象的索引index会被传给matplotlib,并用以绘制X轴。可以通过use_index=False禁用该功能。
DataFrame的plot方法会在一个subplot中为各列绘制一条线,并自动创建图例(如图9-14所示):

In [200]: df = pd.DataFrame(np.random.rand(10,4).cumsum(0),columns=['A','B','C','D'],index=n
     ...: p.arange(0,100,10))

In [201]: df
Out[201]:
           A         B         C         D
0   0.685788  0.297513  0.651090  0.445658
10  1.557753  0.813536  1.338988  0.993341
20  2.433134  1.193840  1.840116  1.262187
30  3.356239  1.889819  2.715777  1.779696
40  3.831967  2.843798  3.342842  2.269416
50  4.688547  3.843593  3.982264  2.882778
60  5.546727  4.640172  4.857665  3.075847
70  6.233858  5.135775  5.343059  3.692292
80  6.597572  5.355745  5.709290  3.919498
90  7.127534  6.151853  5.731094  4.640323

In [202]: df.plot()
Out[202]: <matplotlib.axes._subplots.AxesSubplot at 0x2b35390ac18>

In [203]: plt.show()

《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图

柱状图

plot.bar()和plot.barh()分别绘制水平和垂直的柱状图。这时,Series和DataFrame的索引将会被用作X(bar)或Y(barh)刻度(如图9-15所示):

In [206]: fig,axes = plt.subplots(2,1)

In [207]: data = pd.Series(np.random.randn(16),index = list('abcdefghijklmnop'))

In [208]: data.plot.bar(ax=axes[0],color='k',alpha=0.7)  #alpha为图表的填充不透明度
Out[208]: <matplotlib.axes._subplots.AxesSubplot at 0x2b353c8b358>

In [209]: data.plot.barh(ax=axes[1],color='k',alpha=0.7)
Out[209]: <matplotlib.axes._subplots.AxesSubplot at 0x2b353cb95f8>

In [210]: plt.show()

《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图
color='k’和alpha=0.7设定了图形的颜色为黑色,并使用部分的填充透明度。对于DataFrame,柱状图会将每一行的值分为一组,并排显示:

In [211]: df = pd.DataFrame(np.random.rand(6, 4), index=['one', 'two', 'three', 'four', 'fiv
     ...: e', 'six'],columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))

In [212]: df
Out[212]:
Genus         A         B         C         D
one    0.783765  0.973372  0.397304  0.668468
two    0.849481  0.883813  0.059709  0.620467
three  0.188168  0.387766  0.975336  0.781791
four   0.996210  0.188114  0.205050  0.492547
five   0.404493  0.192918  0.305952  0.436618
six    0.475883  0.312828  0.720343  0.637083

In [213]: df.plot.bar()
Out[213]: <matplotlib.axes._subplots.AxesSubplot at 0x2b353d3c6a0>

In [215]: plt.show()

《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图

传入stacked=True产生堆叠效果:

In [216]: df.plot.bar(stacked=True)
Out[216]: <matplotlib.axes._subplots.AxesSubplot at 0x2b3538fef28>
In [217]: plt.show()

《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图

直方图和密度图

seaborn的distplot方法绘制直方图和密度图更加简单,还可以同时画出直方图和连续密度估计图。作为例子,考虑一个双峰分布,由两个不同的标准正态分布组成

In [219]: import seaborn as sns

In [220]: comp1 = np.random.normal(0,1,size=200)

In [221]: comp2 = np.random.normal(10,2,size=200)

In [222]: values = pd.Series(np.concatenate([comp1,comp2]))

In [223]: sns.distplot(values,bins=100,color='k')
D:\software\anaconda\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
  return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
Out[223]: <matplotlib.axes._subplots.AxesSubplot at 0x2b3566879e8>
In [224]: plt.show()

《利用python进行数据分析》学习记录——使用Pandas和seaborn绘图

感觉《利用python进行数据分析》一书里关于seaborn库的内容不是很详细,打算再找找别的资料学一下。