10

Python (and matplotlib) newbie here coming over from R, so I hope this question is not too idiotic. I'm trying to make a loglog plot on a natural log scale. But after some googling I cannot somehow figure out how to force pyplot to use a base e scale on the axes. The code I have currently:

import matplotlib.pyplot as pyplot 
import math

e = math.exp(1)
pyplot.loglog(range(1,len(degrees)+1),degrees,'o',basex=e,basey=e)

Where degrees is a vector of counts at each value of range(1,len(degrees)+1). For some reason when I run this code, pyplot keeps giving me a plot with powers of 2 on the axes. I feel like this ought to be easy, but I'm stumped...

Any advice is greatly appreciated!

gogurt
  • 811
  • 1
  • 8
  • 24

2 Answers2

16

When plotting using plt.loglog you can pass the keyword arguments basex and basey as shown below.

From numpy you can get the e constant with numpy.e (or np.e if you import numpy as np)

import numpy as np
import matplotlib.pyplot as plt

# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e

plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()

Edit

Additionally if you want pretty looking ticks you can use matplotlib.ticker to choose the format of your ticks, an example of which is given below.

import numpy as np

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

x = np.linspace(1, 4, 1000)

y = x**3

fig, ax = plt.subplots()

ax.loglog(x,y, basex=np.e, basey=np.e)

def ticks(y, pos):
    return r'$e^{:.0f}$'.format(np.log(y))

ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))

plt.show()

Plot

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
  • I see. So plt.loglog() is actually plotting on a scale of base e. Is there any way to get the axes to be labelled correctly though? When I run this code I still get powers of 2 on the axes. Just a detail, but an annoying one... – gogurt Apr 26 '14 at 15:28
  • Really? When I run the code I get the axes labelled in exponential base. What version of Python/matplotlib windows/mac are you using? Are you using the most up to date version of matplotlib is probably the most important question. – Ffisegydd Apr 26 '14 at 15:30
  • Bingo. I was using an old version of matplotlib. After updating, it looks much better. Thanks! – gogurt Apr 26 '14 at 16:01
3

It can also works for semilogx and semilogy to show them in e and also change their name.

import matplotlib.ticker as mtick
fig, ax = plt.subplots()
def ticks(y, pos):
    return r'$e^{:.0f}$'.format(np.log(y))

plt.semilogy(Time_Series, California_Pervalence ,'gray', basey=np.e  )
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))

plt.show()

Take a look at the image.

enter image description here

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264