I've been reading about multiple lines plotting and multicolored lines, but every time I read a post about it people use continuous set of data, like some trigonometrical function:
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
So, here is my problem: I'm making a plotting script for 1D finite element problems like the image attached. I'm plotting the elements as individual lines with the X and Y coordinates array, and I would like to color the lines based on a third array like the axial stress or temperature, or any other
The problem is when I try to follow the examples I've found, every line has local color distribution, instead of a global distribution. I'm thinking about defining a global color scale based on the maximum and mininum values of the third array, let's say temperature, and passing the coordinates of each element + the current average temperature may do the job, but I don't know if something alike is possible
Anyone can help?
You can map values to a particular colormap, and plot each element as a single line with a particular color, like this:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
import numpy as np
# roto-translation matrix
T = lambda t, u, v: np.array([[np.cos(t), -np.sin(t), u], [np.sin(t), np.cos(t), 0], [0, 0, 1]])
# coordinates of a triangle
triangle = np.array([[-0.5, -0.5, 1], [0.5, -0.5, 1], [-0.5, 0.5, 1], [-0.5, -0.5, 1]]).T
n_elements = 10
values = np.linspace(-5, 5, n_elements)
# create a normalizer
norm = Normalize(vmin=values.min(), vmax=values.max())
# normalize values
norm_values = norm(values)
# choose a colormap
cmap = cm.magma
# create colors
colors = cmap(norm_values)
# map values to a colorbar
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
mappable.set_array(values)
f, ax = plt.subplots(1)
ax.set_aspect("equal")
for i in range(n_elements):
tr = np.matmul(T(i * np.pi, int(i / 2), 0), triangle)
ax.plot(tr[0, :], tr[1, :], color=colors[i])
cb = f.colorbar(mappable)
cb.set_label("Value")
I want to plot (filled) polygons that are given by a sequence of points that define the boundary in 3d. Unfortunately these polygons intersect eachother.
Here is a minimal example that shows two squares that intersect, with the issue that they are not plotted correctly. In my actual application these polygons are generated on the fly, so it is also not possible to manually define a triangulation of the polygon. I'm aware that with Poly3DCollection, there is no chance of doing this correctly as the polygons will only be filled after the projection.
Can anyone recommend another method that allows drawing polygons in 3d with correct intersections?
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
verts1 = np.array([
[0, 0, 0.5],
[1, 0, 0.5],
[1, 1, 0.5],
[0, 1, 0.5]
])
verts2 = verts1[:, [1, 2, 0]]
verts = [verts1, verts2]
ax.add_collection3d(p3c := Poly3DCollection(verts))
p3c.set_facecolor([(1, 0, 0), (0, 1, 0)])
plt.show()
I'd like to emulate the blueish background lines from the given image. Can someone tell me how to do so using Matplotlib?
Basically, it's a less complicated version of this.
Here is an approach using a stretched 1D image to draw the bands. The image gets an extent to fill the complete width and the desired height. The vmax for the color mapping is set a bit higher to avoid too light colors, which would be too similar to the white background.
import matplotlib.pyplot as plt
import numpy as np
# create some test data
N = 40
x = np.linspace(-3, 3, N)
values = np.random.normal(0, 2, N)
error_bands = np.array([2, 1, 0, 0, 1, 2])
plt.imshow(error_bands.reshape(-1, 1), extent=[-10, 10, -3, 3], origin='lower',
cmap='Blues_r', vmin=error_bands.min(), vmax=error_bands.max() * 1.4, alpha=0.3)
plt.axhline(0, color='blueviolet', lw=3) # horizontal line at x=0
plt.bar(x, values, width=(x[1] - x[0]) * 0.8, bottom=0, color='blueviolet')
plt.gca().set_aspect('auto') # removed the fixed aspect ratio forced by imshow
plt.xlim(x[0] - 0.3, x[-1] + 0.3) # explicitly set the xlims, shorter than the extent of imshow
plt.show()
PS: A simpler approach, replacing imshow with some calls to axhspan drawing horizontal bars over eachother, using a small alpha:
for i in range(1, 4):
plt.axhspan(-i, i, color='b', alpha=0.1)
I am attempting to use http://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_iris.html for my own data to construct a 3D PCA plot. The tutorial, however, did not specify how I can add a legend. Another page, https://matplotlib.org/users/legend_guide.html did, but I cannot see how I can apply the information in the second tutorial to the first.
How can I modify the code below to add a legend?
# Code source: Gae"l Varoquaux
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import decomposition
from sklearn import datasets
np.random.seed(5)
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data#the floating point values
y = iris.target#unsigned integers specifying group
fig = plt.figure(1, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
plt.cla()
pca = decomposition.PCA(n_components=3)
pca.fit(X)
X = pca.transform(X)
for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]:
ax.text3D(X[y == label, 0].mean(),
X[y == label, 1].mean() + 1.5,
X[y == label, 2].mean(), name,
horizontalalignment='center',
bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))
# Reorder the labels to have colors matching the cluster results
y = np.choose(y, [1, 2, 0]).astype(np.float)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral,
edgecolor='k')
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
plt.show()
There are some issues with the other answer on which neither the OP, nor the answerer seem to be clear about; this is hence not a complete answer, but rather an appendix to the existing answer.
The spectral colormap has been removed from matplotlib in version 2.2,
use Spectral or nipy_spectral or any other valid colormap.
Any colormap in matplotlib ranges from 0 to 1. If you call it with any value outside that range,
it will just give your the outmost color. To get a color from a colormap you hence need to normalize the values.
This is done via a Normalize instance. In this case this is internal to scatter.
Hence use sc = ax.scatter(...) and then sc.cmap(sc.norm(value)) to get a value according to the same mapping that is used within the scatter.
Therefore the code should rather use
[sc.cmap(sc.norm(i)) for i in [1, 2, 0]]
The legend is outside the figure. The figure is 4 x 3 inches in size (figsize=(4, 3)).
The axes takes 95% of that space in width (rect=[0, 0, .95, 1]).
The call to legend places the legend's right center point at 1.7 times the axes width = 4*0.95*1.7 = 6.46 inches. (bbox_to_anchor=(1.7,0.5)).
Alternative suggestion from my side: Make the figure larger (figsize=(5.5, 3)), such that the legend will fit in, make the axes take only 70% of the figure width, such that you have 30% left for the legend. Position the legend's left side close to the axes boundary (bbox_to_anchor=(1.0, .5)).
For more on this topic see How to put the legend out of the plot.
The reason you still see the complete figure including the legend in a jupyter notebook is that jupyter will just save everything inside the canvas, even if it overlaps and thereby enlarge the figure.
In total the code may then look like
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np; np.random.seed(5)
from sklearn import decomposition, datasets
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data #the floating point values
y = iris.target #unsigned integers specifying group
fig = plt.figure(figsize=(5.5, 3))
ax = Axes3D(fig, rect=[0, 0, .7, 1], elev=48, azim=134)
pca = decomposition.PCA(n_components=3)
pca.fit(X)
X = pca.transform(X)
labelTups = [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]
for name, label in labelTups:
ax.text3D(X[y == label, 0].mean(),
X[y == label, 1].mean() + 1.5,
X[y == label, 2].mean(), name,
horizontalalignment='center',
bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))
# Reorder the labels to have colors matching the cluster results
y = np.choose(y, [1, 2, 0]).astype(np.float)
sc = ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap="Spectral", edgecolor='k')
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
colors = [sc.cmap(sc.norm(i)) for i in [1, 2, 0]]
custom_lines = [plt.Line2D([],[], ls="", marker='.',
mec='k', mfc=c, mew=.1, ms=20) for c in colors]
ax.legend(custom_lines, [lt[0] for lt in labelTups],
loc='center left', bbox_to_anchor=(1.0, .5))
plt.show()
and produce
Needed a few tweaks (plt.cm.spectral is the danged weirdest colormap I've ever dealt with), but it seems to be good now:
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from sklearn import decomposition
from sklearn import datasets
np.random.seed(5)
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data#the floating point values
y = iris.target#unsigned integers specifying group
fig = plt.figure(1, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
plt.cla()
pca = decomposition.PCA(n_components=3)
pca.fit(X)
X = pca.transform(X)
labelTups = [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]
for name, label in labelTups:
ax.text3D(X[y == label, 0].mean(),
X[y == label, 1].mean() + 1.5,
X[y == label, 2].mean(), name,
horizontalalignment='center',
bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))
# Reorder the labels to have colors matching the cluster results
y = np.choose(y, [1, 2, 0]).astype(np.float)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral, edgecolor='k')
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
colors = [plt.cm.spectral(np.float(i/2)) for i in [1, 2, 0]]
custom_lines = [Line2D([0], [0], linestyle="none", marker='.', markeredgecolor='k', markerfacecolor=c, markeredgewidth=.1, markersize=20) for c in colors]
ax.legend(custom_lines, [lt[0] for lt in labelTups], loc='right', bbox_to_anchor=(1.7, .5))
plt.show()
Here's a link to an online Jupyter notebook with a live version of the script (requires an account for rerunning, though).
Short explanation
You're trying to add three legend markers for a single plot, which is nonstandard behavior. Thus, you need to manually create the shapes that your legend will display.
Longer explanation
This line of code recreates the colors you used in your plot:
colors = [plt.cm.spectral(np.float(i/2)) for i in [1, 2, 0]]
and then this line of code draws some appropriate-looking dots that we'll eventually display on your legend:
custom_lines = [Line2D([0], [0], linestyle="none", marker='.', markeredgecolor='k', markerfacecolor=c, markeredgewidth=.1, markersize=20) for c in colors]
The first two args are just the (internal) x and y coords of the single dot that will be drawn, linestyle="none" suppresses the line that Line2D would normally draw by default, and the rest of the args create and style the dot itself (referred to as a marker in the terminology of the matplotlib api).
Finally, this statement actually creates the legend:
ax.legend(custom_lines, [lt[0] for lt in labelTups], loc='right', bbox_to_anchor=(1.7, .5))
The first arg is of course a list of the dots we just drew, and the second arg is a list of the labels (one per dot). The remaining two args tell matplotlib where to draw the actual box containing the legend. The last arg, bbox_to_anchor, is basically a way to manually fiddle with the positioning of the legend, which I had to do since matplotlib support for 3D anything is still a little behind the curve. On 2D plots you typically don't need it, and, since matplotlib usually does a decent job of automatically positioning the legend on 2D plots in the first place, you often don't even need the loc arg either.
Some colormap weirdness
Don't quite know what was going on with plt.cm.spectral, but in order to get it to behave, for every value I fed it I had to:
a) first cast the value to float
b) then divide the value by 2
a) does occur explicitly in the OP's original code, right before they plot. The divide by 2 thing, I don't know where that comes from. Somehow the call to ax.scatter is implicitly normalizing all of the y values so that the maximum is 1? I guess?
This question already has an answer here:
How to draw the union shape of rectangles in python
(1 answer)
Closed 7 years ago.
I am trying to plot the union of a couple of polygons in matplotlib, with a certain level of alpha. My current code below has a darker color at the intersections. Would there be anyway to make the intersections the same color with other places?
import matplotlib.pyplot as plt
fig, axs = plt.subplots()
axs.fill([0, 0, 1, 1], [0, 1, 1, 0], alpha=.25, fc='r', ec='none')
axs.fill([0.5, 0.5, 1.5, 1.5], [0.5, 1.5, 1.5, 0.5], alpha=.25, fc='r', ec='none')
As #unutbu and #Martin Valgur's comments indicate, I think shapely is the way to go. This question may be somewhat redundant with an earlier one, but here is a clean code snippet that should do what you need.
The strategy is to first create the union of your various shapes (rectangles) and then plot the union. That way you have 'flattened' your various shapes into a single one, so you don't have the alpha problem in overlapping regions.
import shapely.geometry as sg
import shapely.ops as so
import matplotlib.pyplot as plt
#constructing the first rect as a polygon
r1 = sg.Polygon([(0,0),(0,1),(1,1),(1,0),(0,0)])
#a shortcut for constructing a rectangular polygon
r2 = sg.box(0.5,0.5,1.5,1.5)
#cascaded union can work on a list of shapes
new_shape = so.cascaded_union([r1,r2])
#exterior coordinates split into two arrays, xs and ys
# which is how matplotlib will need for plotting
xs, ys = new_shape.exterior.xy
#plot it
fig, axs = plt.subplots()
axs.fill(xs, ys, alpha=0.5, fc='r', ec='none')
plt.show() #if not interactive