Scatter plot labels in one line - Matplotlib - python

It's possible to set all labels at once in Matplolib?
For example, I have this piece of code to plot a scatter plot:
cmap = plt.get_cmap('Set1')
colors = [cmap(i) for i in numpy.linspace(0, 1, simulations+1)]
plt.figure(figsize=(7, 7))
plt.scatter(coords[:, 0], coords[:, 1], marker='o', c=colors, s=50, edgecolor='None')
plt.legend(loc='lower left',)
where simulations = 7 and coords is a numpy.array with shape (7, 2).
This gives me a plot like that:
If I change the last line for:
plt.scatter(coords[:, 0], coords[:, 1], marker='o', c=colors, s=50, edgecolor='None', label=range(simulations))
plt.legend(loc='lower left')
I get:
I'm wondering if I'll have to do a loop to do the scatter and set each label of if there is some way to do all at once.
Thank you.

I'm not sure how to do it with a scatter plot. But I'm not sure if there is an advantage to use scatter rather than plot if you want different labels.
How about this?
import numpy as np
import matplotlib.pyplot as plt
n = 10
coords = np.random.random((n,2))
cmap = plt.get_cmap('Set1')
for i, (x, y) in enumerate(coords):
plt.plot(x, y, 'o', color=cmap(i/float(n)), label='%i'%i, ms=9, mec='none')
plt.axis((-0.5, 1.5, -0.5, 1.5))
plt.legend(loc='lower left', numpoints=1, frameon=False)
plt.show()

Related

Python subplot of tricontourf

I would like to do subplots of tricontourf. I tried this but it does not work, I obtain the error message: RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).
fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
fig = plt.figure()
# background_field
levels=np.linspace(0,max(max_ls, lc),5)
levels=np.r_[levels,[lc_smooth_min]]
levels=np.sort(levels)
print(levels)
ax1.tricontourf(X, Y, background_field(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")
# echelle_kolmogorov
ax2.tricontourf(X, Y, echelle_1(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")
# echelle_HTLES
ax3.tricontourf(X, Y, echelle_2(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Is it possible to perform subplots of tricontourf without using imshow?
Can someone explain me how should I do it?
Thanks a lot !

Position label of colorbar

I have this function:
def scatter_diagdistance(x, y) :
z = abs(y-x)
fig, ax = plt.subplots(dpi=200)
sc = ax.scatter(x, y, c=z, s=50, edgecolor='none')
x_diag = np.arange(min(x*100), max(x*100))/100
ax.plot(x_diag, x_diag, '-', c="red")
cbar = fig.colorbar(sc)
cbar.set_label('Distance from diagonal')
return(fig)
Which gives me this sort of image:
How can I position the "Distance from diagonal" to the left of the colorbar?
(Also, is there a cleaner way to plot the diagonal over a scatter plot like this?)
one way to do it is to use the text as the label for the secondary y-axis. That will keep the text before the colorbar. Also, you can draw a line for the diagonal. The code (without your data) is shown below. If you use transform=ax.transAxes details, the coordinates are interpreted as axes coordinates
fig, ax = plt.subplots(dpi=200)
ax2 = ax.twinx() ##Create secondary axis
ax2.set_yticks([]) ##No ticks for the secondary axis
sc = ax.scatter(0.5, 0.5, c=1, s=50, edgecolor='none')
ax2.set_ylabel('Distance from diagonal') ##Label for secondary axis
ax.plot([0, 1], [0, 1], '-', c="red", transform=ax.transAxes) #Line from 0 to 1
cbar = fig.colorbar(sc)
Plot

Matplotlib - create a scatter plot with points that fill the available space

I can create a scatter plot as follows:
fig, ax = plt.subplots()
x1 = [1, 1, 2]
y1 = [1, 2, 1]
x2 = [2]
y2 = [2]
ax.scatter(x1, y1, color="red", s=500)
ax.scatter(x2, y2, color="blue", s=500)
which gives
What I would like is something like the following (apologies for poor paint work):
I am plotting data that is all integer values, so they're all on a grid. I would like to be able to control the size of the scatter marker so that I could have white space around the points, or I could make the points large enough such that there would be no white space around them (as I have done in the above paint image).
Note - ideally the solution will be in pure matplotlib, using the OOP interface as they suggest in the documentation.
import matplotlib.pyplot as plt
import matplotlib as mpl
# X and Y coordinates for red circles
red_xs = [1,2,3,4,1,2,3,4,1,2,1,2]
red_ys = [1,1,1,1,2,2,2,2,3,3,4,4]
# X and Y coordinates for blue circles
blu_xs = [3,4,3,4]
blu_ys = [3,3,4,4]
# Plot with a small markersize
markersize = 5
fig, ax = plt.subplots(figsize=(3,3))
ax.plot(red_xs, red_ys, marker="o", color="r", linestyle="", markersize=markersize)
ax.plot(blu_xs, blu_ys, marker="o", color="b", linestyle="", markersize=markersize)
plt.show()
# Plot with a large markersize
markersize = 50
fig, ax = plt.subplots(figsize=(3,3))
ax.plot(red_xs, red_ys, marker="o", color="r", linestyle="", markersize=markersize)
ax.plot(blu_xs, blu_ys, marker="o", color="b", linestyle="", markersize=markersize)
plt.show()
# Plot with using patches and radius
r = 0.5
fig, ax = plt.subplots(figsize=(3,3))
for x, y in zip(red_xs, red_ys):
ax.add_patch(mpl.patches.Circle((x,y), radius=r, color="r"))
for x, y in zip(blu_xs, blu_ys):
ax.add_patch(mpl.patches.Circle((x,y), radius=r, color="b"))
ax.autoscale()
plt.show()

Histogram show values of vertical lines in legends

Can I show the values of vertical lines(dashed) in legends or annotate it somewhere, how?
Here is the code for dashed line
plt.hist(df['wt_avg_delay'], bins=50, color='lightblue', edgecolor='black')
plt.axvline(df['wt_avg_delay'].mean(), color='orange', linestyle='dashed', linewidth=1)
plt.axvline(-19, color='green', linestyle='dashed', linewidth=1)
plt.axvline(27 color='red', linestyle='dashed', linewidth=1)
The easiest way to annotate is probably by using plt.text():
plt.text(x, y, 'annotation')
Alternatively you can just add a label to the lines:
import matplotlib.pyplot as plt
x = [1, 1, 1, 2, 2, 3]
p = 2.5
plt.hist(x, label='data')
plt.axvline(p, color='g', label=str(p))
plt.legend()
plt.show()

Matplotlib help: Formatting a scatter plot to be square

I have a scatter plot where the axis are both limited at -100 and 100. However, when I graph the data, I always get an unappealing looking plot that is rectangular with incorrect axis labels. I'd like the plot to be a square with -100 and 100 as the last axis labels. Does anyone have advice for fixing this formatting issue?
My code is as follows:
import scipy.stats
import numpy as np
r = scipy.stats.pearsonr(x_val, y_val)
fig, ax = matplotlib.pyplot.subplots()
ax.scatter(x_val, y_val, s=75, color='green', edgecolor='black', linewidth = 2, alpha=0.4)
ax.set_axisbelow(True)
matplotlib.pyplot.axvline(0, c='#262626', linewidth=1.5, alpha=0.9)
matplotlib.pyplot.axhline(0, c='#262626', linewidth=1.5, alpha=0.9)
matplotlib.pyplot.grid(linewidth=1, color='#bfbfbf')
matplotlib.pyplot.xticks(np.arange(-100, 100, 20.0),fontsize=14, fontweight='bold',
fontname='Helvetica')
matplotlib.pyplot.yticks(np.arange(-100, 100, 20.0),fontsize=14, fontweight='bold',
fontname='Helvetica')
matplotlib.pyplot.text(-95, 85,'Pearson\'s r: %.3f'%r[0], fontsize=14, fontweight='bold',
fontname='Helvetica')
matplotlib.pyplot.show()

Categories