Option 1: x axis datetime
type
Answer
I suppose your data are in a file named data.csv
. If you load it with pd.read_csv
, you need to pay attention to the format of the 'Time'
column. Look at the output of:
print(graphdf.info())
If the DType
of the column 'Time'
is object
, pandas
identifies the values of this column as str
. In this case, you need to convert them to datetime
with:
graphdf['Time'] = pd.to_datetime(graphdf['Time'], format = '%H:%M')
Finally you can set the format of the labels you see on the x axis with:
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M'))
Check this answer for reference.
Whole code
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md
graphdf = pd.read_csv('data.csv')
graphdf['Time'] = pd.to_datetime(graphdf['Time'], format = '%H:%M')
fig, ax = plt.subplots()
ax.plot(graphdf['Time'],graphdf['Price'],color='red')
plt.xticks(rotation=90)
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M'))
plt.show()
Plot

Option 2: x axis str
type
Answer
In the case you do not want x axis as a general time %H:%M
axis, but you want to keep your original ticks, you have to mantain the x axis as a str
type and simply sample original ticks, then apply them to the axis:
xticks = graphdf['Time'][::2]
ax.set_xticks(xticks)
You can slice original ticks with [::n]
, where n
is the step. If n = 2
you pick alternative ticks; if n = 3
you pick a tick every 3 and so on.
Whole code
import pandas as pd
import matplotlib.pyplot as plt
graphdf = pd.read_csv('data.csv')
fig, ax = plt.subplots()
ax.plot(graphdf['Time'],graphdf['Price'],color='red')
plt.xticks(rotation=90)
xticks = graphdf['Time'][::2]
ax.set_xticks(xticks)
plt.show()
Plot
