carsten carsten - 1 year ago 103
Python Question

plot log-scale and linear scale functions and histograms on same canvas

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

to have it plotted in log scale, wheras for the function, I can only have the logarithms of the values directly. How can I plot both on the same canvas?

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) ]

# this works nicely
xvals = np.arange(-4,4,0.1)
# but I would like to plot this on the same canvas:
# plt.plot(xvals,loggauss(xvals),"-r")

Any suggestions?

Answer Source

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()
ax2 = ax.twinx()
ax2.plot(xvals, loggauss(xvals), '-r')


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download