Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set label for each subplot in a plot in matplotlib?

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

enter image description here

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.

like image 660
ramakrishnareddy Avatar asked Aug 28 '18 11:08

ramakrishnareddy


1 Answers

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:

enter image description here

like image 158
ImportanceOfBeingErnest Avatar answered Sep 24 '22 17:09

ImportanceOfBeingErnest