我试图绘制自火灾以来每年出现的幼苗数量。幼苗数量在y轴上,火灾在x轴上的年数。我想在这个图下面添加一个方框或矩形,显示每年变化的另一个变量(比如降雨量)的值。像这样:
我设法通过每年为geom_rect()
添加一个单独的矩形来实现这一目标,但有没有办法在没有10个单独的矩形的情况下执行此操作?特别是我只需要指定一次颜色修改,而不是在geom_rect()
??
这两个(one,two)较旧的帖子帮助我了解了我现在所处的位置,但我想在几行代码中完成此操作。我无法让scale_fill_gradient()
工作,但也许这是解决方案的一部分?
数据:
yr_since <- c(1:10)
density <- c(23, 58, 68, 126, 154, 103, 90, 94, 73, 59)
rain <- c(3, 6, 8, 5, 8, 3, 4, 4, 6, 2)
data <-as.data.frame(cbind(yr_since, density, rain))
此处的当前(可怕)代码:
plot <- ggplot(data = data, aes(x = yr_since)) +
geom_col(aes(y=density), width = 0.95) +
scale_x_discrete(expand = c(0,0), drop=FALSE, labels = yr_since) +
labs(x = "Years since fire", y = "Density (stems/ha)")
plot +
geom_rect(data=data,
aes(xmin = 0.5, ymin = -5,
xmax = 1.5, ymax = 0,
fill = rain[1])) +
geom_rect(data=data,
aes(xmin = 1.5, ymin = -5,
xmax = 2.5, ymax = 0,
fill = rain[2])) +
geom_rect(data=data,
aes(xmin = 2.5, ymin = -5,
xmax = 3.5, ymax = 0,
fill = rain[3])) +
geom_rect(data=data,
aes(xmin = 3.5, ymin = -5,
xmax = 4.5, ymax = 0,
fill = rain[4])) +
geom_rect(data=data,
aes(xmin = 4.5, ymin = -5,
xmax = 5.5, ymax = 0,
fill = rain[5])) +
geom_rect(data=data,
aes(xmin = 5.5, ymin = -5,
xmax = 6.5, ymax = 0,
fill = rain[6])) +
geom_rect(data=data,
aes(xmin = 6.5, ymin = -5,
xmax = 7.5, ymax = 0,
fill = rain[7])) +
geom_rect(data=data,
aes(xmin = 7.5, ymin = -5,
xmax = 8.5, ymax = 0,
fill = rain[8])) +
geom_rect(data=data,
aes(xmin = 8.5, ymin = -5,
xmax = 9.5, ymax = 0,
fill = rain[9])) +
geom_rect(data=data,
aes(xmin = 9.5, ymin = -5,
xmax = 10.5, ymax = 0,
fill = rain[10]))
答案 0 :(得分:1)
您可以进行额外的geom_col
来电添加,y
具有固定的负值:
library(ggplot2)
data <- data.frame(yr_since = c(1:10),
density = c(23, 58, 68, 126, 154, 103, 90, 94, 73, 59),
rain = c(3, 6, 8, 5, 8, 3, 4, 4, 6, 2))
ggplot(data, aes(x = yr_since, y = density)) +
geom_col(width = 0.95) +
geom_col(aes(y = -5, fill = rain), width = 1) +
scale_x_continuous(breaks = data$yr_since, expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0), limits = c(-5, max(data$density) * 1.05)) +
labs(x = "Years since fire",
y = "Density (stems/ha)")
随意调整。