enter image description here我正在学习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轴代表距离或速度。你知道吗
我从网上找到这个来源。 而这个源头的底部是为测试.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值是相同的。这能解决你的问题吗?你知道吗相关问题 更多 >
编程相关推荐