I am trying to mark data points in the line plot using markevery
option in matplotlib. I am plotting data with index in datetime format. When I create a list for the markevery I get this error
markevery=['13:15:00', '13:30:00', '13:45:00', '14:00:00', '14:15:00', '14:30:00'] is iterable but not a valid numpy fancy index
My code
markers_on= ['13:15:00','13:30:00','13:45:00','14:00:00','14:15:00','14:30:00']
ax1 = plt.subplot()
ax1.plot(data,'-gD', markevery=markers_on)
ax1.set_xlabel("Time (HH:MM:SS)",fontsize=15)
ax1.set_ylabel("Temp",fontsize=15)
My data looks like this:
time | temp |
---|---|
09:59:45 | 0.011154 |
10:00:00 | 0.028380 |
10:00:15 | 0.072002 |
10:00:30 | 0.151146 |
10:00:45 | 0.200887 |
How can I use list of datetime index to mark on the plot?
I have tried to convert the values in the list to datetime objects, but did not work.
You could try to use pandas.Index.get_indexer to convert your list of strings markers_on
to a list of positions where the index matches the target values:
import matplotlib.pyplot as plt
import pandas as pd
# make data
d = {'time': ['09:59:45','10:00:00','10:00:15','10:00:30','10:00:45'],
'temp': [0.011154, 0.028380, 0.072002, 0.151146, 0.200887]}
# make a data frame
data = pd.DataFrame(d, index=d['time'])
# a couple of timestamp strings to set markers at
markers_on = ['10:00:15', '10:00:45']
# plot data, showing markers only for the specified timestamp strings
ax = plt.subplot()
ax.plot(data['time'], data['temp'], '-gD', markevery=data.index.get_indexer(markers_on))
ax.set_xlabel('Time (HH:MM:SS)', fontsize=15)
ax.set_ylabel('Temp', fontsize=15)
plt.show()
The result: