1

I have one csv file:

year;month;day;hour;min;sec;temperature
2022;10;27;13;36;42;5.835
2022;10;27;14;36;42;6.435
2022;10;27;15;36;42;6.335
2022;10;27;16;36;42;6.435

And I would like to plot a simple graph from it. I am not able to combine separate datetime parts. This is my code:

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

def parser(year, month, day, hour, minute, second):
    return pd.to_datetime(day + '.' + month + '.' + year + ' ' + hour + ':' + minute + ':' + second

df = pd.read_csv('temp_data.csv',sep=';',parse_dates={'datetime':['year', 'month', 'day', 'hour', 'min', 'sec']}, date_parser=parser,index_col=0)

time = df['datetime'].values
temp = df['temperature'].values

plt.plot(time, temp)
2

2 Answers 2

1

Update

I would like the x-axis date format to be: 27.10.22

You have to handle manually formatting.

Simply use df.plot:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# df = pd.read_csv(...)

ax = df.plot()
loc = mdates.DayLocator()
fmt = mdates.DateFormatter('%d.%m.%y')
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(fmt)
plt.show()

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, I also get the graph but unfortunately cannot get the x-axis dates right. Pleas see the picture: Link
I would like the x-axis date format to be: 27.10.22
Thank you! The x-axis format is right, but the numbers are wrong. I think the problem is in function: parse_dates. Does Pandas know, that for example "second" means it is part on time... Here is picture: Link
Also tried: ax = df.plot(x='datetime',y='tempc')
If I write in console: df.info(), it says that datetime type is "object" but should be "datetime[ns]"
|
1

I couldn't make your code work on my pc using python 3.11

df = pd.read_csv(
    "temp_data.csv",
    sep=";",
    parse_dates={"datetime": ["year", "month", "day", "hour", "min", "sec"]},
    date_parser=parser,
    # index_col=0, this line was causing the problem
)

My plot wouldn't show as well, so I had to do this too:

plt.plot(time, temp)
plt.show(block=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.