How do I make this LogLog plot?

3.7k Views Asked by At

I am new to python and I am trying to create a LogLogPlot, similar to the one in the image below:

enter image description here

This plot, as can be seen on the top, is based on the equation y=x^2/(e^x +1).

I have found https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.loglog.html , but it doesn't;t make much sense to me.

I have also attempted the code shown in the link: pyplot: loglog() with base e and changing my expression for "y", but the axis are written in exponential form, and I was aiming to have the axis written in terms of real numbers, as shown in the image. The code looks like:

# Generate some data.
x = np.linspace(0, 10, 10)
y = x**2/(np.exp(x)+1)

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

But this is not giving me the same plot as the one above.

1

There are 1 best solutions below

0
On BEST ANSWER

Your current x-axis has only 10 values, equally spaced in linear space between 0 and 10. You need more values, and equally spaced in logspace. For example, np.logspace(-3, 1, 100) creates 100 x-values between 10-3 and 101.

If you change the base in plt.loglog(x, y, basex=np.e, basey=np.e), the axis will be shown with ticks at powers of e. If you don't change the base, the default uses the familiar powers of 10. Note that changing the base doesn't change the transformation, it only changes the position of the ticks.

import numpy as np
import matplotlib.pyplot as plt

x = np.logspace(-3, 1, 100)
y = x ** 2 / (np.exp(x) + 1)

plt.loglog(x, y)
plt.autoscale(enable=True, axis='x', tight=True) # optionally set a tight x-axis
plt.show()

example plot

PS: To avoid the scientific notation, this post suggests:

import matplotlib.ticker as ticker
plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: f'{y:g}'))
plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda y, _: f'{y:g}'))

or, to force decimal notation also for more decimals:

plt.gca().yaxis.set_major_formatter(
    ticker.FuncFormatter(lambda y, _: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(y),0)))).format(y)))