import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Series.plot和DataFrame.plot是plt.plot的一个简单包装
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.head()
2000-01-01 -1.158434
2000-01-02 -1.234039
2000-01-03 -1.453900
2000-01-04 -1.969126
2000-01-05 -2.358607
Freq: D, dtype: float64
ts.plot()
DataFrame.plot是同时绘制每一列到同一个图,并且附带了标签
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.head()
A | B | C | D | |
---|---|---|---|---|
2000-01-01 | 0.687417 | -0.943176 | -0.562482 | 0.398902 |
2000-01-02 | 1.918521 | -0.743811 | -0.974949 | 2.073606 |
2000-01-03 | 3.265497 | -2.035723 | 0.756734 | 1.309357 |
2000-01-04 | 4.643224 | -2.233020 | 0.146825 | 0.574324 |
2000-01-05 | 5.735268 | -3.260842 | 1.409548 | 1.479241 |
df.plot()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jw1Faufq-1579503959330)(images/output_7_1.png)]
你可以使用plot中的x和y关键字绘制一列与另一列的关系:
df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
df3['A'] = pd.Series(list(range(len(df))))
df3.plot(x='A', y='B')
Series.plot或DataFrame.plot默认都是线图,其他类型的图需要修改参数kind
,支持以下几种类型的图:
df.iloc[5].plot(kind='bar')
除了修改kind
参数之外,还支持DataFrame.plot.<>,如 DataFrame.plot.bar 等价于 DataFrame.plot(kind=‘bar’)
df.iloc[5].plot.bar()
除了以上两种方式,有的绘图类型还支持单独的接口:
df.hist()
array([[,
],
[,
]],
dtype=object)
Series.plot.bar会绘制一个条形图
plt.figure()
plt.axhline(0, color='k')
df.iloc[5].plot.bar()
DataFrame.plot.bar会绘制多个条形图
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2.plot.bar()
绘制一个堆条形图,传递参数 stack=True
df2.plot.bar(stacked=True)
绘制横向条形图,调用DataFrame.plot.barh
df2.plot.barh()
df4 = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000), 'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])
df4.plot.hist(alpha=0.5) # 透明度
堆直方图 传递参数stacked=True
df4.plot.hist(stacked=True,bins=20) # bins步数
你可以通过matplotlib的hist函数传递别的参数,如horizontal、cumulative
df4['a'].plot.hist(orientation='horizontal', cumulative=True)
更多关于hist方法的使用 点击这里和这里
DataFrame.plot.hist和DataFrame.hist的区别
df4.hist()
array([[,
],
[,
]],
dtype=object)
df4.plot.hist()
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.plot.box()
自定义箱型图的各个部件的颜色
color = {'boxes': 'DarkGreen', 'whiskers': 'DarkOrange', 'medians': 'DarkBlue', 'caps': 'Gray'}
df.plot.box(color=color, sym='r+') # sym参数表示异常点的形状
当然,你也可以传递matplotlib中的boxplot支持的参数,如vert=False
position=[1,4,5,6,8]
df.plot.box(vert=False, positions=[1,4,6,8,15])
DataFrame.boxplot和DataFrame.plot.box的区别 (没啥区别,不像hist)
df.plot.box()
df.boxplot()
你可以指定by
参数来创建组
df = pd.DataFrame(np.random.rand(10, 2), columns=['Col1', 'Col2'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'])
df.boxplot(by='X') # 按照列X来分组绘制 两列col1 col2的箱型图
array([,
],
dtype=object)
by
参数支持多个列
df = pd.DataFrame(np.random.rand(10, 3), columns=['Col1', 'Col2', 'Col3'])
df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'])
df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'])
df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])
array([,
],
dtype=object)
df = pd.DataFrame(np.random.rand(10, 4), columns=['a','b','c','d'])
df.plot.area()
绘制一个没有堆叠的面积图,调用参数stacked=False
df.plot.area(stacked=False) # 此时透明度默认值=0.5
df = pd.DataFrame(np.random.rand(50,4),columns=['a','b','c','d'])
df.plot.scatter(x='a', y='b') # 散点图必须指定参数x和y
在同一个图中绘制多个列的散点图,调用参数ax
ax = df.plot.scatter(x='a',y='b',color='DarkBlue',label='Group1')
df.plot.scatter(x='c', y='d', color='DarkGreen', label='Group2', ax=ax)
为每个点指定颜色,调用参数c
df.plot.scatter(x='a',y='b',c='c', s=50) # s为点的size
为每个点指定大小,调用参数s
df.plot.scatter(x='a',y='b',s=df['c']*200)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df['b'] = df['b'] + np.arange(1000)
df.plot.hexbin(x='a', y='b', gridsize=25)
网格的size可以通过gridsize
参数控制
df.plot.hexbin(x='a', y='b', gridsize=2)
series = pd.Series(3*np.random.rand(4),index=['a','b','c','d'],name='series')
series.plot.pie(figsize=(6,6))
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])
df.plot.pie(subplots=True, figsize=(8, 4))
array([,
],
dtype=object)
饼图的一些常用参数:labels
fontsize
colors
autopct
figsize
series.plot.pie(labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'], autopct='%.2f', fontsize=20, figsize=(6,6))
如果绘制数据之和小于1 得到的是一个扇形
pd.Series([0.1]*5).plot.pie()
绘图类型 | 缺失值处理方法 |
---|---|
线图 | 在缺失处留空白 |
堆线图 | 填充0 |
条形图 | 填充0 |
散点图 | 舍弃缺失值 |
直方图 | 按列舍弃缺失值 |
箱型图 | 按列舍弃缺失值 |
面积图 | 填充0 |
KDE | 按列舍弃缺失值 |
六边形图 | 舍弃缺失值 |
饼图 | 填充0 |
from pandas.plotting import scatter_matrix
df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
scatter_matrix(df, alpha=0.2,figsize=(6,6),diagonal='kde')
array([[,
,
,
],
[,
,
,
],
[,
,
,
],
[,
,
,
]],
dtype=object)
ser = pd.Series(np.random.randn(1000))
ser.plot.kde()
from pandas.plotting import andrews_curves
from sklearn import datasets
data= pd.DataFrame(datasets.load_iris().data)
data.head()
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 |
1 | 4.9 | 3.0 | 1.4 | 0.2 |
2 | 4.7 | 3.2 | 1.3 | 0.2 |
3 | 4.6 | 3.1 | 1.5 | 0.2 |
4 | 5.0 | 3.6 | 1.4 | 0.2 |
andrews_curves(data, 0)
from pandas.plotting import parallel_coordinates
parallel_coordinates(data, 1)
from pandas.plotting import lag_plot
spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)
data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))
lag_plot(data)
from pandas.plotting import autocorrelation_plot
spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
data = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
autocorrelation_plot(data)
from pandas.plotting import bootstrap_plot
data = pd.Series(np.random.rand(1000))
bootstrap_plot(data)
from pandas.plotting import radviz
data = pd.DataFrame(datasets.load_iris().data)
radviz(data, 1)
略
详见此处