[英]Python graph from txt(csv) file and there are 5 columns, How Can I pick 3rd or 4th columns for y axis?
在这里输入图像描述,我正在研究Python matplotlib。 我有txt文件,其中包括4列。
但是我想从txt中选择第3列或第4列。
我尝试和研究,但是我的编码中有很多错误。 我是python编程的初学者,所以我自己很难处理。 请问你能帮帮我吗?
Date | Time | distance | speed
2016/08/25 02:19:39 0.0006 0.6406
2016/08/25 02:19:40 0.0013 2.7856
2016/08/25 02:19:40 0.0019 2.4938
2016/08/25 02:19:42 0.0025 2.1624
2016/08/25 02:19:43 0.0031 1.7867
2016/08/25 02:19:45 0.0038 1.2161
2016/08/25 02:19:50 0.0044 0.4524
2016/08/25 02:19:51 0.0050 1.7881
2016/08/25 02:19:54 0.0057 0.7540
2016/08/25 02:19:55 0.0063 2.7822
我想制作一个图表,其中x轴表示日期和时间,y轴表示距离或速度。
我从互联网上找到了这个来源。 并且此源的底部适用于test.txt。
Date | Time | distance
2016/08/26 23:45:30 0.0088
2016/08/26 23:45:35 0.0094
2016/08/26 23:45:36 0.0101
2016/08/26 23:45:38 0.0107
2016/08/26 23:45:39 0.0113
2016/08/26 23:45:42 0.0119
2016/08/26 23:45:47 0.0126
2016/08/26 23:45:48 0.0132
2016/08/26 23:45:50 0.0138
2016/08/26 23:45:51 0.0145
2016/08/26 23:45:52 0.0151
2016/08/26 23:45:54 0.0157
码:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import numpy as np
# Converter function
datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%Y/%m/%d %H:%M:%S'))
# Read data from 'file.dat'
dates, levels = np.genfromtxt('sss.txt', # Data to be read
delimiter=19, # First column is 19 characters wide
converters={0: datefunc}, # Formatting of column 0
dtype=float, # All values are floats
unpack=True) # Unpack to several variables
fig = plt.figure()
ax = fig.add_subplot(111)
# Configure x-ticks
ax.set_xticks(dates) # Tickmark + label at every plotted point
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d %H:%M'))
ax.set_ylabel('y')
ax.plot_date(dates, levels, ls='-', marker='o')
ax.set_title('How many km does my hamster runs?')
ax.set_ylabel('Distance (km)')
ax.grid(True)
# Format the x-axis for dates (label formatting, rotation)
fig.autofmt_xdate(rotation=45)
fig.tight_layout()
fig.show()
这是一个可行的示例。 data.txt
的数据与您的第一个示例相同。 我使用np.loadtxt加载文本文件。 我提出的可选参数是:1) unpack=True
,以便将数据放入不同的变量中,如我的示例所示; 2) skiprows=2
不读取文件头; 3) dtype='string'
将数据解析为字符串。 以字符串形式加载数据会迫使您将数据转换为浮点数或日期时间对象。 完成加载后,这是使用matplotlib绘制数据的一种简单方式。 为了清楚起见,我使用twinx
共享x轴,因为x值相同。 这能解决您的问题吗?
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
plt.close('all')
filepath = 'data.txt'
date, ttime, dist, vel = np.loadtxt(filepath, unpack=True, skiprows=2, dtype='string')
timestamps = [datetime.strptime(ddate+'-'+tt, '%Y/%m/%d-%H:%M:%S') for ddate, tt in zip(date, ttime)]
dist = map(float, dist)
vel = map(float, vel)
fig, ax_dist = plt.subplots()
ax_vel = ax_dist.twinx()
ax_dist.plot(timestamps, dist, 'r')
ax_vel.plot(timestamps, vel, 'g')
ax_dist.set_ylabel('Distance')
ax_vel.set_ylabel('Velocity')
ax_dist.set_xlabel('Time')
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.