ggplot2:条形图,其颜色是y轴值的函数 [英] ggplot2: barplot with colors as a function of y-axis value
问题描述
我有这个简单的代码(数据+条形图):
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)
在其他地方,我使用以下调色板创建了热图:
# Palette
LtoM <-colorRampPalette(c('red', 'yellow' ))
Mid <- "snow3"
MtoH <-colorRampPalette(c('lightgreen', 'darkgreen'))
调用者:
scale_fill_gradient2(low = LtoM(100), mid = Mid, high = MtoH(100))
现在,我想为条形图使用类似的调色板,也就是说,我希望每个条形中的颜色是高度的函数(某种等级,从红色(最小y)到绿色(最大y)). /p>
请问我该怎么做?
您的当前代码基本上就在那儿.只需添加scale_fill_gradient函数.
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')
但是,允许scale_fill_gradient2照顾渐变效果很好
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')
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?
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')
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')
这篇关于ggplot2:条形图,其颜色是y轴值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!