使用 matplotlib 繪製 .txt 檔案資料


要使用 matplotlib 繪製 .txt 檔案中的資料,我們可以採取以下步驟 −

  • 設定圖形大小並調整子圖之間及周圍的填充。
  • 為 bar_names 和 bar_heights 初始化空列表。
  • 以讀取“r”模式的開啟一個示例 .txt 檔案,並附加到柱狀圖的名稱和高度列表中。
  • 繪製柱狀圖。
  • 要顯示圖形,可以使用 show() 方法。

示例

from matplotlib import pyplot as plt

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

bar_names = []
bar_heights = []

for line in open("test_data.txt", "r"):
bar_name, bar_height = line.split()
bar_names.append(bar_name)
bar_heights.append(bar_height)

plt.bar(bar_names, bar_heights)

plt.show()

test_data.txt”包含以下資料 −

Javed  12
Raju   14
Rishi  15
Kiran  10
Satish 17
Arun   23

輸出

會生成以下輸出

更新於: 21-Sep-2021

4K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告