Color axis spine with multiple colors using matplotlib

Viewed 776

Is it possible to color axis spine with multiple colors using matplotlib in python?

Desired output style:

enter image description here

2 Answers

Here is a slightly different solution. If you don't want to recolor the complete axis, you can use zorder to make sure the colored line segments are visible on top of the original axis.

After drawing the main plot:

  • save the x and y limits
  • draw a horizontal line at ylims[0] between the chosen x-values with the desired color
  • clipping should be switched off to allow the line to be visible outside the strict plot area
  • zorder should be high enough to put the new line in front of the axes
  • the saved x and y limits need to be put back, because drawing extra lines moved them (alternatively, you might have turned off autoscaling the axes limits by calling plt.autoscale(False) before drawing the colored axes)
from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 20, 100)
for i in range(10):
    plt.plot(x, np.sin(x*(1-i/50)), c=plt.cm.plasma(i/12))

xlims = plt.xlim()
ylims = plt.ylim()
plt.hlines(ylims[0], 0, 10, color='limegreen', lw=1, zorder=4, clip_on=False)
plt.hlines(ylims[0], 10, 20, color='crimson', lw=1, zorder=4, clip_on=False)
plt.vlines(xlims[0], -1, 0, color='limegreen', lw=1, zorder=4, clip_on=False)
plt.vlines(xlims[0], 0, 1, color='crimson', lw=1, zorder=4, clip_on=False)
plt.xlim(xlims)
plt.ylim(ylims)

plt.show()

example plot

To highlight an area on the x-axis, also axvline or axvspan can be interesting. An example:

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 25, 100)
for i in range(10):
    plt.plot(x, np.sin(x)*(1-i/20), c=plt.cm.plasma(i/12))
plt.axvspan(10, 20, color='paleturquoise', alpha=0.5)
plt.show()

axvspan example

Related