问题描述
我进行了搜索,但是似乎找不到一种优雅的方式!
I have searched and searched, but I cant seem to find an elegant way of doing this!
我有一个数据集Data
,由Data$x
(日期)和Data$y
(数字从0到1)组成
I have a dataset Data
consisting of Data$x
(dates) and Data$y
(numbers from 0 to 1)
我想将它们绘制在条形图中:
I want to plot them in a bar-chart:
ggplot(Data) + geom_bar(aes(x = x, y = y, fill = y, stat = "identity")) +
scale_fill_gradient2(low = "red", high = "green", mid = "yellow", midpoint = 0.90)
结果看起来像这样
但是,我想给每个条在垂直方向上设置一个从0(红色)到y(取决于y的绿色)范围的渐变.有什么办法可以顺利地做到这一点?
However, I wanted to give each bar a gradient in the vertical direction ranging from 0 (red) to y (greener depending on y). Is there any way of doing this smoothly?
我试图查看是否可以将图片强加给黑客,但是我不能将其强加给酒吧,除非是超级丑陋的方式.
I have tried to see if I could impose a picture on the graph as a hack, but I can't impose it on the bars only except in a super super ugly way.
推荐答案
另一种(不是很漂亮)使用geom_segment
进行黑客入侵. x的开始和结束位置(x
和xend
)被硬编码(- 0.4
; + 0.4
),size
也是如此.这些数字需要根据x值的数量和y的范围进行调整.
Another, not very pretty, hack using geom_segment
. The x start and end positions (x
and xend
) are hardcoded (- 0.4
; + 0.4
), so is the size
. These numbers needs to be adjusted depending on the number of x values and range of y.
# some toy data
d <- data.frame(x = 1:3, y = 1:3)
# interpolate values from zero to y and create corresponding number of x values
vals <- lapply(d$y, function(y) seq(0, y, by = 0.01))
y <- unlist(vals)
mid <- rep(d$x, lengths(vals))
d2 <- data.frame(x = mid - 0.4,
xend = mid + 0.4,
y = y,
yend = y)
ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
geom_segment(size = 2) +
scale_color_gradient2(low = "red", mid = "yellow", high = "green",
midpoint = max(d2$y)/2)
一个有点相关的问题,可能会给您一些其他想法:
A somewhat related question which may give you some other ideas: How to make gradient color filled timeseries plot in R
这篇关于为geom_bar图创建垂直颜色渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!