使用关于x轴最后值GGplot顺序说明

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

我有一段时间使用ggplot序列数据绘制。我想传说,这出现在图的右侧,是在同一数量级上的情节的x轴的最近日期/价值线。我尝试使用case_when功能,但我明显地使用它错了。下面是一个例子。

df <- tibble(
  x = runif(100),
  y = runif(100),
  z = runif(100),
  year = sample(seq(1900, 2010, 10), 100, T)
) %>%
  gather(variable, value,-year) %>%
  group_by(year, variable) %>%
  summarise(mean = mean(value))



df %>%
  ggplot(aes(year, mean, color = variable)) +
  geom_line()

Example

## does not work

df %>%
  mutate(variable = fct_reorder(variable, case_when(mean ~ year == 2010)))
  ggplot(aes(year, mean, color = variable)) +
  geom_line()
r ggplot2 dplyr
1个回答
1
投票

我们可以添加一个额外的行

ungroup() %>% mutate(variable = fct_reorder(variable, mean, tail, n = 1, .desc = TRUE))

前绘制,或使用

df %>%
  mutate(variable = fct_reorder(variable, mean, tail, n = 1, .desc = TRUE)) %>%
  ggplot(aes(year, mean, color = variable)) +
  geom_line()

这样,我们就来看看mean的最后的值,并相应地重新排序variable

enter image description here

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