Contour plot lines striking through inline labels - python

I'm making a contour plot with three arrays: xdata, ydata, and phi. I'd like the face-on axes to correspond to xdata and ydata, and make contours out of phi.
After looking through the matplotlib contour plot example page, I wrote:
X, Y = np.meshgrid(xdata, ydata)
Z1, Z2 = np.meshgrid(phi, phi)
plt.figure(figsize=(10,8))
plt.scatter(xdata, ydata, s=200, c='white', edgecolor='grey', zorder=2)
plt.xlabel("x (degrees)")
plt.ylabel("y (degrees)")
plt.title("Obscuration ellipse $\phi$ (radians)")
CS = plt.contour(X, Y, Z1, zorder=1)
plt.clabel(CS, inline=True, inline_spacing=3, rightside_up=True, fontsize=18)
plt.show()
Here, I'm using zorder to force the scatter points to show up on top of the contour.
On the plot I get, the contours strike through the inline labels:
Some of these inline labels also appear to be stacked on top of others, and in two cases the labels obscure scatter points, despite zorder assignment.
How do I fix my code such that the labels are not strikethrough (as is the case in matplotlib's example page) and zorder is preserved?

Related

Plotting Points on Matplotlib Colored Grid

I am working with the matplotlib library to generate colored graphs which need to have specific points overlayed on top of them. After messing around with matplotlib, I came up with a method to properly color my grid, however I am unable to plot points manually.
def generate_grid(x, y, data):
fig, ax = plt.subplots(1, 1, tight_layout=True)
my_cmap = matplotlib.colors.ListedColormap(['grey'])
my_cmap.set_bad(color='w', alpha=0)
for x in range(x + 1):
ax.axhline(x, lw=2, color='k', zorder=5)
for y in range(y+1):
ax.axvline(y, lw=2, color='k', zorder=5)
ax.imshow(data, interpolation='none', cmap=my_cmap,
extent=[0, y, 0, x], zorder=0)
plt.locator_params(axis="x", nbins=x+1)
plt.locator_params(axis="y", nbins=y+1)
locs, labels = plt.xticks()
labels = [int(item)+1 for item in locs]
plt.xticks(locs, labels)
locs, labels = plt.yticks()
z = len(locs)
labels = [z-int(item) for item in locs]
plt.yticks(locs, labels)
ax.xaxis.tick_top()
plt.show()
How would I go about plotting a point at any given location ie at (4,2) or (2,1)?
You may simply use the scatter method from within your generate_grid function, for instance, immediately before plt.show().
However, note that if you simply use ax.scatter(2,1, s=50) the symbol will end up under your grid.
You need to play with the zorder parameter to ensure that it appears over the grid. For instance ax.scatter(2,1, s=50, zorder=50) did the trick for me:

PyPlot Scatter Plot - Logarithmic Color Scale - How To Set Color Bar Label Format

I am making a scatter plot in matplotlib with logarithmic color scaling, which is working fine, see attached plot. My problem is, I would like to have the x-tick labels on the r.h.s. of the color bar to be in float format, rather than scientific notation. Interestingly, this works only for some of the labels.
I have my data x, y for the scatter plot and the weights which specify the colors.
This is my code:
fig = plt.figure(dpi=200)
# Plot data, this is the relevant part:
sc = plt.scatter(x, y, c=weights, cmap='rainbow', s=20, alpha=0.5,
norm=mpl.colors.LogNorm(vmin=0.3, vmax=3))
cbar = fig.colorbar(sc, format='%.1f', label='$T_{IDL} / T_{Py}$') # format arg. supposed to do what I want
print(cbar.get_ticks()) # For debugging
# Plot dashed line:
xmin, xmax = plt.gca().get_xlim()
const = np.linspace(xmin, xmax, 500)
plt.plot(const, const, linestyle='--', color='black', alpha=0.3)
# Add titles and axis labels:
fig.suptitle(suptitle)
plt.title(f'{len(amp_py_cmn)} Common Flares -- Duration Ratio: Mean {np.mean(dur_ratio):.2f},'
f' St.Dev. {np.std(dur_ratio):.2f}',
fontsize=7)
plt.xlabel('$A_{Py}$')
plt.ylabel('$A_{IDL}$')
# Save figure and show:
fig.savefig(f'{savePath}/{suptitle}.pdf')
plt.show()
This is the resulting Plot:
Scatter Plot
I added the call of cbar.get_ticks() while debugging, and interestingly the output gives
[1.]
which corresponds to the only label that looks according to my wishes. So the question is, where do the other labels come from, and how can I format them?
Thanks!

Animating points in a matplotlib scatter plot

So I have a bunch of 3D data relating to a shoulder (x3, y3, z3), an elbow(x2, y2, z2), and a wrist(x1, y1, z1). What i'd like to achieve is an animation which replicates the motion of the arm in a plot using matplotlib. Essentially, all I need to do is remove a set of three points on a 3D scatter plot and replace them on the same plot with the next set after a very short delay. I can't seem to find any questions which have covered this type of animation. Any help would be greatly appreciated. Current code below gives me the first set of points and that is all:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range(len(x1)):
wrist = ax.scatter(x1.pop(), y1.pop(), z1.pop(), s=20)
elbow = ax.scatter(x2.pop(), y2.pop(), z2.pop(), s=20)
shoulder = ax.scatter(x3.pop(), y3.pop(), z3.pop(), s=20)
plt.show()
time.sleep(0.01)
wrist.remove()
elbow.remove()
shoulder.remove()

How to plot individual points without curve in python?

I want to plot individual data points with error bars on a plot, but I don't want to have the curve. How can I do this? Are there some 'invisible' line style or can I set the line style colourless (but the marker still has to be visible)?
So this is the graph I have right now:
plt.errorbar(x5,y5,yerr=error5, fmt='o')
plt.errorbar(x3,y3,yerr=error3, fmt='o')
plt.plot(x3_true,y3_true, 'r--', label=(r'$\lambda = 0.3$'))
plot(x5_true, y5_true, 'b--', label=(r'$\lambda = 0.5$'))
plt.plot(x5,y5, linestyle=':', marker='o', color='red') #this is the 'ideal' curve that I want to add
plt.plot(x3,y3, linestyle=':', marker='o', color='red')
I want to keep the two dashed curve but I don't want the two dotted curve. How can I do this? And how can I change the color of the markers so I can have red points for the red curve, blue points for the blue curve?
You can use scatter:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x)
plt.scatter(x, y)
plt.show()
Alternatively:
plt.plot(x, y, 's')
EDIT: If you want error bars you can do:
plt.errorbar(x, y, yerr=err, fmt='o')

Matplotlib - Set background colour of specific quadrants

In Jfreechart there is a method called setQuadrantPaint which let's you set the background colour of a given quandrant in a plot.
How would you achieve the equivalent in matplotlib?
E.g.
You can plot a 2x2 array with imshow in the background. Giving it an extent will make the center of it always at 0,0.
import numpy as np
import matplotlib.pyplot as plt
x1, y1 = np.random.randint(-8,8,5), np.random.randint(-8,8,5)
x2, y2 = np.random.randint(-8,8,5), np.random.randint(-8,8,5)
vmax = np.abs(np.concatenate([x1,x2,y1,y2])).max() + 5
extent = [vmax*-1,vmax, vmax*-1,vmax]
arr = np.array([[1,0],[0,1]])
fig, ax = plt.subplots(1,1)
ax.scatter(x1,y1, marker='s', s=30, c='r', edgecolors='red', lw=1)
ax.scatter(x2,y2, marker='s', s=30, c='none', edgecolors='red', lw=1)
ax.autoscale(False)
ax.imshow(arr, extent=extent, cmap=plt.cm.Greys, interpolation='none', alpha=.1)
ax.axhline(0, color='grey')
ax.grid(True)
Setting the autoscale to False after the data points are plotted, but before the image is, makes sure that the axes scales only to the data points.

Categories