Label lines in a plot

前端 未结 4 1186
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 09:00

I am plotting two lines using

plot(x, y, type = \"l\", color = \"red\")

and

points(x2, y2, type = \"l\", color = \"blue\")         


        
4条回答
  •  半阙折子戏
    2020-12-28 09:38

    locator() is an interactive method of obtaining coordinates by clicking on an existing graph.

    Here are instructions on how to use locator() to find the right coordinates for a label on a graph.

    Step 1: Plot a graph:

    plot(1:100)
    

    Step 2: Type the following into the console:

    coords <- locator()
    

    Step 3: Click once on the plot, then click Stop .. Stop Locator at the top left of the plot (this returns control back to the R console).

    Step 4: Find the returned coordinates:

    coords
    $x
    [1] 30.26407
    $y
    [1] 81.66773
    

    Step 5: Now, you can add a label to the existing plot using these coordinates:

    text(x=30.26407, y=81.66773,label="This label appears where I clicked")
    

    or

    text(x=coords$x, y=coords$y,label="This label appears where I clicked")
    

    Here is the result:

    enter image description here

    You'll notice that the label appears with its center where you clicked. Its better if the label appears with its first character where you clicked. To find the correct parameter, see the help for text, and add the parameter pos=4:

    text(x=30,y=80,pos=4,label = "hello")
    

    Notes:

    • The label appears in the same x,y coordinates as dots on the graph. So, x=100,y=0 would appear on the lower right, while x=0,y=100 would appear on the upper left.
    • Can also use legend() to plot a label (this draws a box around the label which often looks nicer).
    • See How to change font family in a legend in an R-plot? for how to change the font in a legend, and how to auto-place the legend on the top right of the graph.
    • I would recommend becoming familiar with ggplot2 instead of plot, as ggplot2 is the gold standard for producing graphs.

提交回复
热议问题