如何使用 Matplotlib 繪製 Pandas 資料框的特定行?


要繪製 Pandas 資料框的特定行,我們可以執行以下步驟 −

  • 設定圖形大小並調整子圖之間的內邊距和周圍的內邊距。
  • 建立一個 Pandas 資料框,df。它應是二維、大小可變、潛在不均勻的表格資料。
  • 製作 Pandas 圖表行。使用 iloc() 函式切片 df 並列印特定行。
  • 要顯示圖形,請使用 show() 方法。

示例

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(np.random.randn(10, 5), columns=list('abcde'))
df.iloc[0:6].plot(y='e')

print(df.iloc[0:6])

# plt.show()

輸出

資料框中有 10 行。當我們執行程式碼時,它將在控制檯上列印前 6 行,因為 iloc[0:6] 從資料框中切片前 6 行。

      a            b          c          d             e
0 1.826023    0.606137    0.389687    -0.497605     0.164785
1 0.571941    2.324981   -1.154445     0.757724     0.570713
2 -1.328481   1.248171   -0.849694    -1.133029    -0.977927
3 -0.509296   1.086251    0.809288     0.409166    -0.080694
4 0.973164    1.328212    0.858214     0.997309    -0.375427
5 1.014649    1.480790   -1.451903    -0.306659    -0.382312

要繪製此切片資料框,請取消程式碼中最後一行的 plt.show() 註釋並再次執行。

更新於: 2021 年 7 月 8 日

9K+ 瀏覽

開始您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.