2
ggplot(data = dat) + geom_line(aes(x=foo,y=bar)) +geom_line(aes(x=foo_land,y=bar_land))

which creates a plot like the following:

plot without line

I want to try and indicate the maximum values on this plot as well as add corresponding labels to the axis like:

plot with line

The data for the maximum x and y values is stored in the dat file.

I was attempting to use

geom_hline() + geom_vline()

but I couldn't get this to work. I also believe that these lines will continue through the rest of the plot, which is not what I am trying to achieve. I should note that I would like to indicate the maximum y-value and its corresponding x value. The x-value is not indicated here since it is already labelled on the axis.

Reproducible example:

library(ggplot2)

col1 <- c(1,2,3)
col2 <- c(2,9,6)
df <- data.frame(col1,col2)

ggplot(data = df) +
  geom_line(aes(x=col1,y=col2))

reproducible

I would like to include a line which travels up from 2 on the x-axis and horizontally to the y-axis indicating the point 9, the maximum value of this graph.

Fish_Person
  • 107
  • 5
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Feb 02 '23 at 15:27

1 Answers1

3

Here's a start, although it does not make the axis text red where that maximal point is:

MaxLines <- data.frame(col1 = c(rep(df$col1[which.max(df$col2)], 2),
                            -Inf), 
                   col2 = c(-Inf, rep(max(df$col2), 2)))

MaxLines creates an object that says where each of three points should be for two segments.

ggplot(data = df) +
    geom_line(aes(x=col1,y=col2)) +
    geom_path(data = MaxLines, aes(x = col1, y = col2),
              inherit.aes = F, color = "red") +
    scale_x_continuous(breaks = c(seq(1, 3, by = 0.5), df$col1[which.max(df$col2)])) +
    scale_y_continuous(breaks = c(seq(2, 9, by = 2), max(df$col2)))

enter image description here

shirewoman2
  • 1,842
  • 4
  • 19
  • 31
  • 1
    if you create an annotation for the extra y label instead of a proper break within scale_continuous, then you can easily make the label red – tjebo Feb 02 '23 at 16:07
  • 1
    @tjebo or make a conditionally red label via `ggtext` to avoid turning clipping off and having to find the correct co-ordinates? – Allan Cameron Feb 02 '23 at 16:26