carsten - 3 months ago 21

Python Question

I have a probability density function of that I can only evaluate the logarithm without running into numeric issues. I have a histogram that I would like to plot on the same canvas. However, for the histogram, I need the option

`log=True`

Please look at this MWE for illustration of the problem:

`import matplotlib.pyplot as plt`

import random

import math

import numpy as np

sqrt2pi = math.sqrt(2*math.pi)

def gauss(l):

return [ 1/sqrt2pi * math.exp(-x*x) for x in l]

def loggauss(l):

return [ -math.log(sqrt2pi) -x*x for x in l ]

# just fill a histogram

h = [ random.gauss(0,1) for x in range(0,1000) ]

plt.hist(h,bins=21,normed=True,log=True)

# this works nicely

xvals = np.arange(-4,4,0.1)

plt.plot(xvals,gauss(xvals),"-k")

# but I would like to plot this on the same canvas:

# plt.plot(xvals,loggauss(xvals),"-r")

plt.show()

Any suggestions?

Answer

If I understand correctly, you want to plot two data sets in the same figure, on the same x-axis, but one on a log y-scale and one on a linear y-scale. You can do this using twinx:

```
fig, ax = plt.subplots()
ax.hist(h,bins=21,normed=True,log=True)
ax2 = ax.twinx()
ax2.plot(xvals, loggauss(xvals), '-r')
```