0

I'm plotting points on a log-log scatterplot with matplotlib. The x coordinate of these points rises twice as fast (exponentially speaking) than the y coordinate, which means that the x axis is twice as densely packed when plotted on a square plot.

Here's the code and the graph it produces:

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr

fig, ax = plt.subplots(figsize=(10,8))
ax: plt.Axes

# Log scale
ax.set_xscale("log")  # Needed for a log scatterplot. https://stackoverflow.com/a/52573929/9352077
ax.set_yscale("log")
# ax.xaxis.set_major_locator(tkr.LogLocator(base=10))
# ax.xaxis.set_major_formatter(tkr.LogFormatterSciNotation())
# ax.yaxis.set_major_locator(tkr.LogLocator(base=10))
# ax.yaxis.set_major_formatter(tkr.LogFormatterSciNotation())

# Plot points
t = range(1, 10_000_000, 1000)
x = [e**2 for e in t]
y = t
ax.scatter(x, y, marker=".", linewidths=0.05)

# Grid
ax.set_axisbelow(True)
ax.grid(True)

fig.savefig("./test.pdf", bbox_inches='tight')

missing major ticks

By default, matplotlib seems to want a square grid, and hence skips every other power of 10 on the x axis. Supposedly, the 4 lines I have commented out -- a combination of a locator and a formatter -- are the way to customise the spacing of the major ticks. See e.g. this post. Yet, uncommenting them produces the same exact figure, with missing major ticks.

How else, if not with LogLocator(base=10), can I change the spacing between the ticks on the log scale? Here's roughly what it should look like (I've highlighted the changes in red, but they should of course be gray):

no more missing major ticks on log scale

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Mew
  • 368
  • 1
  • 11
  • `ax.xaxis.set_major_locator(tkr.LogLocator(numticks=999))` and `ax.set_aspect('equal')` see [code and plot](https://i.stack.imgur.com/KmvEf.png) – Trenton McKinney May 19 '23 at 01:12
  • 1
    @TrentonMcKinney The aspect ratio suggestion is actually quite nice, I hadn't thought of that. Not sure why you didn't leave your comment as an answer. – Mew May 19 '23 at 01:36
  • If it's covered in the duplicate(s), I usually just leave a comment. – Trenton McKinney May 19 '23 at 01:38

1 Answers1

0

Is this what you want the output to look like? You will probably want a more robust solution for the x_ticks. I removed that t value you had because you didn't need it

enter image description here

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 8))
ax: plt.Axes

# Log scale
ax.set_xscale("log")  
ax.set_yscale("log")

# Plot points
y = range(1, 10_000_000, 1000)
x = [e**2 for e in y]

ax.scatter(x, y, marker=".")

# Grid
ax.set_axisbelow(True)
ax.grid(True)
ax.set_xscale("log")
ax.set_xticks([10**x for x in range(0, 14)])



fig.savefig("./test.pdf", bbox_inches='tight')
MDavidson
  • 67
  • 2
  • Your comment is correct that this is not general enough, since the `0` and `14` are both magic numbers. – Mew May 19 '23 at 01:33