pandas中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

圖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

圖1:
在這裏插入圖片描述
圖2:
在這裏插入圖片描述
圖3:
在這裏插入圖片描述
圖4:
在這裏插入圖片描述
圖5:
在這裏插入圖片描述
圖6:
在這裏插入圖片描述
圖7:
在這裏插入圖片描述
圖8:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章