【问题标题】:Set specific fill colors in ggplot2 by sign通过符号在ggplot2中设置特定的填充颜色
【发布时间】:2012-10-16 08:13:06
【问题描述】:

Hi想调整下面的图表,使零以下的值用红色填充,上面的值用深蓝色填充。我怎样才能用 ggplot2 做到这一点?

   mydata = structure(list(Mealtime = "Breakfast", Food = "Rashers", `2002` = 9.12, 
                            `2003` = 9.5, `2004` = 2.04, `2005` = -20.72, `2006` = 18.37, 
                            `2007` = 91.19, `2008` = 94.83, `2009` = 191.96, `2010` = -125.3, 
                            `2011` = -18.56, `2012` = 63.85), .Names = c("Mealtime", "Food", "2002", "2003", "2004", "2005", "2006", "2007", "2008","2009", "2010", "2011", "2012"), row.names = 1L, class = "data.frame")
x=ggplot(mydata) +
  aes(x=colnames(mydata)[3:13],y=as.numeric(mydata[1,3:13]),fill=sign(as.numeric(mydata[1,3:13]))) +
  geom_bar(stat='identity') + guides(fill=F)
print(x)

【问题讨论】:

    标签: r graphics formatting ggplot2


    【解决方案1】:

    您构建数据的方式不是ggplot2 中应有的方式:

    require(reshape)
    mydata2 = melt(mydata)
    

    基本条形图:

    ggplot(mydata2, aes(x = variable, y = value)) + geom_bar()
    

    现在的诀窍是添加一个额外的变量来指定值是负数还是正数:

    mydata2[["sign"]] = ifelse(mydata2[["value"]] >= 0, "positive", "negative")
    

    ..并在对ggplot2 的调用中使用它(与scale_fill_* 结合用于颜色):

    ggplot(mydata2, aes(x = variable, y = value, fill = sign)) + geom_bar() + 
      scale_fill_manual(values = c("positive" = "darkblue", "negative" = "red"))
    

    【讨论】:

    • 太棒了。谢谢你。 scale_fill_manual 是我要找的。我同意你关于融化和重铸数据的观点。我对 dput() 很懒惰。这仍然适用于我的笨拙代码+ scale_fill_manual(values=c("1" = "dark blue","-1" = "red")),但会导致更难分析。
    • 你通常不使用向量作为美学。美学是将变量(data.frame 中的列)映射到图中的轴。
    猜你喜欢
    • 2013-07-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多