How to 4D plot with contour over cube, using matplotlib? - python

I would like to 4D plot over the cube (x,y,z) vs. q, using the colormap on the 3 surfaces of the cubes, where the color and contour are determined depending on the q variable. Basically, I am looking for a similar image like this:
Any help is appreciated.

See my example of 3D ABC feild
import pyvista as pv
import numpy as np
from numpy import mgrid
import matplotlib.pyplot as plt
print('initializing domain')
xmin = -800.
xmax = 800.
Lx = xmax-xmin
B0 = 1
k = 1
alpha = 2.0*np.pi*k/Lx
x, y, z = Lx*mgrid[0:1:51j, 0:1:51j, 0:1:51j]
print('initializing 3D B field')
Bx = B0*(np.sin(alpha*z) + np.cos(alpha*y))
By = B0*(np.sin(alpha*x) + np.cos(alpha*z))
Bz = B0*(np.sin(alpha*y) + np.cos(alpha*x))
B = np.column_stack((Bx.ravel(), By.ravel(), Bz.ravel()))
grid = pv.StructuredGrid(x, y, z)
grid["ABC field magnitude"] = np.linalg.norm(B, axis=1)
grid["ABC field vectors"] = B
grid.set_active_vectors("ABC field vectors")
#contours = grid.contour(8, scalars="ABC field magnitude")
#arrows = contours.glyph(orient="ABC field vectors", factor=50.0)
print('plotting')
pv.set_plot_theme('document')
p = pv.Plotter(notebook=0, shape=(1,1))
#p.background_color='white'
#p.window_size
cmap = plt.cm.get_cmap("viridis", 4)
p.add_mesh(grid, cmap=cmap)
p.show_grid()
#p.add_mesh(arrows)
#p.subplot(0,1)
#slices = grid.slice_orthogonal(x=20, y=20, z=30)
#slices = grid.slice_orthogonal()
#p.add_mesh(slices, cmap=cmap)
##p.subplot(1,0)
#p.add_mesh(contours, opacity=1)
#p.subplot(1,1)
#p.add_mesh(arrows)
#single_slice = arrows.slice(normal=[1, 1, 0])
#slices = arrows.slice_orthogonal(x=20, y=20, z=30)
#slices = grid.slice_orthogonal()
#p.add_mesh(single_slice, cmap=cmap)
p.show_grid()
p.link_views()
p.view_isometric()
p.show(screenshot='abc3d_slicing.png')

A simple answer is
import numpy as np
import matplotlib.pyplot as plt
length = 10
data = length*np.mgrid[0:1:51j, 0:1:51j, 0:1:51j].reshape(3,-1).T
contour = np.random.rand(data.shape[0])
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
data_plot = ax.scatter(data[:,0], data[:,1], data[:,2], c=contour)
fig.colorbar(data_plot)
To optimize to only boundary points
length = 10
vol_data = length*np.mgrid[0:1:51j, 0:1:51j, 0:1:51j].reshape(3,-1).T
bound_data = np.array([data_i for data_i in vol_data
if any([coord in [0, length] for coord in data_i])])
contour = np.random.rand(bound_data.shape[0])
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
data_plot = ax.scatter(bound_data[:,0], bound_data[:,1], bound_data[:,2], c=contour)
fig.colorbar(data_plot)

Related

FEA Stress plot in Python from 3 1D-arrays

I have 3 1D arrays (node x-coordinates, node y-coordinates and Von-Mises stress scalar) exported from an FEA solver.
I want to create 2D contour plots as shown below in Python:
Stress plot example
I have managed to create such plot as shown below:
Stress plot result
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
for orient in ['top', 'bot', 'side']:
x = []
y = []
z = []
stress = []
with open('data.txt') as file:
for line in file:
cur_line = line.split('\t')
cur_x_old = cur_line[0]
cur_y_old = cur_line[1]
cur_z_old = cur_line[2]
cur_s_old = cur_line[3]
if cur_x_old == 'X Location (mm)':
pass
else:
cur_x = cur_x_old.replace(",",".")
cur_y = cur_y_old.replace(",",".")
cur_z = cur_z_old.replace(",",".")
cur_s = cur_s_old.replace(",",".")
x.append(float(cur_x))
y.append(float(cur_y))
z.append(float(cur_z))
stress.append(float(cur_s))
stress = np.array(stress)
x = np.array(x)
y = np.array(y)
z = np.array(z)
levels=np.linspace(stress.min(), stress.max(), num=100)
triang = tri.Triangulation(x, y)
if orient == 'side':
plt.figure(figsize = (max(x)/50, abs(min(y))/50))
plt.tricontourf(triang, stress, cmap = 'jet', norm = mpl.colors.Normalize(0, 100), levels = levels, extend = 'max')
plt.scatter(x, y, color = 'k')
else:
plt.figure(figsize = (max(x)/50, max(z)*2/50))
plt.tricontourf(x, z, stress, cmap = 'jet', norm = mpl.colors.Normalize(0, 100), levels = levels)
My problem is that by triangulating the data, unwanted triangles are generated at the edge of the mesh (see Stress plot result). The black dots are the scatter plot from x and y coordinates. I want the colour plot to be only inside the boundaries of the grid. Is there a way to remove these unwanted triangles?

MATPLOTLIB: How to stack 2 colormaps on same plot in python?

I want to generate a plot like the below:
At the moment I am trying to play around with the alpha parameter:
import numpy as np
from matplotlib import pyplot as plt
xlocations_edensity = np.loadtxt("edensity_xaxis.txt")
ylocations_edensity = np.loadtxt("edensity_yaxis.txt")
xlocsedensity, ylocsedensity = np.meshgrid(xlocations_edensity, ylocations_edensity)
xlocations_Efield = np.loadtxt("Efield_x_axis.txt")
ylocations_Efield = np.loadtxt("Efield_y_axis.txt")
xlocsEfield, ylocsEfield = np.meshgrid(xlocations_Efield, ylocations_Efield)
edensitytensor = np.load("edensitytensor.npy") # shape (76, 257, 65)
Efieldtensor = np.load("Efieldtensor.npy")
fig, ax = plt.subplots()
ax.set(xlabel="x position [um]", ylabel="y position [um] \n")
pos2 = ax.pcolor(xlocations_Efield, ylocations_Efield, Efieldtensor[40, :, :].T, cmap="Reds", alpha=0.9)
fig.colorbar(pos2, ax=ax, label="\n Efield value [MV/m]")
pos1 = ax.pcolor(xlocations_edensity, ylocations_edensity, edensitytensor[100, :, :].T, cmap="Blues", alpha=0.5)
fig.colorbar(pos1, ax=ax, label="\n electron density value [cm^(-3)]")
plt.savefig("Efield_edensity_map.pdf")
But changing the order of plotting, I get different results. One color map ''hides'' the other.
Say I plot the Reds one first, it appears and the Blues one is hidden.
The other way around, Blues first and Reds first, the Blues hides the Reds.
The result of the above code is:
Do you have anything in mind what shall I do?
Thank you!
Setting the alpha value of the pcolor call is not that good because it applies the same transparency to all the colors on the colormap.
You could use a custom colormap with an evolving transparency, I present my try with linear and sigmoidal evolutions of alpha, you could try others. I created dummy noisy data with a Gaussian pulse to simulate the data as in your example.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
# generating dummy data
nx, ny = 257, 65
x_field, y_field = np.linspace(0,10,nx), np.linspace(0,6,ny)
field = np.random.rand(nx,ny)
# normalizing
field -= np.min(field); field /= np.max(field)
x_density, y_density = np.linspace(1,6,nx), np.linspace(1,6,ny)
Y, X = np.meshgrid(y_density,x_density,)
density = np.random.rand(nx,ny) # shape (76, 257, 65)
gaussian_center = (4.0,4.0)
distance_square = (X - gaussian_center[0])**2 + (Y - gaussian_center[1])**2
density += 5.0*np.exp(-distance_square/4.0)
# normalizing
density -= np.min(density); density /= np.max(density)
# getting the original colormap
orig_cmap = plt.get_cmap('Blues')
cmap_n = orig_cmap.N
derived_cmap = orig_cmap(np.arange(cmap_n))
fig, axs = plt.subplots(
4,3,
gridspec_kw={"width_ratios":[1, 0.025, 0.025]},
figsize=(10,8),
constrained_layout=True)
# original
row_subplot = 0
ax = axs[row_subplot,0]
ax.set_ylabel("original")
image_field = ax.pcolor(
x_field, y_field, field.T,
cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
cmap=orig_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
# option 1 - transparent pseudocolor for the above image
row_subplot = 1
ax = axs[row_subplot,0]
ax.set_ylabel("transparent pcolor")
image_field = ax.pcolor(
x_field, y_field, field.T,
alpha=1.0, cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
alpha=0.5, cmap=orig_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
# option 2 - linear gradient colormap
linear_cmap = derived_cmap.copy()
linear_cmap[:,-1] = np.arange(cmap_n)/cmap_n
linear_cmap = ListedColormap(linear_cmap)
row_subplot = 2
ax = axs[row_subplot,0]
ax.set_ylabel("linear gradient")
image_field = ax.pcolor(
x_field, y_field, field.T,
cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
cmap=linear_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)
# option 3 - sigmoid gradient
sigmoid_cmap = derived_cmap.copy()
x = np.linspace(-10,10,cmap_n)
sigmoid_cmap[:,-1] = np.exp(x)/(np.exp(x) + 1)
sigmoid_cmap = ListedColormap(sigmoid_cmap)
row_subplot = 3
ax = axs[row_subplot,0]
ax.set_ylabel("sigmoid gradient")
image_field = ax.pcolor(
x_field, y_field, field.T,
cmap="Reds", shading='auto')
fig.colorbar(image_field, cax=axs[row_subplot,-2],)
image_density = ax.pcolor(
x_density, y_density, density.T,
cmap=sigmoid_cmap, shading="auto")
fig.colorbar(image_density, cax=axs[row_subplot,-1],)

Embed subplot in cartopy map

I want to embed subplots canvas inside a cartopy projected map. I wrote this code to show the expected result by using rectangles:
#%%
import numpy as np
import cartopy as cr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from cartopy.io import shapereader
import geopandas
resolution = '10m'
category = 'cultural'
name = 'admin_0_countries'
shpfilename = shapereader.natural_earth(resolution, category, name)
# read the shapefile using geopandas
df = geopandas.read_file(shpfilename)
# read the country borders
usa = df.loc[df['ADMIN'] == 'United States of America']['geometry'].values[0]
can = df.loc[df['ADMIN'] == 'Canada']['geometry'].values[0]
central_lon, central_lat = -80, 60
extent = [-85, -55, 40, 62]
# ax = plt.axes(projection=ccrs.Orthographic(central_lon, central_lat))
#Golden ratio
phi = 1.618033987
h = 7
w = phi*h
fig = plt.figure(figsize=(w,h))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
#Set map extent
ax.set_extent(extent)
ax.set_xticks(np.linspace(extent[0],extent[1],11))
ax.set_yticks(np.linspace(extent[2],extent[3],6))
ax.add_geometries(usa, crs=ccrs.PlateCarree(), facecolor='none',
edgecolor='k')
# ax.gridlines()
ax.coastlines(resolution='50m')
nx, ny = 7,6
#Begin firts rectangle
xi = extent[0] + 0.5
yi = extent[2] + 0.5
x, y = xi, yi
#Loop for create the plots grid
for i in range(nx):
for j in range(ny):
#Inner rect height
in_h = 2.8
#Draw the rect
rect = ax.add_patch(mpatches.Rectangle(xy=[x, y], width=phi*in_h, height=in_h,
facecolor='blue',
alpha=0.2,
transform=ccrs.PlateCarree()))
#Get vertex of the drawn rectangle
verts = rect.get_path().vertices
trans = rect.get_patch_transform()
points = trans.transform(verts)
#Refresh rectangle coordinates
x += (points[1,0]-points[0,0]) + 0.2
if j == ny-1:
x = xi
y += (points[2,1]-points[1,1]) + 0.2
# print(points)
fig.tight_layout()
fig.savefig('Figure.pdf',format='pdf',dpi=90)
plt.show()
This routine prints this figure
What I am looking for is a way to embed plots that match every single rectangle in the figure. I tried with fig.add_axes, but I couldn't get that mini-canvas match with the actual rectangles.
Since you want to embed the axes inside the parent axes is recommend using inset_axes, see the documentation here.
I wrote simple code to demonstrate how it works. Clearly there will be some tweaking of the inset_axes positions and sizes necessary for your desired output, but I think my trivial implementation already does decent.
All created axes instances are stored in a list so that they can be accessed later.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
axis = []
x = np.linspace(-85, -55)
y = np.linspace(40, 62)
ax.plot(x, y)
offset_l = 0.05
offset_h = 0.12
num_x = 6
num_y = 7
xs = np.linspace(offset_l, 1-offset_h, num_x)
ys = np.linspace(offset_l, 1-offset_h, num_y)
for k in range(num_x):
for j in range(num_y):
ax_ins = ax.inset_axes([xs[k], ys[j], 0.1, 0.1])
ax_ins.axhspan(0, 1, color='tab:blue', alpha=0.2)
axis.append(ax_ins)
Alternatively, you can also specify the inset_axes positions using data coordinates, for this you have to set the kwarg transform in the method to transform=ax.transData, see also my code below.
import matplotlib.pyplot as plt
import numpy as np
#Golden ratio
phi = 1.618033987
h = 7
w = phi*h
fig, ax = plt.subplots(figsize=(w, h))
axis = []
x = np.linspace(-85, -55)
y = np.linspace(40, 62)
ax.plot(x, y)
offset_l = 0.05
offset_h = 0.12
num_x = 6
num_y = 7
fig.tight_layout()
extent = [-85, -55, 40, 62]
xi = extent[0] + 0.5
yi = extent[2] + 0.5
in_h = 2.8
in_w = phi * 2.8
spacing = 0.4
for k in range(num_x):
for j in range(num_y):
ax_ins = ax.inset_axes([xi+k*(in_w + phi*spacing), yi+j*(in_h + spacing),
in_w, in_h], transform=ax.transData)
ax_ins.axhspan(0, 1, color='tab:blue', alpha=0.2)
axis.append(ax_ins)

Python Plot 3d Vectors

Supppse that I wanted to take the following three [x,y,z] coordinates:
[0.799319 -3.477045e-01 0.490093]
[0.852512 9.113778e-16 -0.522708]
[0.296422 9.376042e-01 0.181748]
And plot them as vectors where the vector's start at the origin [0,0,0]. How can I go about doing this? I've been trying to use matplotlib's quiver, but I keep geting the following value error:
ValueError: need at least one array to concatenate
Here's my code (document_matrix_projections are the three coordinates above represented as a matrix):
D1, D2, D3 = zip(*document_matrix_projections)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(D1)
plt.show()
A good and pretty alternative to using matplolib's quiver() will be to plot using plotly which has the advantage of being interactive. The following function can plot vectors using the Scatter3d() in plotly. Here, the vectors have a big point to mark the direction instead of an arrowhead.
import numpy as np
import plotly.graph_objs as go
def vector_plot(tvects,is_vect=True,orig=[0,0,0]):
"""Plot vectors using plotly"""
if is_vect:
if not hasattr(orig[0],"__iter__"):
coords = [[orig,np.sum([orig,v],axis=0)] for v in tvects]
else:
coords = [[o,np.sum([o,v],axis=0)] for o,v in zip(orig,tvects)]
else:
coords = tvects
data = []
for i,c in enumerate(coords):
X1, Y1, Z1 = zip(c[0])
X2, Y2, Z2 = zip(c[1])
vector = go.Scatter3d(x = [X1[0],X2[0]],
y = [Y1[0],Y2[0]],
z = [Z1[0],Z2[0]],
marker = dict(size = [0,5],
color = ['blue'],
line=dict(width=5,
color='DarkSlateGrey')),
name = 'Vector'+str(i+1))
data.append(vector)
layout = go.Layout(
margin = dict(l = 4,
r = 4,
b = 4,
t = 4)
)
fig = go.Figure(data=data,layout=layout)
fig.show()
Plotting can be done simply by,
p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]
vector_plot([p0,p1,p2])
The output of the above looks:
The quiver() function needs locations of the arrows as X,Y,Z and U,V,W as the components of the arrow. So the following script can plot your data:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]
origin = [0,0,0]
X, Y, Z = zip(origin,origin,origin)
U, V, W = zip(p0,p1,p2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(X,Y,Z,U,V,W,arrow_length_ratio=0.01)
plt.show()
But the results are not pretty. If you would like to use Mayavi, the following works:
import numpy as np
import mayavi.mlab as m
p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]
origin = [0,0,0]
X, Y, Z = zip(origin,origin,origin)
U, V, W = zip(p0,p1,p2)
m.quiver3d(X,Y,Z,U,V,W)

How to color parts of links in dendrograms using scipy in python?

I can color labels in Python dendrograms but I don't know how to color parts of the links belonging its labels.. I want to make something like this:
Is it possible in Python?
Here I color only labels:
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as sc
dists = np.array([[0,2,1,4],[2,0,3,5],[1,3,0,6],[4,5,6,0]])
l = ['a','b','c','b']
Z = sc.linkage(dists, method='complete')
d = sc.dendrogram(Z, labels=l)
label_colors = {'a': 'r', 'b': 'g', 'c': 'm'}
ax = plt.gca()
xlbls = ax.get_xmajorticklabels()
for i in range(len(xlbls)):
xlbls[i].set_color(label_colors[xlbls[i].get_text()])
plt.show()
Not sure if it's possible to color part of an u-shape, however you can color it complete shapes with
something like
d = sc.dendrogram(Z, labels=l)
it = iter(map(label_colors.__getitem__, d['ivl'])[-2::-1])
def f(x):
return it.next()
d = sc.dendrogram(Z, labels=l, link_color_func=f)
ax = plt.gca()
xlbls = ax.get_xmajorticklabels()
for y in xlbls:
y.set_color(label_colors[y.get_text()])
In Python dendrogram you can not colour a half u-shape directly, but you can appoint colours to any node. This can be accomplished as below:
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as sc
dists = np.array([[0,2,1,4],[2,0,3,5],[1,3,0,6],[4,5,6,0],[4,7,6,2]])
Z = sc.linkage(dists, method='complete')
num = len(dists)
color = ["b"]*(2*num-1) # initialize color list with blue
# define the color of a specific node
color[5]="g"
color[6]="r"
color[7]="y"
d = sc.dendrogram(Z,link_color_func=lambda x: color[x])
# add labels for nodes
coord = np.c_[np.array(d['icoord'])[:,1:3],np.array(d['dcoord'])[:,1]]
coord = coord[np.argsort(coord[:,2])]
for posi in coord:
x = 0.5 * sum(posi[0:2])
y = posi[2]
plt.plot(x, y, 'ro')
plt.annotate("%2i" % num, (x, y), xytext=(0, -8),
textcoords='offset points',
va='top', ha='center')
num = num+1
plt.show()
#~ plt.savefig("test.png")

Categories