Search code examples
pythonmatplotlibplotaxissubplot

How to limit the range of only one axis out of several


Here's the code:

fig, ax1 = plt.subplots(figsize=(20, 10))

pds, ns, ss, avgs = polar
ax1.plot(pds, avgs, color="purple", linestyle="-")
ax1.tick_params(axis='y', labelcolor="k")
ax1.set_ylabel("polar field strength")

ax2 = ax1.twinx()

for i, (cmd, ffmd, md, c) in enumerate(zip(cmds, ffmds, mds, cycles)):
    p = ax2.plot(c[0], c[1], label="SC" + str(25 - len(cycles) + i + 1))
    color = p[-1].get_color()
    ax2.axvline(x=cmd, color=color, linestyle=":")
    ax2.axvline(x=md, color=color, linestyle = '--')
    ax2.axvline(x=ffmd, color=color, linestyle = '-')

sc25 = cycles[-1]
p = ax2.plot(sc25[0][:-6], sc25[1][:-6], label="SC25")
color = p[-1].get_color()
ax2.axvline(x=cmds[-1], color=color, linestyle=":")
ax2.tick_params(axis='y', labelcolor="k")
ax2.set_ylabel("SSN")

This works as intended, producing this plot:

enter image description here

However, I would much prefer it if the purple plot which belongs to ax1 were limited to only part of the axis, so as to not clutter up the plot needlessly. In this case it would for example be great to limit the entire range to just the portion of the axis that is now covered by -100 to -50, placing the entire range of the purple plot there. Any suggestions on how to do this?


Solution

  • Given that the purple plot is the only one in ax1, you can play with the y limits, in order to place your purple plot in the position you want. For instance:

    ax1.set_ylim((-300, 500))
    

    You can go further, and limit the y ticks to the relevant range. For instance:

    ax1.set_yticks([-200, -100, 0, 100, 200])