Fish_Person
Fish_Person

Reputation: 111

Indicating the maximum values and adding corresponding labels on a ggplot

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.

Upvotes: 2

Views: 124

Answers (1)

shirewoman2
shirewoman2

Reputation: 1928

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

Upvotes: 3

Related Questions