Last modified: 12 December 2024

Adding a label to a plot


Matplotlib has a number of ways to add or change the labels on a plot. For this example we shall use a simple dataset

sherpa> load_arrays(1, [1, 5, 8], [20, 30, 25])
sherpa> plot_data()  

Figure 1: the original plot

[The plot contains two labels, one for each axis: "x" at the bottom and "y" at the left.]
[Print media version: The plot contains two labels, one for each axis: "x" at the bottom and "y" at the left.]

Figure 1: the original plot

After creating the plot, in this case with:

sherpa> plot_data()

then a number of Matlpotlib commands can be used. For example, the axis labels can be changed:

sherpa> plt.xlabel("The independent axis")
sherpa> plt.ylabel("The dependent axis")
sherpa> plt.title("The plot title")

To add a label we can use the plt.text command:

sherpa> plt.text(5, 20, "At 5,20 [data]")

The default is to use the data coordinate system of the plot, but alternative systems, such as the axes (0 to 1 covers the plot area) and figure (0 to 1 covers the full figure) can also be used:

sherpa> ax = plt.gca()
sherpa> plt.text(0.5, 0, "centered [axis]", c="orange", ha="center", transform=ax.transAxes)
sherpa> fig = plt.gcf()
sherpa> plt.text(1, 1, "top-right [fig]", c="g", ha="right", va="top", transform=fig.transFigure)

Figure 2: adding labels

[The plot now has an X axis label of "The independent axis", Y axius label of "The dependent axis", and a title of "The plot title" above the plot. Additional labels have been added: a green one in the top right labeleld "top-right [fig]", an orange one in the middle of the botton axis labelled "centered [axis]", and a black label "At 5,20 [data]" which starts at x=5 and y=20.]
[Print media version: The plot now has an X axis label of "The independent axis", Y axius label of "The dependent axis", and a title of "The plot title" above the plot. Additional labels have been added: a green one in the top right labeleld "top-right [fig]", an orange one in the middle of the botton axis labelled "centered [axis]", and a black label "At 5,20 [data]" which starts at x=5 and y=20.]

Figure 2: adding labels