Search code examples
rggplot2geom-textggpmisc

How to plot only Global Maximum Value using geom_text?


df%>%
  group_by(approved_date)%>%
  summarise(rev=sum(gmv))%>%
  ggplot(aes(x = approved_date, y = rev)) + 
    geom_line() + 
    geom_smooth(method = 'auto', se = FALSE) + 
    labs(x = 'Date', y = 'Revenue', title = 'Revenue by Date') +
    scale_y_continuous(labels = function(x) format(x, scientific = FALSE)) +
    stat_peaks(colour = "red", span = NULL) + 
    stat_valleys(colour = "blue", span = NULL) + 
    geom_text(aes(label = round(rev, 0)),
              vjust = "inward", 
              hjust = "inward",
              show.legend = FALSE,
              check_overlap = TRUE)

I have this code which on running labels all values of Local Maxima and Minima. I want only the value of Global Maximum and Global Minimum.How to do that?


Solution

  • As the code in the question cannot be run for lack of data, I show an example slightly modified from the package User Guide. In this case this different example should be enough to work out the solution.

    library(ggpmisc)
    ggplot(lynx, as.numeric = FALSE) + geom_line() + 
      stat_peaks(colour = "red") +
      stat_peaks(geom = "text", colour = "red", vjust = -0.5, 
                 check_overlap = TRUE, span = NULL) +
      ylim(-100, 7300)
    

    enter image description here

    In other words geom "text" should be passed as argument to stat_peaks() as well as span = NULL to get a single label. If you add geom_text() directly, peaks are not selected but instead all values stored in the variable mapped to the label aesthetic are added to the plot.