填充渐变颜色不适用于ggplot2的geom_bar

时间:2016-05-20 09:34:36

标签: r ggplot2

当我在ggplot2中使用scale_fill_gradient()和geom_bar()时,只为所有条形填充一个默认颜色。但是期待从低到高的绿色为RED。

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)

输出上述代码,

Actual output

数据看起来像,

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

修改 正如Roman的建议,编辑上面的代码。

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

2 个答案:

答案 0 :(得分:8)

您可以尝试以下代码的内容。 预计算频率并将填充分配给频率变量。

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

答案 1 :(得分:0)

我认为您可以使用..count..,因此您无需预先计算频率:

histGraph=ggplot(theTable,aes(x=Tag, fill=..count..))+
  coord_flip() +
  scale_fill_gradient(low = "green", high = "red")+
  geom_bar(width=0.7)