i have a data frame with dates and values :
n = 1000
date = seq(as.Date("2022/1/1"), by = "day", length.out = n)
value = rnorm(n,0,1)
df = tibble(date,value);df
how can i ggplot this data frame and to plot in the geom_line or geom_point two arrows pointing the maximum value and the minimum value of the value variable ?
ggplot(data =df, aes(x = date,y=value))
geom_point()
ggplot(data =df, aes(x = date,y=value))
geom_line()
Any help ?
CodePudding user response:
It's easiest to create a dataframe of the data for the annotations and then add it to the plot.
Here I make maxmin_df, which contains the details of the maximum and minimum values, and then add a geom_segment()
to add them to the ggplot()
.
You'll need to decide on the look of the line and arrows.
max_df <- tibble(y = max(df$value),
yend = y,
x = df$date[which(df$value == y)] lubridate::days(5),
xend = x lubridate::days(50))
minmax_df <- bind_rows(max_df,
c(tibble(y = min(df$value),
yend = y,
x = df$date[which(df$value == y)] lubridate::days(5),
xend = x lubridate::days(50))
)
)
ggplot(data = df, aes(x = date,y=value))
geom_point()
geom_segment(data = minmax_df, aes(x = xend, xend = x, y = y, yend = yend), colour = "red", arrow = arrow())
CodePudding user response:
Update:
One way could be using additional packages like ``ggpmiscor
gghighlight`:
ggpmisc
library(ggplot2)
library(ggpmisc)
ggplot(data =df, aes(x = date,y=value))
geom_point()
geom_point(data = df[which.max(df$value), ], color="red",
size=3)
stat_peaks(span = NULL,
geom = "text_s",
x.label.fmt = "my text",
segment.colour = "blue",
arrow = grid::arrow(length = unit(0.1, "inches")),
position = position_nudge_keep(x = 90, y = 0.1),
hjust = 0)
OR
gghighlight
:
library(gghighlight)
library(dplyr)
library(ggplot2)
df %>%
mutate(my_label = ifelse(value == max(value), "my text", "")) %>%
ggplot(aes(x = date,y=value))
geom_point()
gghighlight(value == max(value),
use_direct_label = TRUE,
label_key = my_label,
label_params = list(size=3,
color="red"))
geom_point(col = "red", size = 3)
by adding unhighlighted_colour = alpha("black", 1),
we can keep the color of the original geom_point:
First answer: Maybe this one is also helpful: coloring the max value red:
library(ggplot2)
ggplot(data =df, aes(x = date,y=value))
geom_point()
geom_point(data = df[which.max(df$value), ], color="red",
size=3)