How to color space between two lines with a colour transition? - python-3.x

How to colour space between two lines with a colour transition? For instance, with grey colour - the dark grey from the upper line should become lighter as proceeding to the lower line. Thank you
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]
x = np.linspace(0, 1, 100)
y = 0.3*x
ax.set_ylim(-0.2, 0.6)
ax.plot(x, y)
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
ax.plot(x, y - 0.1*width_l)
plt.show()
Edit
And this, please? How to make the width of the coloured part the same?
import matplotlib.pyplot as plt
import numpy as np
import pywt
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]
wavelet = pywt.ContinuousWavelet('morl')
psi, x = wavelet.wavefun(level=2)
cmap = plt.get_cmap('Greys_r')
ax.plot(x, psi)
ax.set_xlim(ax.get_xlim()[0], ax.get_xlim()[1])
y_a = ax.get_ylim()
ax.set_ylim(y_a[0],y_a[1]*1.3)
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
x_range = ax.get_xlim()[1] - ax.get_xlim()[0]
x_shift = x_range * 0.1
ax.plot([x[0]+x_shift, x[1]+x_shift], [psi[0], psi[1]])
ax.plot([x[2]-x_shift, x[3]-x_shift], [psi[2], psi[3]])
ax.plot([x[1], x[2]], [psi[1]-width_l*0.1, psi[2]-width_l*0.1])
for t in np.linspace(0, 1, 40):
ax.plot(x, psi - t * 0.1 * width_l, color=cmap(t/2 + 0.25))
plt.show()

You could draw a lot of parallel lines (or curves) using a color from a gray-scale colormap. The example code below uses a transformation u = t/2 + 0.25, so when t goes from 0 to 1, u would just go between 0.25 and 0.75 to select of specific range from the colormap, avoiding the very dark and very light parts.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]
x = np.linspace(0, 1, 100)
y = 0.3 * x
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
ax.set_ylim(-0.2, 0.6)
cmap = plt.get_cmap('Greys_r')
for t in np.linspace(0, 1, 40):
u = t/2 + 0.25
ax.plot(x, y - t * 0.1 * width_l, color=cmap(u))
ax.plot(x, y)
ax.plot(x, y - 0.1 * width_l)
plt.show()

Related

plotting of 3-d softmax function using matplotlib

I would like to illustrate a detailed function similar to the softmax function.
The formula is as shown in the image.
I wrote it in python based on the following blog. Sorry, written in Japanese.
https://www.anarchive-beta.com/entry/2020/06/07/180000
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib
from mpl_toolkits.mplot3d.axes3d import Axes3D
%matplotlib notebook
def softmax(x, a, b, d):
x = x - np.max(x, axis=-1, keepdims=True)
return (np.exp(a * (x - d))*b / np.sum(np.exp(a * (x - d)), axis=-1, keepdims=True))
# input
x_vals = np.arange(0, 10, 0.01)
x2_vals = np.arange(0, 10, 0.01)
X0_vals, X1_vals = np.meshgrid(x_vals, x2_vals)
X_vals = np.array([
X0_vals.flatten(),
X1_vals.flatten()
]).T
print(X_vals)
print(X_vals[:5])
print(X_vals.shape)
input_shape = X0_vals.shape
print(input_shape)
Y_vals = softmax(X_vals, 12, 0.8, [10,10])
print(np.round(Y_vals[:5], 3))
print(np.sum(Y_vals[:5], axis=1))
Y0_vals = np.array(Y_vals[:, 0]).reshape(input_shape)
fig = plt.figure(figsize=(5, 5))
ax = Axes3D(fig)
ax.plot_wireframe(X0_vals, X1_vals, Y0_vals, label='$y_0$')
ax.set_xlabel('$x_0$')
ax.set_ylabel('$x_1$')
ax.set_zlabel('$y_0$')
ax.set_title('Softmax Function', fontsize=20)
ax.legend()
ax.set_zlim(0, 1)
ax.view_init(elev=20, azim=240)
plt.show()
Y_vals = softmax(X_vals, 12, 0.8, 0)
print(np.round(Y_vals[:5], 3))
print(np.sum(Y_vals[:5], axis=1))
Y0_vals = np.array(Y_vals[:, 0]).reshape(input_shape)
fig = plt.figure(figsize=(5, 5))
ax = Axes3D(fig)
ax.plot_wireframe(X0_vals, X1_vals, Y0_vals, label='$y_0$')
ax.set_xlabel('$x_0$')
ax.set_ylabel('$x_1$')
ax.set_zlabel('$y_0$')
ax.set_title('Softmax Function', fontsize=20)
ax.legend()
ax.set_zlim(0, 1)
ax.view_init(elev=20, azim=240)
plt.show()
(1)
I try to plot the picture with a_1 = a_2 = 12, b = 0.8, c_1 = c_2 = 12. However, I could not find the differences with a_1 = a_2 = 12, b = 0.8, c_1 = c_2 = 0.
How should I write the code?
(2)
I have no idea to plot when a_1 is not equal to a_2, or c_1 is not equal to c_2.
(3)
I would like to overlap a scatterplot of any point on a function, but it does not overlap properly.
There might be similar questions, but I'm not so familiar with the 3-D plot, so I would be glad to show me the details.

Change colorbar limits without changing the values of the data it represents in scatter

I'm trying to change a colorbar attached to a scatter plot so that the minimum and maximum of the colorbar are the minimum and maximum of the data, but I want the data to be centred at zero as I'm using a colormap with white at zero. Here is my example
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 61)
y = np.linspace(0, 1, 61)
C = np.linspace(-10, 50, 61)
M = np.abs(C).max() # used for vmin and vmax
fig, ax = plt.subplots(1, 1, figsize=(5,3), dpi=150)
sc=ax.scatter(x, y, c=C, marker='o', edgecolor='k', vmin=-M, vmax=M, cmap=plt.cm.RdBu_r)
cbar=fig.colorbar(sc, ax=ax, label='$R - R_0$ (mm)')
ax.set_xlabel('x')
ax.set_ylabel('y')
As you can see from the attached figure, the colorbar goes down to -M, where as I want the bar to just go down to -10, but if I let vmin=-10 then the colorbar won't be zerod at white. Normally, setting vmin to +/- M when using contourf the colorbar automatically sorts to how I want. This sort of behaviour is what I expect when contourf uses levels=np.linspace(-M,M,61) rather than setting it with vmin and vmax with levels=62. An example showing the default contourf colorbar behaviour I want in my scatter example is shown below
plt.figure(figsize=(6,5), dpi=150)
plt.contourf(x, x, np.reshape(np.linspace(-10, 50, 61*61), (61,61)),
levels=62, vmin=-M, vmax=M, cmap=plt.cm.RdBu_r)
plt.colorbar(label='$R - R_0$ (mm)')
Does anyone have any thoughts? I found this link which I thought might solve the problem, but when executing the cbar.outline.set_ydata line I get this error AttributeError: 'Polygon' object has no attribute 'set_ydata' .
EDIT a little annoyed that someone has closed this question without allowing me to clarify any questions they might have, as none of the proposed solutions are what I'm asking for.
As for Normalize.TwoSlopeNorm, I do not want to rescale the smaller negative side to use the entire colormap range, I just want the colorbar attached to the side of my graph to stop at -10.
This link also does not solve my issue, as it's the TwoSlopeNorm solution again.
After changing the ylim of the colorbar, the rectangle formed by the surrounding spines is too large. You can make this outline invisible. And then add a new rectangular border:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 61)
y = np.linspace(0, 1, 61)
C = np.linspace(-10, 50, 61)
M = np.abs(C).max() # used for vmin and vmax
fig, ax = plt.subplots(1, 1, figsize=(5, 3), dpi=150)
sc = ax.scatter(x, y, c=C, marker='o', edgecolor='k', vmin=-M, vmax=M, cmap=plt.cm.RdBu_r)
cbar = fig.colorbar(sc, ax=ax, label='$R - R_0$ (mm)')
cb_ymin = C.min()
cb_ymax = C.max()
cb_xmin, cb_xmax = cbar.ax.get_xlim()
cbar.ax.set_ylim(cb_ymin, cb_ymax)
cbar.outline.set_visible(False) # hide the surrounding spines, which are too large after set_ylim
cbar.ax.add_patch(plt.Rectangle((cb_xmin, cb_ymin), cb_xmax - cb_xmin, cb_ymax - cb_ymin,
fc='none', ec='black', clip_on=False))
plt.show()
Another approach until v3.5 is released is to make a custom colormap that does what you want (see also https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html#sphx-glr-tutorials-colors-colormap-manipulation-py)
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
fig, axs = plt.subplots(2, 1)
X = np.random.randn(32, 32) + 2
pc = axs[0].pcolormesh(X, vmin=-6, vmax=6, cmap='RdBu_r')
fig.colorbar(pc, ax=axs[0])
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap
fig, axs = plt.subplots(2, 1)
X = np.random.randn(32, 32) + 2
pc = axs[0].pcolormesh(X, vmin=-6, vmax=6, cmap='RdBu_r')
fig.colorbar(pc, ax=axs[0])
def keep_center_colormap(vmin, vmax, center=0):
vmin = vmin - center
vmax = vmax - center
dv = max(-vmin, vmax) * 2
N = int(256 * dv / (vmax-vmin))
RdBu_r = cm.get_cmap('RdBu_r', N)
newcolors = RdBu_r(np.linspace(0, 1, N))
beg = int((dv / 2 + vmin)*N / dv)
end = N - int((dv / 2 - vmax)*N / dv)
newmap = ListedColormap(newcolors[beg:end])
return newmap
newmap = keep_center_colormap(-2, 6, center=0)
pc = axs[1].pcolormesh(X, vmin=-2, vmax=6, cmap=newmap)
fig.colorbar(pc, ax=axs[1])
plt.show()

Heat map for Irregularly Spaced Data with No Interpolation

I would like to plot a heatmap where the input data is not in the typical rectangularly spaced grid. Here is some sample data:
import numpy as np
xmin = 6
xmax= 12
ymin = 0
x = np.linspace(xmin, xmax, 100)
ymax = x**2
final = []
for i in range(len(ymax)):
yrange = np.linspace(0, ymax[i], 100)
for j in range(len(yrange)):
intensity = np.random.rand()
final.append([x[i], yrange[j], intensity])
data_for_plotting = np.asarray(final) # (10000, 3) shaped array
I would like to plot intensity (in the colorbar) as a function of (x,y) which represents the position and I would like to do this without interpolation.
Here is my solution which uses matplotlib's griddata and linear interpolation.
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
total_length = 100
x1 = np.linspace(min(data_for_plotting[:,0]), max(data_for_plotting[:,0]), total_length)
y1 = np.linspace(min(data_for_plotting[:,1]), max(data_for_plotting[:,1]), total_length)
z1 = griddata(data_for_plotting[:,0], data_for_plotting[:,1], data_for_plotting[:,2], x1, y1, interp='linear')
p=plt.pcolormesh(x1, y1, z1, vmin = 0. , vmax=1.0, cmap='viridis')
clb = plt.colorbar(p)
plt.show()
I am looking for an alternate solution without interpolation as I would like to see the smallest unit of measurement in my x and y position (pixel size/rectangle). Based on the sample data given above I expect the height of the pixel to increase for large values of x.
I'm unsure what matplotlib.mlab.griddata is about. Maybe some very old version?
You could use scipy.interpolate.griddata which needs its parameters in a slightly different format. method='nearest' switches off the interpolation (default method='linear').
Here is how it could look with your test data (see griddata's documentation for more explanation and examples):
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import numpy as np
xmin = 6
xmax = 12
ymin = 0
x = np.linspace(xmin, xmax, 100)
ymax = x ** 2
final = []
for i in range(len(ymax)):
yrange = np.linspace(0, ymax[i], 100)
for j in range(len(yrange)):
intensity = np.random.rand()
final.append([x[i], yrange[j], intensity])
data_for_plotting = np.asarray(final) # (10000, 3) shaped array
total_length = 100
x1 = np.linspace(min(data_for_plotting[:, 0]), max(data_for_plotting[:, 0]), total_length)
y1 = np.linspace(min(data_for_plotting[:, 1]), max(data_for_plotting[:, 1]), total_length)
grid_x, grid_y = np.meshgrid(x1, y1)
z1 = griddata(data_for_plotting[:, :2], data_for_plotting[:, 2], (grid_x, grid_y), method='nearest')
img = plt.imshow(z1, extent=[x1[0], x1[-1], y1[0], y1[-1]], origin='lower',
vmin=0, vmax=1, cmap='inferno', aspect='auto')
cbar = plt.colorbar(img)
plt.show()
An alernative, is to create one rectangle for each of the prolonged pixels. Beware that this can be a rather slow operation. If really needed, one could create a pcolormesh for each column.
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
import numpy as np
# ... create x and data_for_plotting as before
fig, ax = plt.subplots()
cmap = plt.get_cmap('inferno')
norm = plt.Normalize(0, 1)
x_step = x[1] - x[0]
y_step = 0
for i, (xi, yi, intensity_i) in enumerate(data_for_plotting):
if i + 1 < len(data_for_plotting) and data_for_plotting[i + 1, 0] == xi: # when False, the last y_step is reused
y_step = data_for_plotting[i + 1, 1] - yi
ax.add_artist(plt.Rectangle((xi, yi), x_step, y_step, color=cmap(norm(intensity_i))))
cbar = plt.colorbar(ScalarMappable(cmap=cmap, norm=norm))
ax.set_xlim(x[0], x[-1])
ax.set_ylim(0, data_for_plotting[:, 1].max())
plt.tight_layout()
plt.show()

Matplotlib 3d - setting ticks for another axis

How to set ticks to be on the opposite axes please? When I drop it the axes changes but not in this way. Thank you
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()

How to set linewidth of axis in 3d plot in python?

How to set linewidth of axis in 3d plot in python? Is it somehow possible with mpl.rcParams?
Code:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
Try this:
ax.plot_surface(X, Y, Z, linewidth=1)

Resources