Skip to content Skip to sidebar Skip to footer

Color Axis Spine With Multiple Colors Using Matplotlib

Is it possible to color axis spine with multiple colors using matplotlib in python? Desired output style:

Solution 1:

You can use a LineCollection to create a multicolored line. You can then use the xaxis-transform to keep it fixed to the xaxis, independent of the y-limits. Setting the actual spine invisible and turning clip_on off makes the LineCollection look like the axis spine.

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

fig, ax = plt.subplots()

colors=["b","r","lightgreen","gold"]
x=[0,.25,.5,.75,1]
y=[0,0,0,0,0]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments,colors=colors, linewidth=2,
                               transform=ax.get_xaxis_transform(), clip_on=False )
ax.add_collection(lc)
ax.spines["bottom"].set_visible(False)
ax.set_xticks(x)
plt.show()

enter image description here

Solution 2:

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 inrange(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 inrange(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

Post a Comment for "Color Axis Spine With Multiple Colors Using Matplotlib"