Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the format of the axis label in matplotlib

If I plot a log scale graph, matplotlib gives me the nice looking entries 105, 106, ...

For readability I would however prefer the form 1e5, 1e6, ...

Can I directly set the axis properties to behave that way?

I rather ugly hack would be:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 40, 100);
y = np.linspace(1, 5, 100);

# Actually plot the exponential values
plt.plot(x, 10**y)
ax = plt.gca()
ax.set_yscale('log')

# Rewrite the y labels
y_labels = ax.get_yticks()
ax.set_yticklabels(['1e%i' % np.round(np.log(y)/np.log(10)) for y in y_labels])

plt.show()

enter image description here

But surely there must be a better way.

like image 911
magu_ Avatar asked Jun 04 '15 16:06

magu_


People also ask

How do I change the axis format in MatPlotLib?

MatPlotLib with Python Create a figure and a set of subplots using subplots() method. Plot the dataframe using plot method, with df's (Step 1) time and speed. To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.

How do you change the axis labels in MatPlotLib?

Axis Titles You can customize the title of your matplotlib chart with the xlabel() and ylabel() functions. You need to pass a string for the label text to the function.


1 Answers

You use ticker.FormatStrFormatter('%0.0e'). This formats each number with the string format %0.0e which represents floats using exponential notation:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = np.linspace(1, 40, 100)
y = np.linspace(1, 5, 100)

# Actually plot the exponential values
fig, ax = plt.subplots()
ax.plot(x, 10**y)
ax.set_yscale('log')

# Rewrite the y labels
y_labels = ax.get_yticks()
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0e'))

plt.show()

yields

enter image description here

like image 179
unutbu Avatar answered Oct 09 '22 17:10

unutbu