Reputation: 25
So I am trying to display some analytics in my python web-app. I want to display the date-time for the first and last entries on the x axis.
I have attempted to set the ticks as a two entry list but it gave a bad result.
plt.scatter(x_data, y_data)
plt.grid(True)
plt.xticks(x_data, [x_data[0], x_data[-1]])
fig = plt.gcf()
Where the x_data is:
['10:59:44 27-03-2019', '11:00:07 27-03-2019', '11:00:09 27-03-2019', '11:00:12 27-03-2019', '11:30:23 27-03-2019', '11:30:29 27-03-2019', '11:30:30 27-03-2019', '11:30:31 27-03-2019', '11:30:32 27-03-2019', '11:32:44 27-03-2019', '11:33:21 27-03-2019', '11:35:50 27-03-2019', '12:16:12 27-03-2019', '12:16:39 27-03-2019', '12:17:36 27-03-2019', '12:19:40 27-03-2019', '12:23:50 27-03-2019']
I expected the output to place one on the far left and the other on the far right. Instead the first two ticks simply showed the times overlapping.
I am unsure what the proper way of doing it is.
Upvotes: 2
Views: 535
Reputation: 6483
I suspect your problem is that you are defining a vector of ticks and then assigning two labels (in position 0 and 1).
import numpy as np
import matplotlib.pyplot as plt
x_data=np.array([1,2,3,4,5,6,7,8])
y_data=np.random.normal(0, 1, (8, 1))
# create an array for your labels
new_labels=[''] * (len(x_data)-2)
new_labels.insert(0,x_data[0])
new_labels.append(x_data[-1])
plt.scatter(x_data, y_data)
plt.grid(True)
plt.xticks(x_data, new_labels) #use the new tick labels
fig = plt.gcf()
Upvotes: 1
Reputation: 39042
Here is a workaround solution using some random data because you did not specify what the y_data
is. The idea is to loop through the existing default tick labels and then replace all the tick labels by empty strings except the first and the last one.
fig, ax = plt.subplots()
plt.scatter(x_data, range(len(x_data)))
plt.grid(True)
fig.canvas.draw()
xticks = ax.get_xticklabels()
labels_new = [lab.get_text() if i in [0, len(xticks)-1] else ""
for i, lab in enumerate(xticks) ]
ax.set_xticklabels(labels_new)
plt.show()
Upvotes: 2