So I have 2 lists of values: one with temperature values (templist) and one with time values (timelist).
I use this code to plot the values:
n = 0
bettertime = []
sizeoflist = len(timelist)
while n < sizeoflist:
newtime = datetime.strptime(timelist[n], "%H:%M:%S")
bettertime.append(newtime.strftime("%H:%M"))
n = n + 1
fig, ax = plt.subplots()
ax.plot(bettertime, templist)
plt.show()
And when I run it, I got this results:
The values on the time ax are not displayed correctly. I also tried with, but I just got the values cut (just plotting the first 10 values):
ax.set(xlim=(0, 10))
So after some research I found that my list of time (timelist) is a list of strings, not datetime formatted so matplotlib doesn't know how to shrink it down.
How can I fit the values in the graph? (For the example, templist got automatic fitted on the Y ax) (I want to get like 10 values of time in the graph, but from maxim to minim, not just first 10 values of the list)
And as a side note, the lists (timelist and templist) are lists of random length (equal length, len(timelist) is equal with len(timelist) if this is important at all)
EDIT:
The solution:
fmt = mdates.DateFormatter('%H:%M')
bettertimelist = [datetime.strptime(i, '%H:%M:%S') for i in timelist]
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(fmt)
You can specify that the xtick label be rotated, like this:
times = np.arange(10, 27, 1)
templist = np.sin(times)
bettertime = ["10:"+repr(time) for time in times] # make string for the xlabel, since that's what the question states
fig, ax = plt.subplots()
ax.plot(bettertime, templist)
plt.xticks(rotation=45) # here's the line that does the rotation
You can try rotating your xticks value. plt.xticks(rotation=45) # 90 ---> vertical xticks
n = 0
bettertime = []
sizeoflist = len(timelist)
while n < sizeoflist:
newtime = datetime.strptime(timelist[n], "%H:%M:%S")
bettertime.append(newtime.strftime("%H:%M"))
n = n + 1
fig, ax = plt.subplots()
ax.plot(bettertime, templist)
plt.xticks(rotation=45) # Add this line for xticks to be rotated
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.