更改不同组之间的填充顺序ggplot2

问题描述 投票:0回答:1
 library(ggplot2)
 library(dplyr)

 series <- data.frame(
      time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),
      type = c(1984:1987),
      value = rpois(16, 10)
    )
    
    
    series %>%
      ggplot(aes(time, value, group=factor(type, levels=1987:1984)))+
      geom_col(aes(fill= factor(type)))+
      guides(fill=guide_legend(title="type"))

我想重新排序不同组之间的填充顺序,如下图我在Paint中编辑的。我怎样才能做到这一点?

Plot

编辑:

  • 对于时间 1,我想要顺序为 1984、1985、1986 和 1987。
  • 对于时间 2,我想要顺序为 1984、1986、1985 和 1987。
  • 对于时间 3,我想要顺序为 1984、1985、1987 和 1986。
  • 对于时间 3,我想要顺序为 1987、1986、1985 和 1984。
r ggplot2 bar-chart
1个回答
0
投票

一个相当老套的解决方案,其中包括创建一个新的因子列,您可以根据您希望它们出现的顺序为每个

time
type
手动排序。然后使用它来为条形着色,定义所有级别在具有相同
type
的新因子中具有相同的颜色,然后从图例中删除多余的元素:

library(ggplot2)
library(dplyr)

series <- data.frame(
  time = c(rep(1, 4), rep(2, 4), rep(3, 4), rep(4, 4)),
  type = c(1984:1987),
  value = rpois(16, 10)
)

# set order of variables for each time point
plot_data <- series |>
  mutate(
    type = factor(type),
    lvl = paste0(time, "-", type),
    lvl = factor(lvl, levels = c(
      c(
        "1-1984", "1-1985", "1-1986", "1-1987",
        "2-1984", "2-1986", "2-1985", "2-1987",
        "3-1984", "3-1985", "3-1987", "3-1986",
        "4-1987", "4-1986", "4-1985", "4-1984"
      )
    ))
  )

# set colours to use
col_palette <- RColorBrewer::brewer.pal(
  n = length(unique(plot_data$type)),
  name = "Dark2"
)
names(col_palette) <- unique(plot_data$type)
cols_to_plot <- plot_data |>
  select(lvl, type) |>
  left_join(tibble::enframe(col_palette),
    by = c("type" = "name")
  ) |>
  select(lvl, value) |>
  tibble::deframe()

# plot
plot_data |>
  ggplot(aes(x = time, y = value)) +
  geom_col(aes(fill = lvl)) +
  scale_fill_manual(
    values = cols_to_plot,
    breaks = c("1-1984", "1-1985", "1-1986", "1-1987"),
    labels = c("1984", "1985", "1986", "1987"),
    name = "type"
  )

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.