R studio ggplot()对于geom_point()和geom_bar()有不同的颜色

mspsb9vt  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(165)

我需要做两个图表:geom_point()图和geom_bar()图。
我所有的数据都被划分为1-4组,这个组号是我用来给点和条线着色的。
下面是我的图表的代码:

ggplot(all_data, aes(Mean, total)) + 
   geom_point(size=0.5, color = all_data$group)

ggplot(attribute_data, aes(x=attribute,
                       y=attribute_value,
                       fill=factor(attribute_group))) +
   geom_bar(position="dodge",stat="identity") + 
   coord_flip() +
   ggtitle("Characterization")

当我查看每个图表中数据的不同方面时,我需要两个图表中每个组的颜色相同。每个数据文件中的组相同。但是,绘制每个图表时,组的颜色不同。如何使颜色相同?我是否遗漏了一些简单的内容?
下面是一些示例代码:

id <- c(1,2,3,4,5,6,7,8)
 mean <- c(13,23,42,53,64,75,75,8)
 total <- c(52,34,23,15,14,62,16,12)
 group <- c(3,2,1,4,3,2,2,1)

 df1 <- data.frame(id,mean,total,group)

 attribute <- c("round",
           "square",
           "round",
           "square",
           "round",
           "square",
           "round",
           "square"
 )
 value <- c(14,
                 13,
                 55,
                 76,
                 46,
                 3,
                 5,
                 6)
 attribute_group <- c(1,
                   1,
                   2,
                   2,
                   3,
                   3,
                   4,
                   4)
 df2 <- data.frame()

 ggplot(df1, aes(mean, total, color=group)) + 
 geom_point(size=3)

 ggplot(df2, aes(x=attribute,
                       y=value,
                       fill=factor(attribute_group))) +
 geom_bar(position="dodge",stat="identity") + 
 coord_flip() +
 ggtitle("Characterization")
cygmwpex

cygmwpex1#

如果你把aes(color = group)aes(fill = attribute_group)都 Package 在同一个factor函数中,并传递同一组levels,那么就可以确保它们都以离散颜色绘制,并且顺序/Map相同:

library(tidyverse)
ggplot(df1, aes(mean, total, color=factor(group, levels = 1:4))) + 
  geom_point(size=3) +
  scale_colour_discrete("Groups")

ggplot(df2, aes(x=attribute,
                y=value,
                fill=factor(attribute_group, levels = 1:4))) +
  geom_bar(position="dodge",stat="identity") + 
  coord_flip() +
  ggtitle("Characterization") +
  scale_fill_discrete("Groups")

相关问题