EGM8686
EGM8686

Reputation: 1572

R ggplot annotate line plot with max value

I have a line plot created with this code:

# Create data
year <- c(2006,2007,2008,2009,2010,2011,2012,2013,2014)
sales <- c(4176,8560,6473,10465,14977,15421,14805,11183,10012)
df <- data.frame(year,sales)

# Plot
ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line()

I would like to annotate it with a line that "shows" the maximum value like the example below:

enter image description here

Is this possible with ggplot?

Upvotes: 1

Views: 2092

Answers (2)

George Savva
George Savva

Reputation: 5336

This is close, just needs the arrow:

ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line() + theme_bw() + 
  geom_linerange(aes(ymax=sales, ymin=min(df$sales)), 
                 data=df[which.max(df$sales),], 
                 col="red", lty=2) + 
  geom_text(aes(label=sales),data=df[which.max(df$sales),], hjust=1.2, vjust=3)

It works by adding geom_linerange and geom_text geoms but setting the data for each to be the row of the original dataset corresponding to the maximum of the 'sales' column.

Upvotes: 0

Jeremy
Jeremy

Reputation: 876

Yes. For your current example, try this:

ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line() + 
       geom_segment(aes(x = 2011, y = 0, xend = 2011, yend = 15421),linetype="dashed", color = "red")

Of course, for more general plotting needs, you can improve the codes instead of manually inputting the values here.

Upvotes: 1

Related Questions