将图例中的颜色顺序与堆积条形图中的颜色顺序相对应

时间:2019-05-02 12:53:12

标签: r ggplot2

我的数据框如下:

Target_Category<-c("Adhesion","Cytochrome")
Validated<-c(5,12)
Candidate<-c(10,23)
Exploratory<-c(7,6)
Unknown<-c(9,4)
dataf<-data.frame(Target_Category,Validated,Candidate,Exploratory,Unknown)

然后我在下面创建堆叠的条形图:

library(tidyverse)

d<-dataf %>%
  gather(col, value, -Target_Category) %>%
  ggplot() + 
  geom_bar(aes(Target_Category, value, fill = col), stat="identity")
d+scale_fill_manual(values=c("orange","gray48","black","green4"),
                    breaks = c("Validated", "Candidate",
                               "Exploratory", "Unknown"))

enter image description here

问题是颜色值和中断之间的对应关系不正确,因为正确的输出应为绿色,橙色,灰黑色,并且对应关系应类似于下图。图例名称的顺序正确,但图中的颜色顺序不正确。

即使我使用

d<-dataf %>%
  gather(col, value, -Target_Category) %>%
  mutate(col=factor(col, levels = c("Validated", "Candidate",
                                    "Exploratory", "Unknown"))) %>% 
  ggplot() + 
  geom_bar(aes(Target_Category, value, fill = col), stat="identity")

d+scale_fill_manual(values=c("orange","gray48","black","green4"),
                    breaks = c("Validated", "Candidate",
                               "Exploratory", "Unknown"))

输出与第二张图像中的预期输出不同。

enter image description here

1 个答案:

答案 0 :(得分:1)

正如卡米尔所解释的,您可以使用factor来控制颜色的顺序:

    d<-dataf %>%
  gather(col, value, -Target_Category) %>%
  mutate(col=factor(col, levels = c("Unknown", "Exploratory", "Candidate", "Validated"))) %>% 
  ggplot() + 
  geom_bar(aes(Target_Category, value, fill = col), stat="identity")

d+scale_fill_manual(values=c("black", "gray48", "orange", "green4"),
                    breaks = c("Validated", "Candidate",
                               "Exploratory", "Unknown"))