import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pandas和seaborn绘图
折线图
s = pd.Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s
0 0.581758
10 0.927844
20 4.121972
30 3.849217
40 2.643392
50 1.699543
60 1.385943
70 0.623487
80 0.241257
90 0.363434
dtype: float64
s.plot() #默认情况下plot()绘制的是折线图
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d17a9b0>
df = pd.DataFrame(np.random.randn(10,4).cumsum(0),columns=['A','B','C','D'],index=np.arange(0,100,10))
df
A | B | C | D | |
---|---|---|---|---|
0 | -0.454374 | 0.397938 | 0.356842 | 0.071766 |
10 | 1.063938 | -0.929580 | 0.496221 | 0.142492 |
20 | 0.526858 | -0.747939 | -1.405797 | 0.209039 |
30 | 1.022407 | -0.763073 | -2.209488 | 0.071781 |
40 | -0.474689 | -0.782196 | -1.225337 | -0.438294 |
50 | 0.903410 | 0.287945 | -0.837782 | -1.096535 |
60 | 0.473978 | -1.000205 | -0.728329 | -2.816553 |
70 | 0.327923 | -0.646799 | -0.635620 | -3.117912 |
80 | 0.350638 | -1.914932 | -1.410239 | -5.526775 |
90 | 0.446866 | -1.988524 | -1.112387 | -6.427741 |
df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d2c54e0>
plot属性包含了不同绘图类型的方法族。df.plot()等价于df.plot.line().
柱状图
plot.bar()和plot.barh()可以分别绘制垂直和水平的柱状图。
Series或DataFrame的索引将会被用作x轴刻度(bar)或y轴刻度(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将柱子颜色设置为黑色,并将图像的填充色设置为部分透明。
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d37dc50>
df = pd.DataFrame(np.random.rand(6,4),index=['one','two','three','four','five','six'],columns=pd.Index(['A','B','C','D'],name='Genus'))
df
Genus | A | B | C | D |
---|---|---|---|---|
one | 0.116333 | 0.547558 | 0.057368 | 0.763959 |
two | 0.790697 | 0.546626 | 0.408781 | 0.676374 |
three | 0.604865 | 0.557059 | 0.530665 | 0.289824 |
four | 0.567244 | 0.798429 | 0.782860 | 0.712815 |
five | 0.628094 | 0.005699 | 0.439503 | 0.644901 |
six | 0.222623 | 0.442521 | 0.947737 | 0.848191 |
df.plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d335278>
DataFrame的列名称“Genus”被用作了图例标题。通过传递stacked=Ture来生成堆积柱状图,使得每一行的值堆积在一起.
df.plot.barh(stacked=True,alpha=0.5)
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d478da0>
tips = pd.read_csv('examples/tips.csv')
party_counts = pd.crosstab(tips['day'],tips['size'])
party_counts
size | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|
day | ||||||
Fri | 1 | 16 | 1 | 1 | 0 | 0 |
Sat | 2 | 53 | 18 | 13 | 1 | 0 |
Sun | 0 | 39 | 15 | 18 | 3 | 1 |
Thur | 1 | 48 | 4 | 5 | 1 | 3 |
party_counts = party_counts.loc[: ,2:5]
party_counts
size | 2 | 3 | 4 | 5 |
---|---|---|---|---|
day | ||||
Fri | 16 | 1 | 1 | 0 |
Sat | 53 | 18 | 13 | 1 |
Sun | 39 | 15 | 18 | 3 |
Thur | 48 | 4 | 5 | 1 |
#标准化至和为1
party_pcts = party_counts.div(party_counts.sum(1),axis=0)
party_pcts
size | 2 | 3 | 4 | 5 |
---|---|---|---|---|
day | ||||
Fri | 0.888889 | 0.055556 | 0.055556 | 0.000000 |
Sat | 0.623529 | 0.211765 | 0.152941 | 0.011765 |
Sun | 0.520000 | 0.200000 | 0.240000 | 0.040000 |
Thur | 0.827586 | 0.068966 | 0.086207 | 0.017241 |
party_pcts.plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d640198>
import seaborn as sns
tips['tip_pct'] = tips['tip']/(tips['total_bill'] - tips['tip'])
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')
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5f29e6a0>
柱子的值是tip_pct的平均值。柱子上面画出的黑线代表的是95%的置信区间.
sns.barplot(x ='tip_pct',y = 'day',hue='time' ,data = tips,orient = 'h')
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5d69bac8>
使用seaborn.set在不同的绘图外观中进行切换.
sns.set(style='whitegrid')
直方图和密度图
tips['tip_pct'].plot.hist(bins=50)
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5f38a1d0>
tips['tip_pct'].plot.density()
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5f381278>
密度图也被称为内核密度估计图(KDE)。 plot.kde
distplot方法可以绘制直方图和连续密度估计。
comp1 = np.random.normal(0,1,size=200)
comp2 = np.random.normal(10,2,size=200)
values = pd.Series(np.concatenate([comp1,comp2]))
sns.distplot(values,bins=100,color='k')
<matplotlib.axes._subplots.AxesSubplot at 0x1ec5f5c7be0>
散点图或点图
点图或散点图可以用于检验两个一维数据序列之间的关系。
macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi','m1','tbilrate','unemp']]
trans_data = np.log(data).diff().dropna()
trans_data[-5:]
cpi | m1 | tbilrate | unemp | |
---|---|---|---|---|
198 | -0.007904 | 0.045361 | -0.396881 | 0.105361 |
199 | -0.021979 | 0.066753 | -2.277267 | 0.139762 |
200 | 0.002340 | 0.010286 | 0.606136 | 0.160343 |
201 | 0.008419 | 0.037461 | -0.200671 | 0.127339 |
202 | 0.008894 | 0.012202 | -0.405465 | 0.042560 |
使用seaborn的regplot方法,绘制散点图。
sns.regplot('m1','unemp',data=trans_data)
plt.title('Changes in log %s versus log %s'%('m1','unemp'))
Text(0.5,1,'Changes in log m1 versus log unemp')
pairplot函数,在对角线上放置每个变量的直方图或密度估计值。
sns.pairplot(trans_data,diag_kind='kde',plot_kws={'alpha':0.2})
<seaborn.axisgrid.PairGrid at 0x1ec60d4add8>
分面网格和分类数据
使用分面网格是利用多种分组变量对数据进行可视化的方式。
seaborn拥有一个有效的内建函数factorplot,它可以简化多种分面绘图。
sns.factorplot(x='day',y='tip_pct',hue='time',col='smoker',kind='bar',data=tips[tips.tip_pct<1])
<seaborn.axisgrid.FacetGrid at 0x1ec612b2cc0>
#通过每个时间值添加一行来扩展分面网格
sns.factorplot(x='day',y='tip_pct',row='time',col='smoker',kind='bar',data=tips[tips.tip_pct<1])
<seaborn.axisgrid.FacetGrid at 0x1ec61483320>
factorplot支持其他可能有用的图类型,具体取决于显示的内容。
sns.factorplot(x='tip_pct',y='day',kind='box',data=tips[tips.tip_pct<0.5])
<seaborn.axisgrid.FacetGrid at 0x1ec61f40860>
小结: 使用pandas和seaborn入门一些基础数据的可视化知识。