Reputation: 125
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)
Upvotes: 1
Views: 168
Reputation: 120391
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:
Upvotes: 1
Reputation: 545
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)
Upvotes: 1