ggplot2: barplot with colors as a function of y-ax

2019-04-28 20:24发布

I have this simple code (data + barplot) :

dat <- c('Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
val <- c(-2.5, 3, 2.5, -3.3, -1, 0.2, 6, 4.3, 5.5, 2, -1.9, -2.3)
df <- data.frame(dat, val)
bar <- ggplot(data = df, aes(x = factor(dat, levels = month.abb), y = val)) +
    geom_bar(stat = 'identity')
print(bar)

Elsewhere I created a heatmap using the following palette:

# Palette
LtoM <-colorRampPalette(c('red', 'yellow' ))
Mid <- "snow3"
MtoH <-colorRampPalette(c('lightgreen', 'darkgreen'))

that is called by:

scale_fill_gradient2(low = LtoM(100), mid = Mid, high = MtoH(100))

Now I would like to use a similar color palette for my barplot, that is I would like the color in each bar to be a function of the height (some grade from red for mimimum y to green for maximum y).

How can I do that, please?

1条回答
放我归山
2楼-- · 2019-04-28 20:53

You're basically there with your current code. Just add the scale_fill_gradient function.

bar <- ggplot(data = df, aes(x = factor(dat, levels = month.abb), y = val, 
              fill=val)) +
       geom_bar(stat = 'identity') + 
       scale_fill_gradient2(low=LtoM(100), mid='snow3', 
       high=MtoH(100), space='Lab')

custom colors

However, allowing scale_fill_gradient2 to take care of the gradient-ing works pretty well

bar <- ggplot(data = df, aes(x = factor(dat, levels = month.abb), y = val, 
              fill=val)) + 
       geom_bar(stat = 'identity') + 
       scale_fill_gradient2(low='red', mid='snow3', high='darkgreen', space='Lab')

generated colors

查看更多
登录 后发表回答