如何将此数据从文本文件减少到折线图 (Python)
How to reduce this data from a text file to a line graph (Python)
我在 .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 的新手,所以我可以想象这是基本的东西。任何帮助将不胜感激。
谢谢
这样的事情怎么样?
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()
输出:
或者,使用 pandas:
# 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()
我在 .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 的新手,所以我可以想象这是基本的东西。任何帮助将不胜感激。
谢谢
这样的事情怎么样?
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()
输出:
或者,使用 pandas:
# 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()