码迷,mamicode.com
首页 > 其他好文 > 详细

pandas-21 Series和Dataframe的画图方法

时间:2019-07-26 21:34:40      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:标题   numpy   ESS   col   也有   类型   dem   方便   show   

pandas-21 Series和Dataframe的画图方法

### 前言

在pandas中,无论是series还是dataframe都内置了.plot()方法,可以结合plt.show()进行很方便的画图。

Series.plot() 和 Dataframe.plot()参数

data : Series
kind : str
‘line’ : line plot (default)
‘bar’ : vertical bar plot
‘barh’ : horizontal bar plot
‘hist’ : histogram
‘box’ : boxplot
‘kde’ : Kernel Density Estimation plot
‘density’ : same as ‘kde’
‘area’ : area plot
‘pie’ : pie plot
指定画图的类型,是线形图还是柱状图等
label 添加标签
title 添加标题
……(后接一大堆可选参数)
详情请查阅:官方文档传送门

Dataframe.plot()参数 也是大同小异:
详情请查阅:官方文档传送门

Series.plot()代码demo

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from  pandas import Series

# 创建一个随机种子, 把生成的值固定下来
np.random.seed(666)

s1 = Series(np.random.randn(1000)).cumsum()

s2 = Series(np.random.randn(1000)).cumsum()

# series 中 也包含了 plot 方法
s1.plot(kind = 'line', grid = True, label = 'S1', title = 'xxx')
s2.plot(label = 's2')


plt.legend()
plt.show() # 图1

# 通过 子图的 方式,可视化 series
figure, ax = plt.subplots(2, 1)
ax[0].plot(s1)
ax[1].plot(s2)

plt.legend()
plt.show() # 图2

# 通过 series中的plot方法进行指定是哪一个子图
fig, ax = plt.subplots(2, 1)
s1.plot(ax = ax[1], label = 's1')
s2.plot(ax = ax[0], label = 's2')

plt.legend()
plt.show() # 图3
1234567891011121314151617181920212223242526272829303132333435

图1:
技术图片
图2:
技术图片
图3:
技术图片

Dataframe.plot()代码demo

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series, DataFrame

np.random.seed(666)

df = DataFrame(
    np.random.randint(1, 10, 40).reshape(10, 4),
    columns = ['A', 'B', 'C', 'D']
)
print(df)
'''
   A  B  C  D
0  3  7  5  4
1  2  1  9  8
2  6  3  6  6
3  5  9  5  5
4  1  1  5  1
5  5  6  8  2
6  1  1  7  7
7  1  4  3  3
8  7  1  7  1
9  4  7  4  3
'''

# Dataframe 也有个内置方法 plot
df.plot(kind = 'bar') # kind = 'bar'
plt.show() # 图1

# 横向的柱状图
df.plot(kind = 'barh') # kind = 'barh' 可以是一个横向的柱状图
plt.show() # 图2

# 将每个column的柱状图堆叠起来
df.plot(kind = 'bar', stacked = True)
plt.show() # 图3

# 填充的图
df.plot(kind = 'area')
plt.show() # 图4

# 可以进行选择
b = df.iloc[6] # 这时候的b是一个series
b.plot() # 可以看出x轴就是colume的name
plt.show() # 图5

# 可以将所有的行全部画在一张图里
for i in df.index:
    df.iloc[i].plot(label = str(i))
plt.legend()
plt.show() # 图6

# 对一列进行画图
df['A'].plot()
plt.show() # 图7
# 多列画图,同上

# 注意:默认是按照column来进行画图的,
# 如果需要按照 index 画图,可以将 dataframe 转置一下
df.T.plot()
plt.show() # 图8
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162

图1:
技术图片
图2:
技术图片
图3:
技术图片
图4:
技术图片
图5:
技术图片
图6:
技术图片
图7:
技术图片
图8:
技术图片

pandas-21 Series和Dataframe的画图方法

标签:标题   numpy   ESS   col   也有   类型   dem   方便   show   

原文地址:https://www.cnblogs.com/wenqiangit/p/11252847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!