Reputation: 3961
I'm trying to display a dictionary of custom colors in Python using the example in the matplotlib docs
import numpy as np
import matplotlib.pyplot as plt
th = np.linspace(0, 2*np.pi, 512)
fig, ax1 = plt.subplots(1, 1, figsize=(6, 3))
def color_demo(ax, colors, title):
ax.set_title(title)
for j, c in enumerate(colors):
v_offset = -(j / len(colors))
ax.plot(th, .1*np.sin(th) + v_offset, color=c)
ax.annotate("'C{}'".format(j), (0, v_offset),
xytext=(-1.5, 0),
ha='right',
va='center',
color=c,
textcoords='offset points',
family='monospace')
ax.annotate("{!r}".format(c), (2*np.pi, v_offset),
xytext=(1.5, 0),
ha='left',
va='center',
color=c,
textcoords='offset points',
family='monospace')
ax.axis('off')
mycolors = {
'br': ((84/255), (0/255), (0/255)),
'bl': ((15/255), (123/255), (175/255)),
'yl': ((255/255), (186/255), (45/255)),
'rd': ((237/255), (23/255), (69/255)),
'gy': ((210/255), (210/255), (210/255))
}
color_demo(ax1, mycolors, 'mycolors')
fig.subplots_adjust(**{'bottom': 0.0, 'left': 0.059,
'right': 0.869, 'top': 0.895})
But I get the error ValueError: 'br1' is not a valid value for color
.
Upvotes: 0
Views: 988
Reputation: 44838
Here's an experiment:
>>> mycolors = {
... 'br': ((84/255.0), (0/255.0), (0/255.0)),
... 'bl': ((15/255.0), (123/255.0), (175/255.0)),
... 'yl': ((255/255.0), (186/255.0), (45/255.0)),
... 'rd': ((237/255.0), (23/255.0), (69/255.0)),
... 'gy': ((210/255.0), (210/255.0), (210/255.0))
... }
>>>
>>> for i, c in enumerate(mycolors):
... print(i, c)
...
0 br
1 bl
2 yl
3 rd
4 gy
>>>
Is that what you expected this code to do? Iterating over a dictionary like this actually iterates over its keys.
The error I got while running your code says:
ValueError: 'br' is not a valid value for color
It tried to use the first key ('br'
) as a color, which Matplotlib tried to interpret as the name of the color, but it turned out that "'br' is not a valid value for color".
You should iterate over the values of the dictionary:
for j, c in enumerate(colors.values()):
...
Resulting plot:
Upvotes: 1
Reputation: 304
br
, bl
, etc... are not colors by default. I think what you want is:
def color_demo(ax, colors, title):
ax.set_title(title)
for j, c in enumerate(colors):
v_offset = -(j / len(colors))
ax.plot(th, .1*np.sin(th) + v_offset, color=colors[c])
ax.annotate("'C{}'".format(j), (0, v_offset),
xytext=(-1.5, 0),
ha='right',
va='center',
color=c,
textcoords='offset points',
family='monospace')
ax.annotate("{!r}".format(c), (2*np.pi, v_offset),
xytext=(1.5, 0),
ha='left',
va='center',
color=colors[c],
textcoords='offset points',
family='monospace')
ax.axis('off')
Upvotes: 0