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

R 如何使用ggplot2更改堆叠条形图的顺序和颜色方案?,r,ggplot2,stacked-chart,R,Ggplot2,Stacked Chart,我试着把这些排序,这样空间就堆积在时间之上,然后按时间的升序排序。我还希望能够为每个堆栈选择颜色。 任何帮助都将不胜感激!非常感谢 数据如下: 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

我试着把这些排序,这样空间就堆积在时间之上,然后按时间的升序排序。我还希望能够为每个堆栈选择颜色。 任何帮助都将不胜感激!非常感谢

数据如下:

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

基本上,您所需要做的就是反转
Cat
中的因子。这里我使用了
forcats
包。注意:在此代码中,您的数据是
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()
要拾取颜色,请将其与任何其他ggplot图层一样添加。用您选择的颜色替换
“color1”
“color2”

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

除了@notthakindodr的答案之外,您还可以通过使用
forcats
软件包中的
fct\u reorder
功能对条形图进行重新排序,从而按时间升序排序:

库(dplyr)
图书馆(供猫用)
df%
突变(Cat=fct_版本(Cat),
Beg=fct\U重新排序(Beg、计数、最大值、.desc=T))
ggplot(df,aes(x=Beg,y=Count,fill=Cat))+
geom_col()+
ggtitle(“所有东西”)+
theme_classic()+
coord_flip()
其中:


您能否添加用于创建绘图的代码?这是否回答了您的问题?