I'm working with a ggplotly visualization that uses faceting to display data by category. Each facet has a vertical line, and I want to add a label next to it. I'd like the label's y-position to be at 80% of the maximum value in each subplot's data points. Additionally, it would be ideal if the labels could be rotated 90 degrees for better readability.
Here's my current code and the data structure.
# Set the seed for reproducibility (optional)
set.seed(123)
# Define start and end dates
start_date <- as.Date("2023-01-01")
end_date <- as.Date("2023-12-30")
# Generate random dates within the defined range
dates <- seq(from = start_date, to = end_date, by = "day")
# Define categories
categories <- rep(c("A", "B"), each = length(dates)/2) # Repeat A and B to create equal length vectors
# Generate random numerical values for category B
values_B <- rnorm(length(dates), mean = 50, sd = 10)
# Generate values for category A (10 times lower than B)
values_A <- values_B / 10
# Combine categories and values based on category order
values <- ifelse(categories == "A", values_A, values_B)
# Create a data frame
df <- data.frame(
date = dates,
value = values,
category = categories
)
Here is the ggplotly codes
# Define the date for the vertical line
vline_date <- as.Date("2023-10-25")
# Create the ggplot with faceting and vertical line
ggplotly(
ggplot(df, aes(x = date, y = value, color = category)) +
geom_line() +
facet_wrap(~ category, scale = "free_y") + # Facet by category
geom_vline(xintercept = as.numeric(vline_date), linetype = "dashed", color = "red") +
labs(title = "Line Plot with Category Faceting and Vertical Line",
x = "Date", y = "Value")
)
I've modified the df, adding the vline_date and the vertical position as you wanted with 80% of the y's max value.
In geom_text
I've set angle = 90
to rotate the text's label.
# Define the date for the vertical line
vline_date <- as.Date("2023-10-25")
# Create the ggplot with faceting and vertical line
df |>
cbind(label = "label",
vline_date = vline_date) |>
group_by(category) |>
mutate(y_pos = max(value)*.8) |>
ggplot(aes(x = date, y = value, color = category)) +
geom_line() +
# Add text labels for the vertical line and rotate 90 degrees
geom_text(aes(label = "label", x = vline_date, y = y_pos), color = "black", angle = 90, vjust = -0.5) +
facet_wrap(~ category, scale = "free_y") + # Facet by category
geom_vline(xintercept = as.numeric(vline_date), linetype = "dashed", color = "red") +
labs(title = "Line Plot with Category Faceting and Vertical Line",
x = "Date", y = "Value")
This is an example. I've added a noise to B category to highlight the different height in the plot.