简体   繁体   English

如何使用 ggplot2 更改堆叠条形图的顺序和配色方案?

[英]How to change the order and color scheme of stacked bar charts using ggplot2?

I am trying to get these ordered so that Space is stacked on top of Time and then order them in ascending order of Time.我正在尝试对这些进行排序,以便将空间堆叠在时间之上,然后按时间的升序对它们进行排序。 I also want to be able to pick the colors for each stack.我还希望能够为每个堆栈选择 colors。 Any help would be appreciated!Thanks a lot!任何帮助将不胜感激!非常感谢!

Data below:数据如下:

structure(list(Beg = structure(c(20L, 19L, 18L, 15L, 1L, 3L, 
    6L, 10L, 13L, 8L, 5L, 11L, 9L, 7L, 2L, 4L, 17L, 16L, 14L, 12L, 
    20L, 19L, 18L, 15L, 1L, 3L, 6L, 10L, 13L, 8L, 5L, 11L, 9L, 7L, 
    2L, 4L, 17L, 16L, 14L, 12L), .Label = c("a", "b", "c", "d", "e", 
    "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", 
    "s", "t"), class = "factor"), Cat = structure(c(2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L), .Label = c("Time", "Space"), class = "factor"), 
        Count = c(7824.92, 1006.79, 3570.93, 1484.5, 2885.32, 4194.84, 
        4348.94, 3603.31, 4826.33, 2225.49, 3350.02, 3778.35, 2698.51, 
        2247.01, 1705.17, 4742.72, 15231.15, 14083.26, 4437.68, 3109.09, 
        18875.45, 25816.95, 20836.93, 25501.53, 23996.55, 19427.12, 
        21467.89, 22472.71, 9876.27, 9548.99, 22171.83, 21179.33, 
        23358.26, 24763.62, 24551.94, 16726.11, 10691.68, 10537.26, 
        18012.88, 21453.15)), row.names = c(NA, -40L), class = "data.frame")

到目前为止我所拥有的

Essentially all you need to do is reverse the factors in Cat .基本上,您需要做的就是反转Cat中的因素。 Here I used the forcats package.这里我使用了forcats package。 Note your data is df in this code:请注意,您的数据在此代码中是df

library(forcats)
library(dplyr)

df %>% 
  mutate(Cat = forcats::fct_rev(Cat)) %>% 
  ggplot() +
  geom_col(aes(Beg, Count, fill = Cat)) +
  ggtitle("All Stuff") +
  coord_flip() +
  theme_classic()

To pick the colors use this by adding it like any other ggplot layer.要选择 colors,请像添加任何其他 ggplot 层一样使用它。 Substitute "color1" and "color2" with your color of choice:用您选择的颜色替换"color1""color2" color2”:

scale_fill_manual(values = c("color1", "color2"))

Adding to @NotThatKindODr's answer, you can order the bars in ascending order of time by reordering them with the fct_reorder function from the forcats package:添加到@NotThatKindODr 的答案中,您可以通过使用来自forcats package 的fct_reorder function 重新排序条形来按时间升序对条形进行排序:

library(dplyr)
library(forcats)

df <- df %>% 
  mutate(Cat = fct_rev(Cat),
         Beg = fct_reorder(Beg, Count, max, .desc = T))

ggplot(df, aes(x = Beg, y = Count, fill = Cat)) + 
  geom_col() + 
  ggtitle("All Stuff") +
  theme_classic() + 
  coord_flip() 

Which gives:这使:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM