Issue
I am attempting to create a plot with Temperature on the Y axis, and date and time on the X Axis. My data appears to plot correctly, however the date and time does not. My date and time data is in column 0 of my csv, Labeled in the format m/d/Y H:M:S, example: 6/13/2022 2:36:00 PM. Instead of this expected format Time appears as simple integers starting from 0 and going up to 10000.
#Import libraries
from dataclasses import dataclass
from textwrap import indent
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
import csv
from datetime import datetime
#read the CSV
df = pd.read_csv(r"C:\Users\pmay\Desktop\Python\LOGRPT61.csv", parse_dates=True )
change_format = date_sr.dt.strftime('%m/%d/%Y %H:%M:%S')
#Identify column data
ctrlTC = df.iloc[:,[1,2,3,4,5,6,7,8,]]
#Label Axes
plt.xlabel('Time')
plt.ylabel('Temp [deg C]')
#Plot the data
plt.plot(ctrlTC)# kind='line')
plt.rcParams["figure.figsize"] = [10, 7]
plt.rcParams["figure.autolayout"] = True
line1, = plt.plot([1], label="Control TC1")
line2, = plt.plot([2], label="Control TC2")
line3, = plt.plot([3], label="Control TC3")
line4, = plt.plot([4], label="Control TC4")
line5, = plt.plot([5], label="Control TC5")
line6, = plt.plot([6], label="Control TC6")
line7, = plt.plot([7], label="Control TC7")
line8, = plt.plot([8], label="Control TC8")
plt.legend(loc="upper left")
Which results in:
Updated:
#Import libraries
from dataclasses import dataclass
from textwrap import indent
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
import csv
import os
import datetime as dt
from statistics import mean
from datetime import datetime
from datetime import date
#read the CSV
os.chdir(r"C:\Users\pmay\Desktop\Python")
df = pd.read_csv(r"C:\Users\pmay\Desktop\Python\LOGRPT61.csv",parse_dates=['Time'])
df['Time'] = pd.to_datetime(df['Time'])
#Identify column data
ctrlTC = df.iloc[:,[1,2,3,4,5,6,7,8]]
df.info()
Time = df['Time']
#Label Axes
plt.xlabel('Time')
plt.ylabel('Temp [deg C]')
#Plot the data
x = Time
y = ctrlTC
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.rcParams["figure.figsize"] = [10, 7]
plt.rcParams["figure.autolayout"] = True
line1, = plt.plot([1], label="Control TC1")
line2, = plt.plot([2], label="Control TC2")
line3, = plt.plot([3], label="Control TC3")
line4, = plt.plot([4], label="Control TC4")
line5, = plt.plot([5], label="Control TC5")
line6, = plt.plot([6], label="Control TC6")
line7, = plt.plot([7], label="Control TC7")
line8, = plt.plot([8], label="Control TC8")
plt.legend(loc="upper left")
df sample:
Time Loop #1.Process Value Loop #2.Process Value \
0 2022-06-13 14:36:00 25.3 25.0
1 2022-06-13 14:37:00 25.3 25.0
2 2022-06-13 14:38:00 25.3 25.0
3 2022-06-13 14:39:00 25.3 24.9
4 2022-06-13 14:40:00 25.3 25.0
I'm uncertain why the format changes to Y-m-D H:M:S, in the CSV it is given as m/d/Y H:M:S. There are 11240 rows in the CSV (counting headers, 11239 without) from 6/13/2022 to 6/21/2022 at 1 minute intervals.
The ultimate goal is to be able to use the code with other historical and future CSVs to produce graphs as well.
Solution
I have updated your code to what I hope is what you need. Some of the key changes are:
- The date format read from CSV needs to be converted to datetime using pd.to_datetime()
- The CrtlTC should be just a list of all column names, except Time
- Date formatter added, which you can use to control the text you want to show in the X-axis, More information here if you need it
- Simplified the code a bit, so that you loop through the line creation process
- Labels added to legend, so that you can see the customized legend.
Note: As there were only 2 columns of data provided, there are just 2 lines. As mentioned in the question, I have changed the dates in data a bit so that you can see dates from 6/13/2022 to 6/21/2022
Code
import matplotlib.pyplot as plt
from datetime import datetime
df = pd.read_csv("abc.csv")#,parse_dates=['Time'])
df['Time'] = pd.to_datetime(df['Time'], format="%d-%m-%Y %H.%M") # Mention how your text data is
#Identify column data
ctrlTC = df.columns[1:] #Should not be iloc, but all columns except DATE
fig, ax = plt.subplots(figsize=(10, 7))
for col in ctrlTC:
df.plot("Time", col, ax=ax)
#dfmax.plot("Date", "max", ax=ax)
#plt.gcf().autofmt_xdate()
plt.xlabel('Time')
plt.ylabel('Temp [deg C]')
ax.legend(labels=["Control TC1", "Control TC2"], loc="upper left")
# Define the date format
from matplotlib.dates import DateFormatter
date_form = DateFormatter("%d-%m-%Y %H:%M") ## Change this to what you want to show in X-axis DATE labels
ax.xaxis.set_major_formatter(date_form)
Output plot
Answered By - Redox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.