user1410395
user1410395

Reputation: 101

How to set the unit length of axis in matplotlib?

For example x = [1~180,000] When I plot it, in x axis, it shows: 1, 20,000, 40,000, ... 180,000 these 0s are really annoying

How can I change the unit length of x axis to 1000, so that it show:1, 20, 40, ... 180 and also show that somewhere its unit is in 1000.

I know I can do a linear transformation myself. But isn't there a function doing that in matplotlib?

Upvotes: 10

Views: 6886

Answers (2)

FakeDIY
FakeDIY

Reputation: 1445

You can use pyplot.ticklabel_format to set the label style to scientific notation.

import pylab as plt
import numpy as np

# Create some random data over a large interval
N = 200
X = np.random.random(N) * 10 ** 6
Y = np.sqrt(X)

# Draw the figure to get the current axes text
fig, ax = plt.subplots()
plt.scatter(X,Y)
ax.axis('tight')
plt.draw()

plt.ticklabel_format(style='sci',axis='x',scilimits=(0,0))

# Edit the text to your liking
#label_text   = [r"$%i \cdot 10^4$" % int(loc/10**4) for loc in plt.xticks()[0]]
#ax.set_xticklabels(label_text)

# Show the figure
plt.show()

Output

Upvotes: 3

Hooked
Hooked

Reputation: 88118

If you are aiming on making publication quality figures, you'll want to a fine control over the axes labels. One way to do this is to extract the label text and apply your own custom formatting:

import pylab as plt
import numpy as np

# Create some random data over a large interval
N = 200
X = np.random.random(N) * 10 ** 6
Y = np.sqrt(X)

# Draw the figure to get the current axes text
fig, ax = plt.subplots()
plt.scatter(X,Y)
ax.axis('tight')
plt.draw()

# Edit the text to your liking
label_text   = [r"$%i \cdot 10^4$" % int(loc/10**4) for loc in plt.xticks()[0]]
ax.set_xticklabels(label_text)

# Show the figure
plt.show()

enter image description here

Upvotes: 8

Related Questions