通过符号在ggplot2中设置特定的填充颜色 [英] Set specific fill colors in ggplot2 by sign

查看:617
本文介绍了通过符号在ggplot2中设置特定的填充颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好希望调整以下图表,以使零以下的值用红色填充,而上方的则用深蓝色填充.如何使用ggplot2做到这一点?

Hi wanted to adjust the following chart so that the values below zero are filled in red and the ones above are in dark blue. How can I do this with 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)

推荐答案

构造数据的方式与ggplot2中的数据不同:

The way you structure your data is not how it should be in ggplot2:

require(reshape)
mydata2 = melt(mydata)

基本条形图:

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

现在的技巧是添加一个附加变量,该变量指定值是负数还是正数:

The trick now is to add an additional variable which specifies if the value is negative or postive:

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

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

..and use that in the call to ggplot2 (combined with scale_fill_* for the colors):

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

这篇关于通过符号在ggplot2中设置特定的填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆