Issue
Now I have some points coordinates and corresponding RGB color like:
((1, 0), (12, 20), (11, 0), (12, 28), (9, 24), (3, 17), (1, 13), (11, 0))
and their color:
[[0., 0., 0.],
[0., 0., 1.],
[0., 0., 0.5],
[0.125, 0.529, 1.0],
[0.33, 0.4, 0.67],
[0.6, 0.5, 1.0],
[0., 1., 0.],
[1., 0., 0.]]
I want show my point by imshow() method, not scatter method(),like convert this image:
to this style, how to do it:
Solution
You can create a ListedColormap
from the colors. And then fill in a matrix using the given positions.
Note that to be able to create smooth intermediate colors, matplotlib needs a sequential colormap. Instead of explicit colors, you'd need to provide single numbers between 0 and 1 to indicate a color in such a colormap.
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
pos = ((1, 0), (12, 20), (11, 0), (12, 28), (9, 24), (3, 17), (1, 13), (11, 0))
colors = [[0., 0., 0.],
[0., 0., 1.],
[0., 0., 0.5],
[0.125, 0.529, 1.0],
[0.33, 0.4, 0.67],
[0.6, 0.5, 1.0],
[0., 1., 0.],
[1., 0., 0.]]
pos = np.array(pos)
M = pos[:, 0].max() + 1
N = pos[:, 1].max() + 1
matrix = np.full((M, N), np.nan)
matrix[pos[:, 0], pos[:, 1]] = np.arange(len(pos))
cmap = ListedColormap(colors)
plt.imshow(matrix, cmap=cmap, origin='lower')
plt.show()
The following approach creates a smooth image, using colors from gist_rainbow
and supposes more points are given. SmoothBivariateSpline
smoothens out the values. As a comparison, also the result of tricontourf
is shown.
from scipy.interpolate import SmoothBivariateSpline
from matplotlib import pyplot as plt
import numpy as np
pos = np.zeros((50, 2))
pos[:, 0] = np.random.randint(0, 13, len(pos))
pos[:, 1] = np.random.randint(0, 29, len(pos))
colors = np.random.rand(len(pos))
pos = np.array(pos)
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(20, 4))
ax1.scatter(pos[:, 1], pos[:, 0], s=50, c=colors, cmap='gist_rainbow')
ax2.tricontourf(pos[:, 1], pos[:, 0], colors, levels=256, cmap='gist_rainbow')
M = pos[:, 0].max()
N = pos[:, 1].max()
interp = SmoothBivariateSpline(pos[:, 1], pos[:, 0], colors, kx=1, ky=1)
x, y = np.linspace(0, N, 100), np.linspace(0, M, 100)
ax3.imshow(interp(x, y).T, cmap='gist_rainbow', extent=[0, N, 0, M], aspect='auto', origin='lower')
plt.show()
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.