Reputation: 102
x = array([0], [1], [2], [3] ...[175])
y = array([333], [336], [327], ...[351])
Both have the shape (175,1)
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x, y, color='blue')
I get this result https://i.sstatic.net/pbQ9n.jpg
But I wanted separate labels on my x-axis ticks, taken from this array
year = array([1974], [1974], [1974], ....[1987])
which also has the shape (175,1) but a lot of repeating values
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(year, y, color='blue')
Gives https://i.sstatic.net/T8IPb.jpg
And
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x, y, color='blue')
ax.set_xticklabels(year)
Gives https://i.sstatic.net/nvrw8.jpg
I want the resultant plot as obtained in first figure but the labels on xticks as obtained in the second figure
Upvotes: 0
Views: 3760
Reputation: 102
Thanks to inputs from @ImportanceOfBeingErnest, @Jody Klymak, and @Jan Kuiken.
So, instead of setting the labels on x-axis ticks, it's better to set the desired ticks.
Since "year" is not compatible with "y" for the correct plot, I created another array that is obtained from "year" and is also compatible to plot with "y".
start = year.min().astype(float)
end = year.max().astype(float)
step = (year.max() - year.min())/len(year)
x = np.arange(start, end, step)
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x, y, color='blue')
ax.xaxis.set_ticks([1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987])
plt.grid(color='y', linestyle='-', linewidth=0.5)
Plot obtained - https://i.sstatic.net/CtlEh.jpg
Upvotes: 0
Reputation: 2010
If I combine the suggestions in the comments of @ImportanceOfBeingErnest and @Jody Klymak you could:
set_xticks
to specify what the tick labels you want to seefor instance:
# mimic your data a little bit
x = np.arange(0, 175)
y = 330.0 + 5.0 * np.sin(2 * np.pi * x / 13.0) + x / 10.0
# change the x values in something meaningful
x_in_years = 1974.5 + x / 13.0
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x_in_years, y, color='blue')
# select the ticks you want to display
ax.set_xticks([1975, 1980, 1985, 1990])
# or
# ax.set_xticks([1974, 1978, 1982, 1986])
Upvotes: 1