0

I have a scatterplot where both axes are in logarithmic scale. For instance, a plot generated with the following code:

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.RandomState(42)

x = np.logspace(0, 3, 100)
y = np.logspace(0, 3, 100) + rng.randn(100) * 2

ax = plt.gca()
ax.scatter(x, y, marker="x", color="orange")

ax.axline((0, 0), (1, 1), color="black", linestyle=":")

ax.set_xscale("log")
ax.set_yscale("log")

ax.set_aspect("equal")
plt.show()

that produces the following plot Scatter plot with bisector

I would like to draw diagonal lines in correspondence of each power of 10, for instance as in the following plot Scatter plot with bisector and two diagonal lines

I tried to add

ax.axline((1, 0), (10, 1), color="black", linestyle=":")
ax.axline((0, 1), (1, 10), color="black", linestyle=":")

but I get Scatter plot with bisector and two lines which is not what I expected.

1 Answers1

2

Multiply the Y coordinate values by a constant

I am not sure your original idea of (0,0) and (1,1) is ideal. It would be better to avoid 0's in a log-log plot. I have changed it to (1,1) and (10,10), which is the same line.

Then you want your next line to be passing through the same X co-ordinates, but at Y coordinates that are, say, 10 times higher. So multiply both Y coordinates by 10.

Likewise for the line on the other side, divide by 10.

In this code I have made the factor k.


import matplotlib.pyplot as plt
import numpy as np

rng = np.random.RandomState(42)

x = np.logspace(0, 3, 100)
y = np.logspace(0, 3, 100) + rng.randn(100) * 2

ax = plt.gca()
ax.scatter(x, y, marker="x", color="orange")

k = 10
ax.axline((1, 1),  (10, 10  ), color="black", linestyle=":")
ax.axline((1,1*k), (10, 10*k), color="black", linestyle=":")
ax.axline((1,1/k), (10, 10/k), color="black", linestyle=":")

ax.set_xscale("log")
ax.set_yscale("log")

ax.set_aspect("equal")
plt.show()

The result is:

enter image description here

Why do the dotted lines intersect the axis a bit low?

They are actually intersecting in the correct place. They should not intersect the Y axis at 1, 10, 100 etc. The Y axis is not at x=1. It is at some number slightly to the left of 1.

If you trace up a line at x=1, and across from x=1, you will see that the dotted line passes through their crossing point.

enter image description here

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • 1
    Thank you! I think my mistake was that I thought the axes started from 0, but they actually start from 1, and it makes sense since they are in log scale. Nevertheless, these lines do not really intersect the axes at the powers of 10, but they intersect a bit below the "big ticks" (also in your picture). Any idea on why this happens? – Scacco Matto Mar 20 '23 at 07:03
  • 1
    I got it, it is because both axes must start at 1. This can be done by adding ```ax.set_xlim(1, 1000)``` and ```ax.set_ylim(1, 1000)``` – Scacco Matto Mar 20 '23 at 09:48