猿问

如何加载文本文件并在单个图中绘制多列

我有一个包含 5 列的文本文件。第 1 列是 X 轴(1,2,3,4),其余列是 y 轴。我想将它们绘制在一张图中。


1 0 0 0 0

2 7 14 2.53381 0.0691848

3 6 16 2.61242 0.0507856

4 6 17 2.65154 0.040285

我正在尝试将此代码用于单个y值。


import matplotlib.pyplot as plt

import numpy as np


file_name = input("Enter the file name:")


x, y = np.loadtxt(file_name, delimiter=',', unpack=True)

plt.plot(x,y, label='Loaded from file!')


plt.xlabel('Action')

plt.ylabel('Rate')

plt.title('Plot of Rate')

plt.legend()

plt.show()

如何y提取并绘制多个值?


宝慕林4294392
浏览 151回答 4
4回答

眼眸繁星

用于*y将所有列数据(x 列之后)存储在 y 变量中。delimite=' '如果您的数据是空格分隔的,请使用。因此,只需在加载文件时进行此更正并保留其他代码即可): x, *y = np.loadtxt(file_name, delimiter=',', unpack=True)结果:

慕哥9229398

用于pandas.read_csv读入文件,并将第0列设置为索引根据所示示例使用sep='\\s+',但如果它不是 OP 中的内容,请使用适当的分隔符。根据示例,使用header=None,但根据文件需要进行更改。用于pandas.DataFrame.plot在 1 行中绘制数据框。此外,使用的好处pandas是现在可以轻松分析数据。尝试df.describe()获取按列的统计数据。import pandas as pd# read the filedf = pd.read_csv('file.txt', sep='\\s+', header=None, index_col=0)# add column names if desired; the list must have as many values as there are columnsdf.columns = ['a', 'b', 'c', 'd']# plot the datadf.plot(figsize=(7, 4), xlabel='Action', ylabel='Rate', title='Plot of Rate')数据汇总统计df.describe()             a       b        c        dcount  4.00000   4.000  4.00000  4.00000mean   4.75000  11.750  1.94944  0.04006std    3.20156   7.932  1.30055  0.02926min    0.00000   0.000  0.00000  0.0000025%    4.50000  10.500  1.90036  0.0302150%    6.00000  15.000  2.57312  0.0455475%    6.25000  16.250  2.62220  0.05539max    7.00000  17.000  2.65154  0.06918

慕勒3428872

请检查片段import matplotlib.pyplot as pltimport pandas as pdimport matplotlib.ticker as tickerdf = pd.read_csv('samp.txt', sep=" ", header=None)df.columns = ["x", "y1", "y2", "y3","y4"]print(df)fig, ax = plt.subplots()ax.plot(df['x'],df['y1'], label='Line1')ax.plot(df['x'],df['y2'], label='Line2')ax.plot(df['x'],df['y3'], label='Line3')ax.plot(df['x'],df['y4'], label='Line4')tick_spacing = 1ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))plt.xlabel('Action')plt.ylabel('Rate')plt.title('Plot of Rate')plt.legend()plt.show()

Smart猫小萌

所以首先我将数据加载到 4 个变量中,其中一个是 x,其中三个是 y1、y2、y3,然后我只使用该方法三次以创建'plot'三个不同的图形import matplotlib.pyplot as pltimport numpy as npfile_name = input("Enter the file name:")data = np.loadtxt(file_name, delimiter=',', unpack=True)x = data[0]y1 = data[1] # the first graphy2 = data[2] # the second graphy3 = data[3] # the third graphy4 = data[4] # the fourth graphplt.plot(x,y1, label='y1')plt.plot(x,y2, label='y2')plt.plot(x,y3, label='y3')plt.plot(x,y4, label='y3')plt.xlabel('Action')plt.ylabel('Rate')plt.title('Plot of Rate')plt.legend()plt.show()
随时随地看视频慕课网APP

相关分类

Python
我要回答