Highlight stack plot region with matplotlib - matplotlib

I would like to highlight a region of one stack in a stackplot, for example the region 4-5 on the x-axis for B only with another color or hashes:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
labels = ['A', 'B']
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, labels=labels)
ax.legend()

Manually added polygons. This can be both colored and hatched at the same time.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
labels = ['A', 'B']
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, labels=labels)
p = patches.Polygon(((4.0, 3.0),(5.0,4.0),(5.0,13.0),(4.0,9.0)), fc='g', hatch='x')
ax.add_patch(p)
ax.legend()

Related

in pyplot hist2D with customized colorbar mark bins outside colorbar range

I'm plotting a weighted 2D histogram with one value assigned to each bin. Here's a minimal example:
import matplotlib.pyplot as plotter
plot_field, axis_field = plotter.subplots()
x = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 0.5, 1.5, 2.5]
y = [0.5, 0.5, 0.5, 1.5, 1.5, 1.5, 2.5, 2.5, 2.5]
w = [2, 1, 0, 3, 0, 0, 1, 0, 3]
minimum = 1
bins = [[0, 1, 2, 3], [0, 1, 2, 3]]
histo = plotter.hist2d(x, y, bins=bins, weights=w)
plotter.colorbar(histo[3], extend='min')
plotter.clim(minimum, max(w))
plotter.show()
Restricting the range of the colorbar works fine. However, I want to the bins with weight below the minimum to be marked in some way. Either colored differently or indicated in some other way.
Is there a simple way to do this?
Thanks a lot!
You could create your own colormap for example:
import numpy as np
import matplotlib.pyplot as plotter
from matplotlib import cm
from matplotlib.colors import ListedColormap
plot_field, axis_field = plotter.subplots()
viridis = cm.get_cmap('viridis', 256)
newcolors = viridis(np.linspace(0, 1, 256))
pink = np.array([248/256, 24/256, 148/256, 1])
newcolors[0, :] = pink
newcmp = ListedColormap(newcolors)
x = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 0.5, 1.5, 2.5]
y = [0.5, 0.5, 0.5, 1.5, 1.5, 1.5, 2.5, 2.5, 2.5]
w = [2, 1, 0, 3, 0, 0, 1, 0, 3]
minimum = 1
bins = [[0, 1, 2, 3], [0, 1, 2, 3]]
_, _, _, mesh = plotter.hist2d(
x, y, bins=bins, weights=w, cmap=newcmp, vmin=minimum, vmax=max(w)
)
plotter.colorbar(mesh, extend='min')
plotter.show()

Interpolated heat map plot from discrete data points

I have a data set of discrete, sparse points (x, y, value). I'd like to plot the data so that every (x, y) coordinate is given a color based on interpolation between nearby data points.
data = np.array([
[0, 0, 18.75],
[0, 2, 0],
[0, 4, 16],
[0, 6, 2],
[-4, 2, 18],
[-4, 4, 35],
[-4, 6, 32],
[-4, 8, 15],
[-4, 10, 28],
[4, 0, 26],
[4, 2, 30],
[4, 4, 32],
[4, 6, 35],
[4, 8, 26.5],
])
I've tried using pcolormesh but it expects my C values are a 2D array. How can I achieve this?
I adapted an example of scipy.interpolate.griddata, with plt.contourf() as suggested by Matt Pitkin:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
x, y, vals = data[:,0], data[:,1], data[:,2]
X, Y = np.meshgrid(
np.linspace(np.min(x), np.max(x), 100),
np.linspace(np.min(y), np.max(y), 100)
)
interpolated_vals = griddata((x, y), vals, (X, Y), method='cubic')
plt.contourf(X, Y, interpolated_vals)
plt.show()
You could try using contourf and doing the following:
from matplotlib import pyplot as plt
# create mesh grid for x/y-data
grid = np.meshgrid(data[:,0], data[:,1])
# create 2D array of z-values
vals = np.zeros((len(data), len(data)))
for row in data:
vals[(grid[0] == row[0]) & (grid[1] == row[1])] = row[2]
# create contour plot
plt.contourf(data[:, 0], data[:, 1], vals)

matlibplot plotting lines based on a matrix

New to both matplotlib and numpy.
I have a matrix that represents an L shape:
import numpy as np
L = np.array([[1, 1, 1.5, 1.5, 2, 2], [2, 4, 4, 2.5, 2.5, 2]])
How do I plot this in matplotlib?
Let's try a little advanced indexing:
plt.plot(*L[:, range(-1,L.shape[1])])
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.show()
Or probably more naturally with Patch.Polygon:
from matplotlib.patches import Polygon
fig, ax = plt.subplots()
ax.add_patch(Polygon(L.T, facecolor='None', edgecolor='C0'))
ax.set_xlim(0,5)
ax.set_ylim(0,5)
plt.show()
Output:

numpy - add two arrays to get matrix

How do I find a matrix of all sums of two arrays?
With the input
x1 = np.array([0, 1])
x2 = np.array([1,2,3])
I want the output of this to be like this:
[[1, 2, 3], [2, 3, 4]]
You can use NumPy's newaxis attribute:
x1[:, np.newaxis] + x2
which is an acronym for None:
In [2]: np.newaxis is None
Out[2]: True
Thus:
x1[:, None] + x2
also works.
You can use list comprehension like this example:
x1 = np.array([0, 1])
x2 = np.array([1,2,3])
final = [[j+k for j in x2] for k in x1]
# Or, maybe:
# final = np.array([[j+k for j in x2] for k in x1])
# >>> array([[1, 2, 3], [2, 3, 4]])
print(final)
Output:
[[1, 2, 3], [2, 3, 4]]

How to change linestyle in matplotlib Step function?

x1 = [1, 2, 3, 4, 5, 6]
y1 = [6, 5, 4, 3, 2, 1]
fig = plt.figure()
ax = fig.add_subplot(211)
ax.step(x1, y1, alpha=0.8, linewidth=2, color="b", linestyle="--", label="test")
Why the linestyle parameter doesn't effect this plot? And how to make it work?
The documentation mentions "Additional keyword args to step() are the same as those for plot()." (doc)
Add 'dashes=(a,b)' to ax.plot:
import matplotlib.pyplot as plt
x1 = [1, 2, 3, 4, 5, 6]
y1 = [6, 5, 4, 3, 2, 1]
fig = plt.figure()
ax = fig.add_subplot(211)
ax.step(x1, y1, alpha=0.8, linewidth=2, color="b", linestyle="--", dashes=(4,2), label="test")
plt.show()
What version of matplotlib are you using?
This is a bug/interface issue (PR #1802) that was fixed in 1.3.0.
If you can not upgrade, see the work-around at
Linestyle in matplotlib step function.