如何在ggplot中向点和条发出相同的颜色比例

时间:2015-12-04 19:44:02

标签: r ggplot2

我有一个数据框,并希望使用ggplot向点和条发出相同的颜色。不幸的是,即使为点和条都选择了相同的连续变量,ggplot也会选择它自己的渐变比例。

如何强制ggplot为两者使用相同的色标?见下面的例子:

data <- structure(list(ind = structure(c(5L, 4L, 3L, 2L, 1L), .Label = c("Indicator 5", 
                                                                         "Indicator 4", "Indicator 3", "Indicator 2", "Indicator 1"), class = "factor"), 
                       value = c(2L, 26L, 29L, 39L, 40L), Target = c(20L, 30L, 30L, 
                                                                     45L, 60L), LastYr = c(90L, 80L, 95L, 80L, 50L), Perc.time = c(92.539356605065, 
                                                                                                                                   92.539356605065, 92.539356605065, 92.539356605065, 92.539356605065
                                                                     ), Perc = c(10, 86.6666666666667, 96.6666666666667, 86.6666666666667, 
                                                                                 66.6666666666667), Behind = c(-10, -5.87268993839835, 0, 
                                                                                                               -5.87268993839835, -10), tex = c("Need 17 more", "Need 2 more", 
                                                                                                                                                "OK!", "Need 3 more", "Need 16 more")), .Names = c("ind", 
                                                                                                                                                                                                   "value", "Target", "LastYr", "Perc.time", "Perc", "Behind", "tex"
                                                                                                                                                ), row.names = c(NA, -5L), class = "data.frame")
library(ggplot2)
ggplot(data, aes(ind))+ 
  geom_bar(aes(y=Perc,width=0.2,fill=Behind),stat = "identity") + 
  geom_point(aes(y=Perc,color=Behind),size=10) +
  scale_colour_gradient(low = "red",high="dark green", limits=c(LowLVL,0))

由此产生的情节:

enter image description here

1 个答案:

答案 0 :(得分:1)

您还需要设置条形图的颜色,所以试试这个

ggplot(data, aes(ind))+ 
  geom_bar(aes(y=Perc,width=0.2,fill=Behind),stat = "identity") + 
  geom_point(aes(y=Perc,color=Behind),size=10) +
  scale_colour_gradient(low = "red",high="dark green") + scale_fill_gradient(low = "red",high="dark green")