Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting each tickline with individually specified color

I am trying to change the color of the ticklines in my plot, where I would like to assign the colors based on a list of strings with color codes. I am following the following approach, but I cannot see why that does not work:

import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = np.sin(x)
y2 = np.tan(x)
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, y)
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, y2)
colors = ['b', 'g', 'r', 'c', 'm', 'y']
ax1.set_xticks(x)
for tick, tickcolor in zip(ax1.get_xticklines(), colors):
    tick._color = tickcolor
plt.show()

Does anyone know the correct implementation of this?

like image 351
HWIK Avatar asked Oct 30 '25 02:10

HWIK


1 Answers

As noted in comments, tick._color/tick.set_color(tickcolor) isn't working due to a bug:

Using tick.set_markeredgecolor is the workaround, but it doesn't seem to be the only issue. ax1.get_xticklines() yields the actual ticks lines on every two items, you should thus only zip those:

for tick, tickcolor in zip(ax1.get_xticklines()[::2], colors):
    tick.set_markeredgecolor(tickcolor)

Output:

enter image description here

NB. also changing the ticks width for better visualization of the colors.

Full code:

import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5]
y = np.sin(x)
y2 = np.tan(x)
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax1.plot(x, y)
ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(x, y2)
colors = ['b', 'g', 'r', 'c', 'm', 'y']
ax1.set_xticks(x)
for tick, tickcolor in zip(ax1.get_xticklines()[::2], colors):
    tick.set_markeredgecolor(tickcolor)
    tick.set_markeredgewidth(4)
plt.show()
like image 120
mozway Avatar answered Oct 31 '25 15:10

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!