Issue
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?
Solution
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:
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()
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.