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

2019-09-19 09:41发布

问题:

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:

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()

回答1:

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.



标签: r ggplot2 colors