How to add diagonal line to log-log plot

Hello,

I would like to plot a diagonal line on a log-log plot. How can I do that?

using Plots
x = 1:4
y = [44,29,6,1]
scatter(x, y, xaxis=:log10, yaxis=:log10)
Plots.abline!(-1, 44)

Will this work?

plot!(x -> x, 1, 50)

Thanks for your reply. The identity line is not what I am looking for. I am trying to do two things. One is to plot a diagonal line (i.e., with a slope of -1 and intercept at the max of y). The other thing, which has been more difficult, is plotting the best fit linear equation. Basically, I am trying to analyze whether a network is scale free. Here is something similar to my goal:

Among the things I tried, was LogFit in Curve Fit, but that did not work I tried LinearFit, but it was not linear in log space even with xaxis = :log10, yaxis = :log10.

Your example graph is plotted in log space. Why can’t you transform your data into log space and do a simple least squares fit to the transformed data? You can then either plot the results in log space (like your example), or transform the fit data back into lin space and plot on a log/log scale like in your original code snippet.

In other words, you need to be clear whether your lin to log transformation is done in the data themselves or if is merely done in the representation of the data on the chart. You can’t mix.

A simple way to add a regression line is:

scatter(log10.(x), log10.(y), smooth=true)

I did try something to that effect, but it didn’t work. Here is the code:

using Plots
using CurveFit
x = 1:4
y = [44,29,6,1]
log_x = log10.(x)
log_y = log10.(y)
scatter(x, y, xaxis = :log10, yaxis = :log10)
fit = curve_fit(LinearFit, log_x, log_y)
plot!(log_x, fit.(log_x))

example

I think the problem is that plot! performs another log10 transform. If I fit in real space, some of the predicted values are negative, which leads to an error.

plot! performs another log10 transform

Yes, because you are trying to plot on log-log axes.

Try plot! with x rather than log_x and transform the fit data to lin using 10^(fit_x). With both in linear space you can then plot them onto your original log/log axes.

1 Like

I tried with xaxis = :exp10 but that did not work. Maybe it is not an option for xaxis. What you proposed did work. Thank you for your help.

Here is the solution for future reference:

using Plots
using CurveFit
x = 1:4
y = [44,29,6,1]
log_x = log10.(x)
log_y = log10.(y)
scatter(x, y, xaxis = :log10, yaxis = :log10)
fit = curve_fit(LinearFit, log_x, log_y)
plot!(x, 10 .^(fit.(log_x)))

Thank you both for your help. I’ll mark this as the solution, but attribute it to TimG.