I have an issue with matplotlib chart, I've been trying multiple ways, but can't seem to make it work, I want a chart that goes from left to right, I have data that looks like this: prices = [0.03, 0.025, 0.01, 0.01, 0.05, 0.02] time = ['00:00', '00:05', '00:10', '00:15', '00:20', '00:00'] I want the chart to go from left to right, but when it goes to the last position '00:00' it goes back to the left side. Is there a chance to make it create new tick '00:00' after '00:20'? Below is the code.
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
stored_prices = [0.03, 0.025, 0.01, 0.01, 0.05, 0.02]
prices_time = ['00:00', '00:05', '00:10', '00:15', '00:20', '00:00']
fig, ax = plt.subplots()
plt.title("X")
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)
plt.plot(prices_time, stored_prices)
plt.grid()
plt.subplots_adjust(left=0.03, right=0.86)
fig.autofmt_xdate()
loc = plticker.MultipleLocator(base=2) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
print(stored_prices, prices_time)
plt.show() #Preview of chart
Here is image to explain what I mean, after '00:20' it isn't creating '00:00' to the right of '00:20' but goes back to '00:00' that is already created on the left of the graph :
CodePudding user response:
Since your x-values are equidistant (except for the last one), you can just use any sequence of equidistant numbers to plot them. It may be an arbitrary decision whether to show the last point at the same distance.
Then you just have to manually set the x-ticks and label them with the real values:
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
stored_prices = [0.03, 0.025, 0.01, 0.01, 0.05, 0.02]
prices_time = ['00:00', '00:05', '00:10', '00:15', '00:20', '00:00']
x = range(len(prices_time))
fig, ax = plt.subplots()
plt.title("X")
plt.tick_params(axis='y', which='both', labelleft=False, labelright=True)
plt.plot(x, stored_prices)
plt.grid()
plt.subplots_adjust(left=0.03, right=0.86)
fig.autofmt_xdate()
# loc = plticker.MultipleLocator(base=2)
# this locator puts ticks at regular intervals
# ax.xaxis.set_major_locator(loc)
ax.set_xticks(x)
ax.set_xticklabels(prices_time)
print(stored_prices, prices_time)
plt.show() #Preview of chart