Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set specific fill colors in ggplot2 by sign

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)
like image 722
Tahnoon Pasha Avatar asked Oct 16 '12 08:10

Tahnoon Pasha


People also ask

How do I specify colors in ggplot2?

When creating graphs with the ggplot2 R package, colors can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”). It is also possible to use pre-made color palettes available in different R packages, such as: viridis, RColorBrewer and ggsci packages.

How do you set a specific color in R?

In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.

What does %>% mean in Ggplot?

1. the %>% is a pipe operator that is actually part of the dplyr library (along with the filter function) not from the ggplot2 library. To sample 1%, there is a sample_frac function in the dplyr library.


1 Answers

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

require(reshape)
mydata2 = melt(mydata)

Basic barplot:

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

enter image description here

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

..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"))

enter image description here

like image 63
Paul Hiemstra Avatar answered Oct 02 '22 12:10

Paul Hiemstra