let's think i have four features in a dataset and plotting scatter plots using two features each time.I want to provide label to each plot separately.
fig,axes=plt.subplots(ncols=2,figsize=(10,8))
axes[0].scatter(x1,x2],marker="o",color="r")
axes[1].scatter(x3,x4,marker="x",color="k")
axes[0].set(xlabel="Exam score-1",ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1",ylabel="Exam score-2")
axes[0].set_label("Admitted")
axes[1].set_label("Not-Admitted")
axes.legend()
plt.show()
Here I will get two scatter plots but labels are not shown. I want to see admitted as label for first plot and not-admitted for second scatter plot.
I am able to give label by using plt.legend()
but not getting already created plots.
You are setting the label for the axes, not the scatters.
The most convenient way to get a legend entry for a plot is to use the label
argument.
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.rand(2,23)
fig,axes=plt.subplots(ncols=2)
axes[0].scatter(x,y, marker="o", color="r", label="Admitted")
axes[1].scatter(x,y, marker="x", color="k", label="Not-Admitted")
axes[0].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[0].legend()
axes[1].legend()
plt.show()
If you want to set the label after creating the scatter, but before creating the legend, you may use set_label
on the PathCollection
returned by the scatter
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.rand(2,23)
fig,axes=plt.subplots(ncols=2)
sc1 = axes[0].scatter(x,y, marker="o", color="r")
sc2 = axes[1].scatter(x,y, marker="x", color="k")
axes[0].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1", ylabel="Exam score-2")
sc1.set_label("Admitted")
sc2.set_label("Not-Admitted")
axes[0].legend()
axes[1].legend()
plt.show()
Finally you may set the labels within the legend call:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.rand(2,23)
fig,axes=plt.subplots(ncols=2)
sc1 = axes[0].scatter(x,y, marker="o", color="r")
sc2 = axes[1].scatter(x,y, marker="x", color="k")
axes[0].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[1].set(xlabel="Exam score-1", ylabel="Exam score-2")
axes[0].legend([sc1], ["Admitted"])
axes[1].legend([sc2], ["Not-Admitted"])
plt.show()
In all three cases, the result will look like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With