【问题标题】:Make all positive value bar graph the same color theme as bar graph with negative values in ggplot使所有正值条形图与 ggplot 中具有负值的条形图具有相同的颜色主题
【发布时间】:2014-10-04 15:43:39
【问题描述】:

我昨天刚开始玩 ggplot。我的负值条形图代码按预期工作:

dtf1 <- data.frame(ID = c(1:10),Diff = c(-5:4))
dtf1$colour <- ifelse(dtf1$Diff < 0, "firebrick1","steelblue")
dtf1$hjust <- ifelse(dtf1$Diff > 0, 1.3, -0.3)
ggplot(dtf1,aes(ID,Diff,label="",hjust=hjust))+
  geom_text(aes(y=0,colour=colour))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))

但当我将相同的代码应用于只有正值的不同数据集时,情况并非如此

dtf <- data.frame(ID = c(1:10),Diff = rnorm(10,3))
dtf$colour <- ifelse(dtf$Diff < 0, "firebrick1","steelblue")
dtf$hjust <- ifelse(dtf$Diff > 0, 1.3, -0.3)
ggplot(dtf,aes(ID,Diff,label="",hjust=hjust))+
  geom_text(aes(y=0,colour=colour))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))

我发现我可以调整代码的最后一行来为我的正条获得蓝色, geom_bar(stat="identity",position="identity",fill="steelblue")

因此,我的两个问题是:

  1. 但是,颜色不符合预期:

看起来颜色可能更接近绿松石3而不是钢蓝。

  1. 此外,我还想知道为什么相同的代码会 允许正面条具有不同的颜色。

我一定是在问一个非常简单的问题。我不知道如何最好地表达它,因此很难找到解决方案。如果问题已经被问过,我很抱歉,我很乐意删除自己。

【问题讨论】:

    标签: r colors ggplot2


    【解决方案1】:

    美学在ggplot 中不起作用。 $colour 被视为具有两个级别的因素,firebrick1steelblue,但这些是 不是ggplot 使用的颜色。它们只是色标的标签。 ggplot 选择它自己的颜色。如果要覆盖默认值,请添加以下行:

    scale_fill_manual(values=c(firebrick1="firebrick1",steelblue="steelblue"))
    

    比较一下:

    dtf1$colour <- ifelse(dtf1$Diff < 0, "negative","positive")
    ggplot(dtf1,aes(ID,Diff,label="",hjust=hjust))+
      geom_bar(stat="identity",position="identity",aes(fill = colour))+
      scale_fill_manual(values=c(positive="firebrick1",negative="steelblue"))
    

    这适用于所有正面(或负面)。

    dtf <- data.frame(ID = c(1:10),Diff = rnorm(10,3))
    dtf$colour <- ifelse(dtf$Diff < 0,"negative","positive")
    dtf$hjust <- ifelse(dtf$Diff > 0, 1.3, -0.3)
    ggplot(dtf,aes(ID,Diff,label="",hjust=hjust))+
      geom_bar(stat="identity",position="identity",aes(fill = colour))+
      scale_fill_manual(values=c(positive="firebrick1",negative="steelblue"))
    

    【讨论】:

    • 谢谢 - 我真的很感激拥有一个适用于所有图表的代码。我对颜色的解释是错误的
    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多