简体   繁体   中英

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

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: 在此处输入图像描述

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:

在此处输入图像描述

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

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

用 np.exp(ticks) 绘制输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM