Reputation: 41
I am using a numpy array with datetime values for my x-axis. Although the xData has gaps, matplot finds a way to fill them in the plot. I do not want that behavior. I want the x axis to plot the exact entries in the array "dates". Any suggestions?
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dates = np.array([datetime.datetime(2017, 3, 24, 14, 52),datetime.datetime(2017, 3, 24, 14, 56),datetime.datetime(2017, 3, 26, 16, 0),datetime.datetime(2017, 3, 26, 16, 4)])
yData = np.ones(len(dates))
fig = plt.figure(figsize=(6,6))
ax = plt.subplot(111)
li, = ax.plot(dates,yData)
plt.gcf().subplots_adjust(bottom=0.3)
ax.get_xaxis().tick_bottom()
xfmt = mdates.DateFormatter('%Y-%m-%d-%H:%M')
ax.xaxis.set_major_formatter(xfmt)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
fig.canvas.draw()
plt.show()
Upvotes: 0
Views: 1697
Reputation: 41
In the end I was able to remove the gap using the post provided by @ImportanceOfBeingErnest and the hacks in those threads. I had to treat dates as indexes and only preserve them for labeling and ease of numpy manipulation. Here is the final code:
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dates = np.array([datetime.datetime(2017, 3, 24, 14, 52),
datetime.datetime(2017, 3, 24, 23, 56),
datetime.datetime(2017, 3, 26, 8, 0),
datetime.datetime(2017, 3, 26, 19, 4)])
dates_indx = range(len(dates))
dates_strings = [dt.strftime('%Y-%m-%d-%H:%M') for dt in dates]
yData = np.ones(len(dates))
fig = plt.figure(figsize=(6,6))
ax = plt.subplot(111)
li, = ax.plot(dates_indx,yData, marker = 'o', linestyle="-")
plt.gcf().subplots_adjust(bottom=0.3)
ax.get_xaxis().tick_bottom()
plt.xticks(dates_indx,dates_strings)
plt.xticks(dates_indx, rotation=90)
fig.canvas.draw()
plt.show(block=False)
Upvotes: 2
Reputation: 339570
The xticks can be set via plt.xticks
. So
plt.xticks(dates, rotation=90)
would set the xticks to those values from the dates
array.
Complete code where I changed the dates a bit, such that they don't overlap
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dates = np.array([datetime.datetime(2017, 3, 24, 14, 52),
datetime.datetime(2017, 3, 24, 23, 56),
datetime.datetime(2017, 3, 26, 8, 0),
datetime.datetime(2017, 3, 26, 19, 4)])
yData = np.ones(len(dates))
fig = plt.figure(figsize=(6,6))
ax = plt.subplot(111)
li, = ax.plot(dates,yData, marker="o", linestyle="-")
plt.gcf().subplots_adjust(bottom=0.3)
ax.get_xaxis().tick_bottom()
xfmt = mdates.DateFormatter('%Y-%m-%d-%H:%M')
ax.xaxis.set_major_formatter(xfmt)
plt.xticks(dates, rotation=90)
fig.canvas.draw()
plt.show()
produces
Upvotes: 1