Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill gradient color not working with geom_bar of ggplot2

Tags:

r

ggplot2

When I use scale_fill_gradient() with geom_bar() in ggplot2, only one default color is filled for all bar. But expecting GREEN to RED for low to high count.

theTable <- within(data, Tag <- factor(tag, levels=names(sort(table(tag), 
                                                        decreasing=FALSE))))
histGraph=ggplot(theTable,aes(x=Tag))+
  coord_flip() +
  scale_fill_gradient(low = "green", high = "red")+
  geom_bar(width=0.7)

Output of above code,

Actual output

And data look like,

ID  Tag
1   BibArticleDOI
1   FirstPage
1   LastPage
2   BibArticleDOI
2   JournalTitle
3   BibArticleDOI
3   FirstPage

Edit: As got suggestion from Roman, editing above code.

dataOfTag <- as.data.frame(table(data$tag))
dataOfTag$tag <- factor(dataOfTag$Var1, levels = dataOfTag$Var1[order(dataOfTag$Freq)])

histPlot=ggplot(dataOfTag,aes(x=tag, y = Freq, fill = Freq))+
  coord_flip() +
  scale_fill_gradient(low = "green", high = "red")+
  geom_bar(width=0.7, stat = "identity")
histPlot
like image 900
Somnath Kadam Avatar asked May 20 '16 09:05

Somnath Kadam


2 Answers

You can try something along the lines of the below code. Precompute frequencies and assign fill to the frequency variable.

library(ggplot2)

xy <- data.frame(letters = sample(letters[1:6], size = 1000, replace = TRUE, prob = c(0.5, 0.3, 0.1, 0.5, 0.25, 0.25)))

xy2 <- as.data.frame(table(xy$letters))
xy2$Var1 <- factor(xy2$Var1, levels = xy2$Var1[order(xy2$Freq)])

ggplot(xy2,aes(x=Var1, y = Freq, fill = Freq))+
  coord_flip() +
  scale_fill_gradient(low = "green", high = "red")+
  geom_bar(width=0.7, stat = "identity")

enter image description here

like image 51
Roman Luštrik Avatar answered Nov 01 '22 14:11

Roman Luštrik


I think you can use ..count.. so you don't need to pre-compute the frequency:

histGraph=ggplot(theTable,aes(x=Tag, fill=..count..))+
  coord_flip() +
  scale_fill_gradient(low = "green", high = "red")+
  geom_bar(width=0.7)
like image 20
lafncow Avatar answered Nov 01 '22 15:11

lafncow