0

My data is a 100 x 100 array of strings which are all hex codes:

[['#10060e' '#11070f' '#060409' ... '#08030a' '#09030d' '#12050f']
['#110600' '#09010e' '#0d0210' ... '#09030f' '#08060b' '#160a0a']
['#0a070e' '#13060f' '#0c040f' ... '#0c0610' '#0e040c' '#0a020f']
...
['#0c020d' '#09040b' '#10070c' ... '#0a090f' '#160613' '#08000f']
['#0a020f' '#09040a' '#150812' ... '#11040d' '#07040b' '#0b060d']
['#0d0715' '#0e020c' '#140710' ... '#0a0112' '#12090e' '#0c020d']]

Matplotlib: throws this error: TypeError: cannot perform reduce with flexible type

I think the issue it is having is it cannot give a colour to these as they are strings, not numbers. I can only find examples where all the data is numerical and has a colour map applied to it, nothing where every bit of data's colour is specified. I would like to tell Matplotlib what colour I'd like all of these to be using, surprise surprise, the hex codes. How can I go about doing that?

Full(er) code sample:

z = np.asanyarray(pixel_arr)
x = np.arange(0, width, 1)  # len = 100
y = np.arange(0, height, 1)  # len = 100

fig, ax = plt.subplots()
ax.pcolormesh(x, y, z)
plt.show()
1
  • I didn't realise that was possible. Will have a go at it later today. Would you be able to point me in the direction of some sample code? Commented May 17, 2021 at 18:10

1 Answer 1

1

I would like to tell Matplotlib what colour I'd like all of these to be using

It sounds like you have a bunch of pixel values you want to plot, i.e., an image. So you can treat it like one.

import matplotlib.pyplot as plt
import numpy as np

data = np.array([['#10060e', '#11070f', '#060409', '#08030a', '#09030d', '#12050f'],
                 ['#110600', '#09010e', '#0d0210', '#09030f', '#08060b', '#160a0a'],
                 ['#0a070e', '#13060f', '#0c040f', '#0c0610', '#0e040c', '#0a020f'],
                 ['#0c020d', '#09040b', '#10070c', '#0a090f', '#160613', '#08000f'],
                 ['#0a020f', '#09040a', '#150812', '#11040d', '#07040b', '#0b060d'],
                 ['#0d0715', '#0e020c', '#140710', '#0a0112', '#12090e', '#0c020d']])

img = [[tuple(bytes.fromhex(pixel[1:])) for pixel in row] for row in data]
img = np.array(img, dtype=np.uint8)
plt.imshow(img)
plt.show()

The output may be dark at first glance, but that's because I used the data you showed us, which all happen to be very dark pixels.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.