Joanne
Joanne

Reputation: 503

Integer values for plt.xticks in Python

I want to plot a figure, and I set the plt.xticks as np.linspace(1, 3, 10).

I thought the values on the x-axis would be 1, 1.2, 1.4, 1.6, ..., 3.

But it turned out: 1.000, 1.222, 1.444, 1.667, ..., 3.000.

How can I fix this?

import numpy as np
import matplotlib.pyplot as plt

n_c = 1
n_s = np.linspace(1, 3, 100)

iso_trapping_efficiency = (np.sqrt(1 - (n_c ** 2 / n_s ** 2))) *100

plt.figure()
plt.plot(n_s, iso_trapping_efficiency, 'r', label='Isotropic Dipole')

plt.xlabel('Refractive Index, n_s', fontsize=15)
plt.ylabel('Trapping Efficiency [%]', fontsize=15)

# change the xticks
plt.xticks(np.linspace(1, 3, 10))

plt.legend(loc='lower right')

plt.show()

enter image description here

Upvotes: 1

Views: 766

Answers (4)

Ehsan
Ehsan

Reputation: 12397

np.linspace(1, 3, 10) creates 10 samples (interval boundaries) in the interval (1,3). Note that it includes beginning and end of the interval in the samples. Therefore, 10 samples of interval boundaries will create 10-1=9 intervals (think of it as a single interval has two boundaries). If you need to split it into 10 intervals, call np.linspace for 10+1 samples:

 np.linspace(1, 3, 11)

Upvotes: 1

olenscki
olenscki

Reputation: 507

I think that matplotlib has some useful methods to do this. You could give a try to this one:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker # new line

n_c = 1
n_s = np.linspace(1, 3, 100)

iso_trapping_efficiency = (np.sqrt(1 - (n_c ** 2 / n_s ** 2))) *100

plt.figure()
plt.plot(n_s, iso_trapping_efficiency, 'r', label='Isotropic Dipole')

plt.xlabel('Refractive Index, n_s', fontsize=15)
plt.ylabel('Trapping Efficiency [%]', fontsize=15)

# change the xticks
plt.xticks(np.linspace(1, 3, 10))

ax = plt.gca() # get current axis
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00)) # define a major locator to the ticker
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25)) # set minor locators, w/o labels

plt.legend(loc='lower right')

plt.show()

The documentation of mpl is very good, it's filled with examples, you can check it out here: https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html

Here's the result of the code:

enter image description here

Upvotes: 1

Greesham anand
Greesham anand

Reputation: 1

Python has default precision set for float variables. What you're looking for is rounding up just one variable.

plt.xticks(np.linspace(1, 3, 10).round(2))

Just adding round 2 solves the issue

Upvotes: 0

Jack Cummins
Jack Cummins

Reputation: 41

The third parameter of np.linspace() does not include the value. Try plt.xticks(np.linspace(1, 3, 11))

Upvotes: 1

Related Questions