您想调整以下图表,以便将零以下的值填充为红色,上面的值为深蓝色。我怎么能用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)
答案 0 :(得分:20)
您构建数据的方式不是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"))