Search code examples
pythonmatplotlibline-plot

How to use axline with log scale axis?


I'm trying to plot a linear line through zero:

fig, ax = plt.subplots()

l2 = ax.axline(xy1=(0, 0), slope=0.3)

ax.set_xlim(0.1, 10)
ax.set_ylim(0.1, 10)

It works well:

example

However, if I change the scale to log, it would be empty:

fig, ax = plt.subplots()

l2 = ax.axline(xy1=(0, 0), slope=0.3)

ax.set_xlim(0.1, 10)
ax.set_ylim(0.1, 10)

ax.set_xscale('log')
ax.set_yscale('log')

example2


Solution

  • Unfortunately the order of operations has hidden the actual error message from appearing for you. If you were to modify your code to the following:

    fig, ax = plt.subplots()
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.axline(xy1=(0, 0), slope=0.3)
    

    You would have seen the following error

    TypeError: 'slope' cannot be used with non-linear scales
    

    However, you can still generate the line if you wish with something like the following:

    import matplotlib.pyplot as plt
    import numpy as np
    fig, ax = plt.subplots()
    ax.set_xscale('log')
    ax.set_yscale('log')
    
    x = np.linspace(0.1, 10, 1000)
    plt.plot(x, 0.3 * x)
    ax.set_xlim(0.1, 10)
    ax.set_ylim(0.1, 10)
    

    Which would give you the following figureenter image description here