0

I am attempting to make a log-lin plot where my y-axis has negative values. I also want to fit a best-fit line to it.

Here's the lin-lin plot:

enter image description here

Here's the plot with the (wrong) code:

plt.scatter(x, y, c='indianred', alpha=0.5)
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"-", color="grey", alpha=0.5)

plt.yscale('log')
plt.show()

enter image description here

Even tho the line for the plot is wrong, it plots the y-axis as I want it (I believe). However, if I comment plt.plot(x,p(x),"-", color="grey", alpha=0.5), I get the following plot instead:

enter image description here

This is essentially the same I get when writing the code the proper way:

plt.scatter(x, y, c='indianred', alpha=0.5)
p = np.polyfit(x, np.log(y), 1)
plt.semilogy(x, np.exp(p[0] * x + p[1]), 'g--')
plt.yscale('log')
plt.show()

but I obviously get the following error due to my negative y-values:

RuntimeWarning: invalid value encountered in log
  result = getattr(ufunc, method)(*inputs, **kwargs)

enter image description here

What alternative do I have so my y-values can be better seen? A best-fit line is not a must. I just want to better observe the relationship between these variables (which should be correlated theoretically).

Joehat
  • 979
  • 1
  • 9
  • 36
  • 1
    I’m a little confused why you want a log scale for data that crosses zero. OTOH if you insist on it, there is the “symlog” scale. – Jody Klymak Sep 09 '21 at 11:06
  • What would you do instead? I'd like to know what the best approach is. – Joehat Sep 09 '21 at 11:12
  • it really depends on the story you are trying to tell with the data. But usually data that crosses zero is not distributed in log space. – Jody Klymak Sep 09 '21 at 11:27

0 Answers0