Issue
The following contourf plots were created in Python as well as in Mathcad. The colormap for both plots is 'Greens'. I'd like my plot to look like Mathcad's where low values are represented by black (or very dark green). In order to achieve this, I used the hint given here, but it still looks very different from the plot in Mathcad. Can anyone provide suggestions on how my colormap resembles Mathcad's colormap?
The code is as follows:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
r = np.linspace(0, 1.5, 50)
p = np.linspace(0, 2*np.pi, 50)
R, P = np.meshgrid(r, p)
z1 = ((R**2 - 1)**2)
# Express the mesh in the cartesian system.
x1, y1 = R*np.cos(P), R*np.sin(P)
fig = plt.Figure()
ax = plt.axes()
levels = np.linspace(z1.min(), z1.max(), 100)
cmap = mpl.cm.Greens_r(np.linspace(0,1,100))
cmap = mpl.colors.ListedColormap(cmap[:,:70])
cont = ax.contourf(x1, y1, z1, cmap=cmap, vmin=z1.min(), vmax=z1.max(), levels=levels)
plt.colorbar(cont)
plt.title('Matplotlib')
plt.show()
Solution
The Greens
colormap goes from Black to Green to White in matplotlib. You only want the portion going from Black to Green (also, the green you want is more vivid than in the matplotlib colormap). There are several options available to achieve this (e.g. you could truncate the colormap using something like the answer here). But, a simpler option is to create your own colormap which starts at black and ends at green. You can then control the tone of the green as well, to get a closer match to your desired colormap from mathcad.
We can do this using the matplotlib.colors.LinearSegmentedColormap.from_list()
function.
For example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.colors as colors
mygreens = colors.LinearSegmentedColormap.from_list('mygreens',
['#000000', '#00FF00'])
r = np.linspace(0, 1.5, 50)
p = np.linspace(0, 2*np.pi, 50)
R, P = np.meshgrid(r, p)
z1 = ((R**2 - 1)**2)
# Express the mesh in the cartesian system.
x1, y1 = R*np.cos(P), R*np.sin(P)
fig = plt.Figure()
ax = plt.axes()
levels = np.linspace(z1.min(), z1.max(), 100)
cont = ax.contourf(x1, y1, z1, cmap=mygreens, vmin=z1.min(), vmax=z1.max(), levels=levels)
plt.colorbar(cont)
plt.title('Matplotlib')
plt.show()
Answered By - tmdavison
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.