在我的图表上添加日期到X轴会导致它出现问题。

huangapple go评论55阅读模式
英文:

Adding Dates to the X axis on my graph breaks it

问题

我有一个CSV文件,记录了我的互联网连接每小时的上传和下载速度。列分别是日期、时间、下载、上传和ping。见下方...

然而,当我尝试在x轴上显示日期时,我得到了这个结果:[V2示例](https://i.stack.imgur.com/3Vftp.png)

我在这里做错了什么?

英文:

I have a CSV file that stores an upload and download speed of my Internet connection every hour.
The columns are Date, Time, Download, Upload & ping. see below...

> 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

I can display the data fine when I just use 0-x on the x axis like the example below:
在我的图表上添加日期到X轴会导致它出现问题。

However I want to display dates on the x Axis and when I do this I get this result:
在我的图表上添加日期到X轴会导致它出现问题。

What am I doing wrong here?

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()

答案1

得分: 1

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

[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)]

所以在你的最后一个图表中,相同的 x 值有多个 y 值。<br>
修复此问题的方法有多种,其中一种可以是:

for row in reader:
    time_str = row[0] + row[1] # 将日期和时间相加
    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)
英文:

You are not adding hour and minutes to your timestamp. If you print the dates list you will see

&gt;&gt;&gt; [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)]

so there are multiple y values for same x values in your last plot. <br>
There are multiple ways to fix your issue, one can be:

for row in reader:
    time_str = row[0] + row[1] # add together date and time
    current_date = datetime.strptime(time_str,&#39;%y%m%d%H%M&#39;)
    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)

答案2

得分: 0

你可以将数据加载到 pandas 数据框中,然后使用内置的绘图方法。

这部分代码应该有效:

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 输入的是。

英文:

You can load your data into a pandas dataframe and use the in-built plot method.

This should mostly work:

import pandas as pd
df = pd.read_csv(&#39;C:/Users/tim/Documents/p5e/Internet_Speed_Tests.csv&#39;)

df.plot(x=&quot;date&quot;, y=&quot;up&quot;, label=&quot;up&quot;)
df.plot(x=&quot;date&quot;, y=&quot;down&quot;, label=&quot;down&quot;)
plt.show()

Note that the x and y input

答案3

得分: 0

以下是您要翻译的代码部分:

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()
英文:

Try setting the ticks labels manually:

import numpy as np

fig, ax = plt.subplots()
ax.set_title(&quot;Internet Speed&quot;, fontsize=24)
ax.set_ylabel(&quot;Speed&quot;, fontsize=16)
ax.set_xlabel(&#39;date&#39;, fontsize=16)

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

# setting the x&#39;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()

huangapple
  • 本文由 发表于 2023年4月13日 17:32:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定