Use Python to Create Image and Row of Boxes in Matplotlib

Viewed 42

I'm trying to create a JPG that consists of an image stacked on top of a row of boxes. Below is a picture of what I'm trying to accomplish. Each of these boxes is an individual color.

How do I add an image above the color palette (row of colors)?

Here is the code I have tried:

palette, scores = ['#272727', '#fafafa', '#1a1a1a', '#979797', '#a1473d'], [0.75, 0.16, 0.05, 0.04, 0.0]

fig = plt.figure(figsize=(5,1))
ax = fig.add_subplot()
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)

for i, color in enumerate(palette):
    x = i/len(palette)
    rect = Rectangle((x, 0), .20, 1, facecolor=color)
    ax.add_patch(rect)

plt.savefig(os.path.join(save_dir, f'{id+1}.png'))

Here is the outcome of my code: enter image description here

Here is what I want: enter image description here

1 Answers

You could use plt.GridSpec (see doc here).

See code below:

import matplotlib.pyplot as plt


palette, scores = ['#272727', '#fafafa', '#1a1a1a', '#979797', '#a1473d'], [0.75, 0.16, 0.05, 0.04, 0.0]

fig = plt.figure(figsize=(6,10))
gs=plt.GridSpec(8,3)
ax=plt.subplot(gs[7:8,0:3])

ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)

for i, color in enumerate(palette):
    x = i/len(palette)
    rect = plt.Rectangle((x, 0), .20, 1, facecolor=color)
    ax.add_patch(rect)

plt.box(False)

ax2=plt.subplot(gs[0:7,0:3])
img=plt.imread('b.jpg')
ax2.imshow(img,aspect='auto')
ax2.axes.xaxis.set_visible(False)
ax2.axes.yaxis.set_visible(False)

plt.box(False)
plt.tight_layout()
plt.show()

And the output returns the following:

enter image description here

Related