steve
steve

Reputation: 531

Manually change xticks in matplotlib

I am using the following code to make some plot of a variable having 4 values:

for station in stations:
    os.chdir(inbasedir)
    nc = Dataset(surf + station + "Fluxnet.nc", 'r+')
    soil_moist = nc.variables['SoilMoist'][:,0,0]
    plt.plot(soil_moist, c='black', linewidth=0.5, label="Soil Moisture - 4 layers")

Which gives me the following plot:

enter image description here

How could I modify the xticks as follow:

I tried this answer: Changing the "tick frequency" on x or y axis in matplotlib?

but it does not work and provides me the following error: TypeError: arange: scalar arguments expected instead of a tuple.

Upvotes: 0

Views: 4006

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

Make sure to plot the actual data

If 0 really denotes 1, you should plot 1 in the first place.

x = [1,2,3,4]
y = [.3,.3,.25,.29]

plt.plot(x,y)
plt.show()

enter image description here

Set the locations to integer numbers

from matplotlib.ticker import MultipleLocator

x = [1,2,3,4]
y = [.3,.3,.25,.29]

plt.plot(x,y)

plt.gca().xaxis.set_major_locator(MultipleLocator(1))
plt.show()

enter image description here

Upvotes: 2

SBylemans
SBylemans

Reputation: 1764

The xticks method of matplotlib.pyplot expects an array for the values to display as first argument and an array with labels for those elements in the first array. So add the following to your code:

plt.xticks(positions, labels)

Where positions is the array of the values you want to display, and labels the labels you want to give to those values.

Upvotes: 2

Related Questions