利用Python进行数据分析第二版复现(八)

第09章 绘图和可视化

9.1 matplotlib API入门

%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
data = np.arange(10)
plt.plot(data)
1.png
[]

Figure和Subplot

#matplotlib的图像都位于Figure对象中。你可以⽤plt.figure创建1个新的Figure
fig = plt.figure()

#多图框
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)#把图像分为2*2,并且选择第一个。
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
3.png

如果这时执行一条绘图命令(如plt.plot([1.5, 3.5, -2, 1.6])),matplotlib就会在最后1个用过的subplot(如果没有则创建1个)上进行绘制。
subplot相关参数:


41.png
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
plt.plot(np.random.randn(50).cumsum(), 'k--')
ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
4.png





调整subplot周围的间距

利用Figure的subplots_adjust方法可以轻而易举地修改间距,

#subplots_adjust(left=None, bottom=None, right=None, top=None,
#                wspace=None, hspace=None)
#wspace和hspace用于控制宽度和高度的百分比,
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
    for j in range(2):
        axes[i, j].hist(np.random.randn(500), bins=50, color='k', alpha=0.5)
plt.subplots_adjust(wspace=0, hspace=0)
5.png

颜色、标记和线型

from numpy.random import randn
plt.plot(randn(30).cumsum(), 'ko--')

6.png
[]
plt.plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o')

7.png
[]
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
plt.legend(loc='best')


8.png

刻度、标签和图例

设置标题、轴标签、刻度以及刻度标签

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


9.png
[]
#要改变x轴刻度,最简单的办法是使用set_xticks和set_xticklabels。
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
                            rotation=30, fontsize='small')
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')
ax.plot(np.random.randn(1000).cumsum())

10.png

添加图例

最简单的是在添加subplot的时候传入label参数.

from numpy.random import randn
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()或plt.legend()来自动创建图例
ax.legend(loc='best')
#loc告诉matplotlib要将图例放在哪。如果你不是吹毛求疵的话,"best"是不错的选择,因为它会选择最
#不碍事的位置。

在这里插入图片描述

注解以及在Subplot上绘图

from datetime import datetime
fig = plt.figure()

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

data = pd.read_csv('examples/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) + 75),
                xytext=(date, spx.asof(date) + 225),
                arrowprops=dict(facecolor='black', headwidth=4, width=2,
                                headlength=4),
                horizontalalignment='left', verticalalignment='top')
# Zoom in on 2007-2010
ax.set_xlim(['1/1/2007', '1/1/2011'])
ax.set_ylim([600, 1800])

ax.set_title('Important dates in the 2008-2009 financial crisis')

在这里插入图片描述
Text(0.5, 1.0, 'Important dates in the 2008-2009 financial crisis')
#图形绘制
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.savefig可以将当前图表保存到文件
plt.savefig('figpath.png', dpi=400, bbox_inches='tight')
from io import BytesIO
buffer = BytesIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()

还有一些savefig的参数:


在这里插入图片描述

matplotlib配置
matplotlib自带一些配色方案,以及为生成出版质量的图片而设定的默认配置信息.
9.2 使用pandas和seaborn绘图
线型图
Series和DataFrame都有一个用于生成各类图表的plot方法。 plot参数如下图


在这里插入图片描述

DataFrame还有一些用于对列进行灵活处理的选项。


在这里插入图片描述
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()

在这里插入图片描述

df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
                  columns=['A', 'B', 'C', 'D'],
                  index=np.arange(0, 100, 10))
df.plot()

在这里插入图片描述

柱状图

plot.bar()和plot.barh()分别绘制水平和垂直的柱状图。

fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
data.plot.bar(ax=axes[0], color='k', alpha=0.7)
data.plot.barh(ax=axes[1], color='k', alpha=0.7)

在这里插入图片描述

#color='k'和alpha=0.7设定了图形的颜色为黑色,并使用部分的填充透明度。
df = pd.DataFrame(np.random.rand(6, 4),
                  index=['one', 'two', 'three', 'four', 'five', 'six'],
                  columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
print(df)
df.plot.bar()
Genus         A         B         C         D
one    0.723298  0.853998  0.565488  0.273296
two    0.048097  0.969580  0.735727  0.950350
three  0.403365  0.944421  0.183394  0.710260
four   0.448636  0.359694  0.603251  0.106916
five   0.399786  0.747887  0.952541  0.890342
six    0.819866  0.459968  0.981807  0.548266




在这里插入图片描述

```


#设置stacked=True即可为DataFrame生成堆积柱状图,这样每行的值就会被堆积在1起
df.plot.barh(stacked=True, alpha=0.5)


tips = pd.read_csv('examples/tips.csv')
party_counts = pd.crosstab(tips['day'], tips['size'])
party_counts = party_counts.loc[:, 2:5]
party_pcts = party_counts.div(party_counts.sum(1), axis=0)
import seaborn as sns
tips['tip_pct'] = tips['tip'] / (tips['total_bill'] - tips['tip'])
print(tips.head())
total_bill   tip smoker  day    time  size   tip_pct
0       16.99  1.01     No  Sun  Dinner     2  0.063204
1       10.34  1.66     No  Sun  Dinner     3  0.191244
2       21.01  3.50     No  Sun  Dinner     3  0.199886
3       23.68  3.31     No  Sun  Dinner     2  0.162494
4       24.59  3.61     No  Sun  Dinner     4  0.172069
sns.barplot(x='tip_pct', y='day', data=tips, orient='h')


直方图和密度图

tips['tip_pct'].plot.hist(bins=50)#直方图


tips['tip_pct'].plot.density()#密度图


#使用双峰分布举例
comp1 = np.random.normal(0, 1, size=100)#数组生成
comp2 = np.random.normal(10, 2, size=100)#产生数组
values = pd.Series(np.concatenate([comp1, comp2]))#生成数组
sns.distplot(values, bins=100, color='k')


散布图或点图

macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data = np.log(data).diff().dropna()
#使用seaborn的regplot方法,它可以做1个散布图,并加上1条线性回归的线
sns.regplot('m1', 'unemp', data=trans_data)
plt.title('Changes in log %s versus log %s' % ('m1', 'unemp'))

Text(0.5, 1.0, 'Changes in log m1 versus log unemp')
sns.pairplot(trans_data, diag_kind='kde', plot_kws={'alpha': 0.2})


分面网格(facet grid)和类型数据

sns.factorplot(x='day', y='tip_pct', hue='time', col='smoker',
               kind='bar', data=tips[tips.tip_pct < 1])
sns.factorplot(x='day', y='tip_pct', row='time',
               col='smoker',
               kind='bar', data=tips[tips.tip_pct < 1])
E:\anaconda\lib\site-packages\seaborn\categorical.py:3666: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
  warnings.warn(msg)







sns.factorplot(x='tip_pct', y='day', kind='box',
                data=tips[tips.tip_pct < 0.5])

在这里插入图片描述

说明:
放上参考链接,复现的这个链接中的内容。
放上原链接: https://www.jianshu.com/p/04d180d90a3f
作者在链接中放上了书籍,以及相关资源。因为平时杂七杂八的也学了一些,所以这次可能是对书中的部分内容的复现。也可能有我自己想到的内容,内容暂时都还不定。在此感谢原作者SeanCheney的分享

你可能感兴趣的:(利用Python进行数据分析第二版复现(八))