Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
user1410395 Avatar asked May 22 '12 14:05

user1410395


People also ask

How do you change the units of the Axis in Python?

The Axis. set_units() function in axis module of matplotlib library is used to set the units for axis.

How do I change the y axis values in Matplotlib?

To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0.


2 Answers

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

like image 52
Hooked Avatar answered Nov 03 '22 08:11

Hooked


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

like image 36
FakeDIY Avatar answered Nov 03 '22 09:11

FakeDIY