Reputation: 11
Matplotlib recognize color in many formats, including as a tuple. What's wrong with this code? Thanks.
import numpy as np
import matplotlib.pyplot as plt
data = []
for _ in xrange(2):
data.append((np.random.rand(), np.random.rand()))
data.append((np.random.rand(), np.random.rand()))
# data.append('b') # this works
# data.append('0.5') # this also works
color = (0.1, 0.2, 0.3)
data.append(tuple(color)) # this does not work
plt.plot(*data)
plt.show()
Upvotes: 1
Views: 1281
Reputation: 11
I experienced the same problem. The cause of the problem is that the color tuple is being interpreted as data, which of course is what neither you nor I want. The workaround is to convert the color tuple to a color string.
from matplotlib.colors import to_hex # convert to hex string
if not isinstance(color, str):
color = to_hex(color)
In your case, include the import. Then change data append line:
data.append(to_hex(color))
Upvotes: 0
Reputation: 223152
you're passing everything as data
so you're plotting this:
[
(0.45, 0.36),
(0.33, 0.78),
(0.1, 0.2, 0.3),
]
You will get a value error, because your table of data has two values in the first two rows but three values in the third row.
Upvotes: 3