0

What I want to do is read from a .csv file and then plot the data read. The file has the below format:

Date/Time,Humidity,Temperature

00:00:56,90.00,16.90 00:01:56,90.00,16.90 00:02:56,90.00,16.90 00:03:56,91.00,16.90 00:04:56,90.00,16.90 00:05:56,91.00,16.90 00:06:56,91.00,16.90 00:07:56,91.00,16.90 00:08:56,91.00,16.90 00:09:56,91.00,16.90 00:10:56,91.00,16.90 00:11:56,91.00,16.90 00:12:56,91.00,16.90 00:13:56,91.00,16.90 00:14:56,91.00,16.90 00:15:56,91.00,16.90 00:16:56,91.00,16.90 00:17:56,91.00,16.80 00:18:56,91.00,16.90

Then after reading the data I'm formatting them in datetime using the below code:

data = pd.read_csv("Data-24-January-2021.csv")

data["Date/Time"] = pd.to_datetime(data["Date/Time"])

data.sort_values("Date/Time", inplace=True)

dt_time = data["Date/Time"]

When I try to print dt_time I get ->

0 2021-01-25 00:00:56 1 2021-01-25 00:01:56 2 2021-01-25 00:02:56 3 2021-01-25 00:03:56 4 2021-01-25 00:04:56 ...
1435 2021-01-25 23:55:46 1436 2021-01-25 23:56:46 1437 2021-01-25 23:57:46 1438 2021-01-25 23:58:46 1439 2021-01-25 23:59:46 Name: Date/Time, Length: 1440, dtype: datetime64[ns]

So when I try to plot the data, in x-axis I get something like this:

Current Plot I'm getting

I want to get rid of the 01-25 in the plot.

I've managed getting only the time from the .csv file but with all the methods I tried it returned dtype: object, so the plot takes too long to plot and isn't displaying correctly the x-axis.

enter image description here

Can you please advise on which is the best way to approach this? What I basically want is to read the Date/Time from the .csv file and plot it in x-axis, without the 01-25.

The code I'm currently running is the below:

import pandas as pd
import os
from matplotlib import pyplot as plt
from datetime import datetime


plt.style.use("seaborn")

data = pd.read_csv("Data-24-January-2021.csv")


data["Date/Time"] = pd.to_datetime(data["Date/Time"])


data.sort_values("Date/Time", inplace=True)

dt_time = data["Date/Time"].dt.strftime("%H :%M")
# print(dt_time)

humidity = data["Humidity"]
temperature = data["Temperature"]


# plt.plot(dt_time, humidity, label="Humidity")

plt.plot(dt_time, temperature, label="Temperature")

plt.gcf().autofmt_xdate()

plt.legend(loc="upper left")

plt.title("Test Plot")

plt.xlabel("Time")
plt.ylabel("Temperature")

plt.tight_layout()
plt.savefig("Figure_example3.png")
plt.show()
fio_10
  • 63
  • 2
  • 9
  • 1
    It seems you should use the [matplotlib DateFormatter](https://stackoverflow.com/a/65343940/8881141) with ``%H:%M` instead of changing Date/Time in your dataframe. – Mr. T Jan 25 '21 at 12:27
  • Thank you so much, using DateFormatter works fine. – fio_10 Jan 25 '21 at 12:54

0 Answers0