Search code examples
plotstatisticslabelgnuplotmedian

gnuplot - adding label for the median to the right-hand side of the diagram


I'm using gnuplot's STATS to plot a median to some data.

On the right-hand side of the graph, where the median intersects the diagram's border, I should like to place a label stating the median's value - or its percentage of a pre-determined maximum.

How do I best achieve that?


Solution

  • You can use a label. The syntax is

    set label id "text" at x-coordinate,y-coordinate
    

    where the id is optional (but useful if you need to change the label or remove it later). See help label for all of the options (including alignment and font options).

    Note also that gnuplot has several coordinate systems. See help coordinates for information about these.

    To place a label with the median on the right side at y-coordinate 10 (for example), you can use a command like:

    set label 1 sprintf("%f",STATS_median) at graph 1, first 10
    

    where we use sprintf to turn our numerical value into a string for the label. We specify the graph coordinate system for the x-coordinate. This system runs from 0 (left) to 1 (right) and similarly for the y-values from top to bottom. It is useful for when we need to address relative positions without knowing exact coordinates. We specify the first coordinate system for the y-coordinate. This system corresponds to the system used the by x1 and y1 axes.

    Note that when placing a label outside the graph (which we have done here), it is sometimes necessary to increase margins. See help margins for full details. A command like set rmargin 15 will give enough space for a 15 character string on the right.

    For an example, suppose that we have data that looks like

    8
    9
    15
    3
    6
    

    Then we can plot this, drawing a line at the median and labeling it with

    stats datafile nooutput
    set arrow 1 from graph 0, first STATS_median to graph 1, first STATS_median nohead
    set label 1 sprintf("%0.2f",STATS_median) at graph 1, first STATS_median offset char 1,0
    set rmargin 5
    plot datafile w points pt 7
    

    This produces the following

    enter image description here

    Note that we specified an offset on the label in the character coordinate system, which allows us to move it one character width to the right.


    In this example, an alternative could have been achieved by using the y2 axis and specifying the tic marks literally with

    set link y
    set y2tics ("%0.2f" STATS_median)
    plot datafile w points pt 7
    

    The advantage here is that the margin is automatically computed. This is not possible, however, when you need the label elsewhere.