Mert Şölen
Mert Şölen

Reputation: 61

How To Assign Color Values To Vertices Instead of Face Colors in Matplotlib When Plotting a Polygon?

I have data regarding x, y and color values which are all NxM arrays. Normally, when using Polygon function from Matplotlib, it needs to have color values per FACE (which would be a 1xM array) instead of VERTEX. However, my color data is per VERTEX. So, my question is that is there a way to convert my vertex data to single face color data? Or even better, is there a way to plot polygons using color values per vertex instead of per face?

Note: What I want is quite similar to MATLAB's patch function which you can use color values per vertex.

Edit: Below, you can find a data example of one element. A mesh consists of many elements and below is just one of them. X and Y refer to coordinates and C refers to color values of each coordinate. Note that the below arrays are actually stored as columns in the original code as there are many other elements.

import numpy as np

X = np.array([0,0.176611,0.343377,0.366506,0.390424,0.254526,0.117785,0.602218])
Y = np.array([0,0.0248673,0.0436277,0.0834644,0.123043,0.110448,0.0995953,0.0509885])
C = np.array([0.136649,0.114582,0.100576,0.102412,0.102754,0.104971,0.110123,0.120756])

Upvotes: 3

Views: 1294

Answers (1)

JohanC
JohanC

Reputation: 80319

To assign colors to vertices instead of faces, pcolormesh accepts the parameter shading='gouraud'. Here is an example:

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 15, 8)
y = np.linspace(0, 10, 5)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)

fig, axs = plt.subplots(ncols=2, figsize=(12, 3))
cmap = 'plasma'
axs[0].scatter(X, Y, s=50, c=Z, cmap=cmap, edgecolors='black')
axs[0].set_title('given vertex colors')
axs[1].pcolormesh(x, y, Z, shading='gouraud', cmap=cmap)
axs[1].scatter(X, Y, s=50, c=Z, cmap=cmap, edgecolors='black')
axs[1].set_title('interpolated vertex colors')
axs[1].set_xlim(axs[0].get_xlim())
axs[1].set_ylim(axs[0].get_ylim())
plt.show()

example plot

Upvotes: 3

Related Questions