Highlight minimum and maximum points in faceted ggplot2 graph in R -


i using built-in economics (from ggplot2 package) dataset in r, , have plotted time-series each variable in same graph using following code :

library(reshape2) library(ggplot2)  me <- melt(economics, id = c("date")) ggplot(data = me) +       geom_line(aes(x = date, y = value)) +      facet_wrap(~variable, ncol = 1, scales = 'free_y') 

now, further want refine graph, each series, want display red point smallest , largest value. thought if find co-ordinates of min , max of each time-series, find way plot red dot @ beginning , ending of each time series. used following code :

which(pce == min(economics$pce), arr.ind = true)  which(pca == max(pca), arr.ind = true) 

this doesnt lead me anywhere. thank you:)

method 1: using joins

this can nice when want save filtered subsets


library(reshape2) library(ggplot2) library(dplyr)  me <- melt(economics, id=c("date"))  me %>%   group_by(variable) %>%   summarise(min = min(value),             max = max(value)) -> me.2  left_join(me, me.2) %>%   mutate(color = value == min | value == max) %>%   filter(color == true) -> me.3  ggplot(data=me, aes(x = date, y = value)) +    geom_line() +   geom_point(data=me.3, aes(x = date, y = value), color = "red") +   facet_wrap(~variable, ncol=1, scales='free_y') 

method 2: simplified without joins

thanks @gregor

me.2 <- me %>%   group_by(variable) %>%   mutate(color = (min(value) == value | max(value) == value))  ggplot(data=me.2, aes(x = date, y = value)) +   geom_line() +   geom_point(aes(color = color)) +   facet_wrap(~variable, ncol=1, scales="free_y") +   scale_color_manual(values = c(na, "red")) 

plot


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -