首页 > 解决方案 > 在 ggplot 中指定条形图颜色

问题描述

我在 ggplot 中有一个条形图,我想在其中为条形图上色,它们落在哪个范围内。我绘制了 hlines 以显示我想要颜色变化的位置:0.4、0.5、0.6。我能找到的所有东西都会根据渐变进行着色。但是,我希望超过 0.6 的每个条都具有相同的绿色,低于 0.4 的每个条都具有相同的红色,等等。

attach(screen2D)
screen2D[order(screen2D[,2]),]
library(ggplot2)
ggplot(screen2D) +
  geom_bar(aes(x = reorder(Target, -Median), 
               y = Median),
           stat = "identity",
           fill = "skyblue") +
  geom_errorbar(aes(x = reorder(Target, 
                                - Median),
                    ymin = Q1, ymax = Q3),
                width = 0.25, colour = "black",
                alpha = 0.9, size = 0.2) +
  ggtitle("Title") +
  xlab("X Label") + 
  ylab("Y Label") +
  theme(plot.title = element_text(hjust = 0.5), 
        axis.text.x = element_text(angle = 90, 
                                   hjust = 1, 
                                   vjust = 0.25)) +
  scale_y_continuous(expand = c(0,0),
                     limits = c(0,1)) +
  geom_hline(yintercept = 0.40, linetype = "dashed",
             color = "red") +
  geom_hline(yintercept = 0.50, linetype = "dashed",
             color = "red") +
  geom_hline(yintercept = 0.60, linetype = "dashed",
           color = "red")

绘图输出 insidefill参数geom_bar要求长度为 1 或与数据集的长度相同,在本例中为 102。有解决办法吗?

我认为这scale_fill_manual对参数很有用breaks,但这似乎只指定了一个单独的变量。

+ scale_fill_manual(
     values = c("red", "yellow", "orange", "green"),
     breaks = c(Median<0.4, 0.4<Median<0.5,
                0.5<Median<0.6, 0.6<Median))

有没有办法实现这一点,而无需手动将数据集分成 4 个并将它们单独添加在一起?

标签: rggplot2

解决方案


感谢@ValeriVoev 的评论。在将颜色逻辑列导入到 R 之前,将颜色逻辑列添加到电子表格中的明显选择是我所需要的。

更正的条形图


推荐阅读