ggplotly 分面图中 vline 旁边标签的 Y 轴位置

问题描述 投票:0回答:1

我正在使用 ggplotly 可视化,它使用分面按类别显示数据。每个面都有一条垂直线,我想在它旁边添加一个标签。我希望标签的 y 位置位于每个子图数据点中最大值的 80%。此外,如果标签可以旋转 90 度以提高可读性,那就更理想了。

这是我当前的代码和数据结构。

# 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
)

这是 ggplotly 代码

# 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") 
)
r ggplot2 ggplotly
1个回答
0
投票

我修改了 df,根据需要添加了 vline_date 和垂直位置,其中 y 最大值的 80%。 在

geom_text
中,我设置了
angle = 90
来旋转文本的标签。

# 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")

这是一个例子。我在 B 类别中添加了噪声以突出显示图中的不同高度。

plot

© www.soinside.com 2019 - 2024. All rights reserved.