BayesianMonk
BayesianMonk

Reputation: 647

Use of set_xscale with exponential function

I am trying to use an exponential scale on the xaxis. I've had a look at this post:How can I exponentially scale the Y axis with matplotlib, but found no simple solution to do it.

I though that the matplotlib function set_xscale would be able to do the job very easily. However the following code produce a warning and the displayed result is far from expected:

import numpy as np
from matplotlib import pyplot as plt
from scipy import stats

def forward(x):
    return np.exp(x)

def reverse(x):
    return np.log(x)

# Define a Gaussian probability density function:
mu,std=6.6,0.75
rv = stats.norm(loc=mu,scale=std)

# x sample
x = np.linspace(mu - 3 * std, mu + 3 * std, 100)

# Display
fig, axes = plt.subplots(2, 1)
axes[0].plot(x, rv.pdf(x), color='r')
axes[0].set_title('linear scale')
axes[1].plot(x, rv.pdf(x), color='r')
axes[1].set_title('exponential scale')
axes[1].set_xscale('function', functions=(forward, reverse))

As a result, I get the following warning: RuntimeWarning: invalid value encountered in log, and the x axis on the figure is not good: enter image description here

I guess that this is because it tries to take the log of a negative or null value. However, there is no such value in the curve I plot.

I know that I could obtain a similar plot if I would display the corresponding lognormal distribution. However, the reason I need to do it as I described is that I plan to display more complicated probability density functions, with more complicated xscale functions.

Thanks for the help!

Upvotes: 0

Views: 1030

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339160

Autoscaling might be confused about the custom scale in use. Since set_scale("function", ...) is a pretty new API, probably not every detail fits perfectly yet.

So here one would need to set the limits manually, e.g. via

axes[1].set_xlim(x.min(), x.max())

enter image description here

Upvotes: 1

Related Questions