matplotlib 将日期添加到图表的X轴会破坏它

w7t8yxp5  于 2023-04-21  发布在  其他
关注(0)|答案(3)|浏览(132)

我有一个CSV文件,它存储了我的互联网连接的上传和下载速度每小时。列是日期,时间,下载,上传和ping。见下文...

230302,2305,835.89,109.91,11.46
230303,0005,217.97,109.58,5.222
230303,0105,790.61,111.41,5.191
230303,0205,724.59,109.23,9.259
230303,0305,820.04,111.06,4.376

当我在x轴上使用0-x时,我可以很好地显示数据,如下例所示:

但是我想在x轴上显示日期,当我这样做时,我得到了这个结果:

我做错了什么?

import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename = 'C:/Users/tim/Documents/p5e/Internet_Speed_Tests.csv'
with open(filename) as f:
    reader = csv.reader(f)

    dates = []
    times = []
    downs = []
    ups = []
    pings = []

    for row in reader:
        #date = int(row[0])
        current_date = datetime.strptime(row[0],'%y%m%d')
        time = int(row[1])
        #current_time = datetime.strptime(row[1],'%H%m')
        #dateandtime = current_date + current_time
        down = float(row[2])
        up = float(row[3])
        ping = float(row[4])

        dates.append(current_date)
        #times.append(current_time)
        downs.append(down)
        ups.append(up)
        pings.append(ping)

fig, ax = plt.subplots()
ax.set_title("Internet Speed", fontsize=24)
ax.set_ylabel("Speed", fontsize=16)
ax.set_xlabel('date', fontsize=16)
fig.autofmt_xdate()
ax.plot(dates, downs)
ax.plot(dates, ups)

plt.show()
m2xkgtsf

m2xkgtsf1#

您没有将小时和分钟添加到时间戳中。如果打印日期列表,您将看到

>>> [datetime.datetime(2023, 3, 2, 0, 0), datetime.datetime(2023, 3, 3, 0, 0), 
    datetime.datetime(2023, 3, 3, 0, 0), datetime.datetime(2023, 3, 3, 0, 0), 
    datetime.datetime(2023, 3, 3, 0, 0)]

所以在上一个图中有多个y值对应相同的x值。
有多种方法可以解决您的问题,其中之一可以是:

for row in reader:
    time_str = row[0] + row[1] # add together date and time
    current_date = datetime.strptime(time_str,'%y%m%d%H%M')
    down = float(row[2])
    up = float(row[3])
    ping = float(row[4])

    dates.append(current_date)
    downs.append(down)
    ups.append(up)
    pings.append(ping)
7gs2gvoe

7gs2gvoe2#

您可以将数据加载到pandas dataframe中,并使用内置的plot方法。
这应该主要是工作:

import pandas as pd
df = pd.read_csv('C:/Users/tim/Documents/p5e/Internet_Speed_Tests.csv')

df.plot(x="date", y="up", label="up")
df.plot(x="date", y="down", label="down")
plt.show()

注意x和y输入

j8ag8udp

j8ag8udp3#

尝试手动设置刻度标签:

import numpy as np

fig, ax = plt.subplots()
ax.set_title("Internet Speed", fontsize=24)
ax.set_ylabel("Speed", fontsize=16)
ax.set_xlabel('date', fontsize=16)

# fig.autofmt_xdate()
ax.plot(dates, downs)
ax.plot(dates, ups)

# setting the x's ticks manually
spacing = 10  # e.g. a tick each 10 - set as you like
ticks = np.array(ax.get_xticks())  # get the ticks
idx = np.arange(0, len(ticks), spacing)  # make indices
labels = np.array(dates)[idx]  # keep a subset of the dates

# set the new ticks with dates as labels
ax.set_xticks(ticks[idx], labels, rotation=30)

plt.show()

相关问题