matlibplot plotting lines based on a matrix - numpy

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:

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)

Highlight stack plot region with 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()

How to set the color in matplotlib 3d axis ax.plot_surface()?

How can I set the colors in a 3d surface plot? By default, the Z value is used to create a color, but that is encoding the same information twice and therefore redundant. I would like to embed some other information in the color dimension.
%matplotlib notebook
import seaborn as sns
sns.set_context('paper')
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure(figsize=(8,8), dpi=300)
ax = fig.gca(projection='3d')
# Make data.
X = peaks2d.index
Y = peaks2d.columns
X, Y = np.meshgrid(X, Y)
Z = peaks2d.fillna(0).values.T
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
xlabel('Retention Time')
ylabel('m/z')
title('Peak Selection')
I tried to use color=(Z==0).astype(int) but that did not work. It returned
ValueError: Invalid RGBA argument: array([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]])
If a colormap is defined the function should be able to map integers to a color, but apparently this is not implemented?

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.