Reputation: 255
I'm working with Python 3.6 and matplotlib to draw a plot of a list with 24 elements.
I'd like to have only 6 ticks on x-axis, one every 4 elements; also, I'd like that these 6 ticks would be equally spaced and in hour-format, like:
00:00, 01:00, 02:00, 03:00, 04:00, 05:00
Which is a good way to do this?
Upvotes: 0
Views: 341
Reputation: 11
For matplotlib there's always multiple ways to do the same thing. You can use the method plt.xticks(<ticks>,<labels>)
where <ticks>
is a list of integers of where you want the tick to appear and <labels>
is a list of labels. If you have multiple plots in one figure and want to set each axis independently you can use ax.set_xticks(<ticks>)
and ax.set_xticklabels(<labels>)
but it requires you to assign your axes object to some variable name, for example by using fig, ax = plt.subplots()
.
See below for example. If you are curious why the last index is 23 and not 24 I can explain further.
# === Method using plt.plot() directly ====
# --- generate data -----
data=[]
for i in list(range(24)):
data += [random()]
# --- plot data ----
plt.xticks([0,4,8,12,16,20,23], ["00:00", "01:00", "02:00", "03:00", "04:00","05:00","6:00"]) # note that the final index is 23 not 24
plt.plot(data) # plt.plot() can be called either before or after plt.xticks() in this case
plt.show()
# === Method using plt.subplots() ====
# --- generate random data again to show its not the same plot -----
data=[]
for i in list(range(24)):
data += [random()]
# --- plot data ----
fig,ax= plt.subplots(nrows=1, ncols=1)
plt.xticks([0,4,8,12,16,20,23], ["00:00", "01:00", "02:00", "03:00", "04:00","05:00","6:00"]) #in this case .xticks cannot be called before .subplots()
#use the below two lines and remove the line above if you have multiple subplots and want to set each subplot to have a different x-axis
#ax.set_xticks([0,4,8,12,16,20,23])
#ax.set_xticklabels(["00:00", "01:00", "02:00", "03:00", "04:00","05:00","6:00"])
ax.plot(data)
plt.show()
Upvotes: 1