10

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.

magu_
  • 4,766
  • 3
  • 45
  • 79
  • There's probably some way with [`ticker`](http://matplotlib.org/api/ticker_api.html) and `FormatStrFormatter` – tmdavison Jun 04 '15 at 16:23

1 Answers1

19

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

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Perfect, exactly what I was looking for. You didn't happen to know a way to format `1e+04` to `1e4`? – magu_ Jun 04 '15 at 16:45
  • Unfortunately, to control that [you would need to write a custom function](http://stackoverflow.com/q/9910972/190597). If you do want to go down this path, note that you could use a `ticker.FuncFormatter`. – unutbu Jun 04 '15 at 17:02
  • Well yeah, that's what I thought. But thanks anyway for your the help. – magu_ Jun 04 '15 at 17:46