How to change linestyle in matplotlib Step function? - matplotlib

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.

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:

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()

Font type in Matplotlib

I am pretty new to Matplotlib, I have been wading through their very nice webpage, and managed to generate something very similar to what I wanted. I am including the code to the plot I want, the only issue I can't fix is to get the xlabel, ylabel and legend also in bold.
Any suggestions would be very welcome,
many thanks
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy as np
from matplotlib.font_manager import FontProperties
from pylab import *
font = FontProperties()
font = {'family' : 'serif',
'weight' : 'bold',
'size' : 12,
}
fig = plt.figure(figsize=(6, 8))
matplotlib.rc('font', **font)
ax = host_subplot(211, axes_class=AA.Axes)
X=[0.061, 0.12, 0.17, 0.23, 0.29, 0.34, 0.4, 0.46, 0.51]
Y=[3.2, 4, 5.6, 7.4, 11.2, 18.6, 28.9, 42.5, 55.9]
Z=[3.2, 4.1, 5.7, 7.6, 11.3, 18.5, 27, 35.6, 46.9]
A=[3.2, 4, 5.6, 7.6, 11.3, 19.2, 30.4, 44.6, 57.7]
B=[3.2, 3.5, 4.8, 6.5, 10.4, 19.7, 32.9, 53.8, 84.2]
C=[3.1, 3.8, 5.6, 8, 13, 26.1, 41.1, 64.3, 103.7]
ax.plot(X, Y, color="red", linewidth=2.5, marker="v", markersize=7)
ax.plot(X, Z, color="orange", linewidth=2.5, marker="p", markersize=7)
ax.plot(X, A, color="yellow", linewidth=2.5, marker="s", markersize=7)
ax.plot(X, B, color="#33CC33", linewidth=2.5, marker="h", markersize=7)
ax.plot(X, C, color="green", linewidth=2.5, marker="D", markersize=7)
ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.set_xticks([0.061, 0.12, 0.17, 0.23, 0.29, 0.34, 0.4, 0.46, 0.51])
ax2.set_xticklabels(["4", "3","2.4", "2", "1.9", "1.7", "1.6", "1.5", "1.4$\AA$"])
ax2.axis["right"].major_ticklabels.set_visible(False)
ax.set_xlim(0.05, 0.52)
ax.set_ylim(0, 109)
plt.xlabel('1/d$^2$', fontsize=14, fontweight='bold')
plt.ylabel('R$_{meas}$')
plt.legend(("0.05deg/0.05s", "SUM20", "SUM40", "SUM80", "SUM160"))
fontsize=12, fancybox=True, shadow=True)
ax = host_subplot(212, axes_class=AA.Axes)
X=[0.061, 0.12, 0.17, 0.23, 0.29, 0.34, 0.4, 0.46, 0.51]
Y=[65, 62, 46, 35, 23, 13, 8, 4, 2]
Z=[65, 62, 47, 35, 23, 14, 9, 5, 3]
A=[66, 62, 47, 35, 23, 13, 8, 4, 2]
B=[71, 66, 48, 36, 23, 13, 8, 4, 2]
C=[70, 65, 48, 36, 23, 13, 8, 4, 2]
ax.plot(X, Y, color="red", linewidth=2.5, marker="v", markersize=7)
ax.plot(X, Z, color="orange", linewidth=2.5, marker="p", markersize=7)
ax.plot(X, A, color="yellow", linewidth=2.5, marker="s", markersize=7)
ax.plot(X, B, color="#33CC33", linewidth=2.5, marker="h", markersize=7)
ax.plot(X, C, color="green", linewidth=2.5, marker="D", markersize=7)
ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.set_xticks([0.061, 0.12, 0.17, 0.23, 0.29, 0.34, 0.4, 0.46, 0.51])
ax2.set_xticklabels(["4", "3","2.4", "2", "1.9", "1.7", "1.6", "1.5", "1.4$\AA$"])
ax2.axis["right"].major_ticklabels.set_visible(False)
ax.set_xlim(0.05, 0.52)
fig.subplots_adjust(hspace=0.3)
plt.xlabel('1/d$^2$', fontweight='bold')
plt.ylabel('I/sigma', fontdict=font)
plt.legend(("0.05deg/0.05s", "SUM20", "SUM40", "SUM80", "SUM160"))
plt.show()
Text objects have a weight property: http://matplotlib.org/users/text_props.html
plt.xlabel('This is my label', weight='bold')
plt.title('This is my title', weight='bold')