【问题标题】:Specifying barplot colors in ggplot在 ggplot 中指定条形图颜色
【发布时间】:2020-10-05 04:20:00
【问题描述】:

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

Plot Output geom_bar 中的 fill 参数要求长度为 1 或与数据集的长度相同,在本例中为 102。有解决办法吗?

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

+ 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 个并单独添加在一起?

【问题讨论】:

  • 我的建议是添加一个具有您描述的颜色逻辑的列,并将该列传递给fill审美。
  • @ValeriVoev 感谢您的帮助。完美运行。

标签: r ggplot2


【解决方案1】:

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

Corrected Barplot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多