我有一個 .txt 檔案(該檔案稱為 numbers.txt)中的資料,我想以圖形方式顯示(折線圖)。檔案的內容類似于
6 8 2 4 8 // 1 6 8 9 3 // 1 6 8 5 6 // 3 5 6 8 9 //
其中 // 代表一個新行。
我想做的是撰寫一些代碼,該代碼將占用一列,例如第一個 (6 ,1 ,1 ,3) 并將其顯示在折線圖上。所以這個圖會有坐標 (1, 6), (2, 1), (3, 1), (4, 3)。
我是 python 新手,所以我可以想象這是基本的東西。任何幫助,將不勝感激。
謝謝
uj5u.com熱心網友回復:
這樣的事情呢?
with open('numbers.txt') as f: # read file
data = [list(map(int, S.split())) # numbers as integers
for s in f.read().split(' //') # from split string
if (S:=s.strip())] # walrus operator python ≥ 3.8
import matplotlib.pyplot as plt
# create axes
ax = plt.subplot()
# set up X values
xs = list(range(1, len(data) 1))
# plot each line
for i, ys in enumerate(zip(*data), start=1):
ax.plot(xs, ys, label=f'line_{i}')
ax.legend()
輸出:

uj5u.com熱心網友回復:
或者,使用熊貓:
# Read the file and store it into an array
file1 = open('numbers.txt', 'r')
Lines = file1.readlines()
data = []
for line in Lines:
x = [int(x) for x in line.strip().split(" ") if x.isdigit()]
data.append(x)
import pandas as pd
#make a dataframe out of the array
df = pd.DataFrame(data)
import matplotlib.pyplot as plt
#plot the first column
df[0].plot()
plt.show()
如果您是初學者,閱讀檔案是一個很好的練習。您可以跳過該部分并立即撰寫以下內容
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('numbers.txt', sep=" ", header=None)
df[0].plot() # df.plot() to plot all the dataframe
plt.legend()
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457252.html
標籤:Python 麻木的 matplotlib 图形
