ggplot - How to set the bar itself to be colored b

2019-09-19 09:29发布

I want that the bars will be filled by the color gradient. Just to be clear, I don't mean to colored the whole bar with just one color based on the value and the gradient, like this:

scale_fill_gradient(low="green", high="red")

I mean gradient inside the bar itself, something like this:

enter image description here

What I'm trying to do is to create a kind of daily risk bar scale for 11 days and later on to add arrows to indicate the risk on each bar. It should look like this and I want that all the bars will be colored as the above bar pic.

    lines <- data.frame(day=c("Today", "Tomorrow","Day 3","Day 4","Day 5","Day 6","Day 7","Day 8","Day 9","Day 10","Day 11"),
                    a=rep(4,times=11))
lines$a <- as.numeric(lines$a)
order=c(1:11)

ggplot(lines, aes(x=reorder(day,-order),y=a, fill = a)) + 
       geom_bar(stat = "identity") +
       coord_flip()

标签: r ggplot2 colors
1条回答
家丑人穷心不美
2楼-- · 2019-09-19 10:15

You need lots of bars.

lines <- expand.grid(day=c("Today", "Tomorrow","Day 3","Day 4","Day 5","Day 6","Day 7","Day 8","Day 9","Day 10","Day 11"),
                     x = 1:1000)
lines$day <- factor(lines$day, unique(lines$day))

ggplot(lines, aes(day, x, fill = x)) + 
    geom_bar(stat = "identity", show.legend = FALSE) +
    coord_flip() + 
    viridis::scale_fill_viridis()

You can change the fill scale, but I don't advise using red to green.

enter image description here

查看更多
登录 后发表回答