how to plot line of best fit using loglog in python matplotlib

Viewed 76

Using this code:

x = np.array([1, 2, 7, 5, 8])
y = np.array([ 5, 4, 6, 7, 10 ])
x = np.log(x)
y = np.log(y)
m, b = np.polyfit(x, y, 1)
plt.plot(x, y, 'o')
plt.plot(x, m*x + b)

I can make a plot of log value as follow: enter image description here

But I want to have the axis ticks in non log-value, so I thought this would work:

x = np.array([1, 2, 7, 5, 8])
y = np.array([ 5, 4, 6, 7, 10 ])
m, b = np.polyfit(x, y, 1)
plt.loglog()
plt.plot(x, y, 'o')
plt.plot(x, m*x + b)

But I got this instead:

enter image description here

How do I make a best fit line in log scale but with non log axis ticks?

1 Answers

If I understand correctly, you can set the xticklabels / yticklabels to the exponential of the xticks / yticks:

x = np.log(x)
y = np.log(y)
m, b = np.polyfit(x, y, 1)

fig, ax = plt.subplots()
ax.plot(x, y, 'o')
ax.plot(x, m*x + b)

ax.set_xticklabels([f'{tick:.1f}' for tick in np.exp(ax.get_xticks())])
ax.set_yticklabels([f'{tick:.1f}' for tick in np.exp(ax.get_yticks())])

plot output with np.exp(ticks)

Related