向ggplot中的每个矩形添加相同的渐变

Mih*_*iha 3 r ggplot2

我正在尝试在下面创建的ggplot2中显示颜色渐变。因此,使用以下数据和代码

vector <- c(9, 10, 6, 5, 5)
Names <- c("Leadership", "Management\n", "Problem Solving",
           "Decision Making\n", "Social Skills")

# add \n
Names[seq(2, length(Names), 2)] <- paste0("\n" ,Names[seq(2, length(Names), 2)]) 
# data.frame, including a grouping vector
d <- data.frame(Names, vector, group=c(rep("Intra-capacity", 3), rep("Inter-capacity", 2))) 
# correct order
d$Names  <- factor(d$Names, levels= unique(d$Names))
d$group_f = factor(d$group, levels=c('Intra-capacity','Inter-capacity'))
# plot the bars

p <- ggplot(d, aes(x= Names, y= vector, group= group, fill=vector, order=vector)) + 
  geom_bar(stat= "identity") +
  theme_bw()+
  scale_fill_gradient(low="white",high="blue")
# use facet_grid for the groups
#p + facet_grid(.~group_f, scales= "free_x", space= "free_x") 
p+ theme(text = element_text(size=23),plot.background = element_rect(fill = "white"),
         strip.background = element_rect(fill="Dodger Blue")) +
  facet_grid(.~group_f, scales= "free_x", space= "free_x") +  xlab("") +ylab("") +
  theme(strip.text.x = element_text(size = 18, colour = "white" )) + 
  geom_text(size=10, aes(label=vector)) 
Run Code Online (Sandbox Code Playgroud)

我的输出是这样的: 在此处输入图片说明

但是现在我想插入颜色渐变,以便每个矩形看起来像下面的图片(我想要的输出):

在此处输入图片说明

我也看了这个:

R:ggplot2中geom_rect的渐变填充

创建具有渐变颜色的箭头

http://www.computerworld.com/article/2935394/business-intelligence/my-ggplot2-cheat-sheet-search-by-task.html

带有ggplot的颜色渐变

用文本:ggplot2标记比例尺填充梯度图例的最小值和最大值

如何在ggplot2中的geom_rect对象上应用渐变填充?

并尝试使用:

scale_fill_gradient(low="white",high="blue") 要么

scale_fill_gradientn(colours = c("blue","white","red"), 
                     values = c(0,5,10),
                     guide = "colorbar", limits=c(0,10))
Run Code Online (Sandbox Code Playgroud)

但是我显然做错了。

luk*_*keA 5

我在这里与@RomanLustrik。但是,如果您不能使用Excel(=容易得多),则仅添加带有alpha渐变的白色矩形就足够了:

ggplot(d, aes(x= Names, y= vector, group= group,order=vector)) + 
  geom_bar(stat= "identity", fill="blue") +
  theme_bw() + 
  scale_fill_gradient(low="white",high="blue") + 
  annotation_custom(
    grid::rasterGrob(paste0("#FFFFFF", as.hexmode(1:255)), 
                     width=unit(1,"npc"), 
                     height = unit(1,"npc"), 
                     interpolate = TRUE), 
    xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=5
  ) + 
  geom_text(aes(label=vector), color="white", y=2, size=12)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 你懂我!可以用投票的答案来回一下。 (2认同)