[英]apply ggplot color scale gradient to portion of data
我对应用ggplot的色阶渐变有疑问。 我有一个数据集,其中响应变量是包括正数和负数的连续变量,而自变量是多个独立站点。 我试图以一种可以在背景中绘制所有数据的方式绘制数据,然后将色阶渐变应用于覆盖数据负范围的响应数据。 到目前为止,这是我的示例数据集,它模仿了我的实际数据集的结构。
tr_sim <- data.frame(site_id = seq(1,100,1), estimated_impact =
rnorm(100,18,200), impact_group = rep(c(1,2),each = 50))
rng_full <- range(tr_sim$estimated_impact)
#produce plot showing the full range of impacts across all sites and then
over the subsetted sites
impact_plot_full <- ggplot(data = tr_sim, aes(x = factor(site_id, levels =
site_id[order(estimated_impact)]), y = estimated_impact)) +
geom_bar(stat = "identity",width = 1, fill = "grey80")
impact_plot_full
impact_plot_full +
geom_bar(stat = "identity", width = 1, position = "stack", aes(y =
estimated_impact[impact_group == 1])) +
scale_fill_gradient2(low="firebrick", mid="yellow", high = "green4") +
labs(y = "Estimated Impact ($/week)", x = "Total number of sites with estimate
is 100", title = "Sites with the greatest impact after coverage loss") +
theme(axis.text.x = element_blank()) +
scale_y_continuous(breaks =
round(seq(rng_full[1],rng_full[2],by=100),digits=0))
我可以将背景中的所有数据绘制成灰色,并尝试在此之上绘制响应数据的负范围。 我得到一个错误,即“美学必须为1或与data(100),y,x相同”。 我知道发生这种情况是因为负数数据的长度与整个数据集的长度不同,但是我想不出办法。 任何建议将不胜感激。
谢谢柯蒂斯
您需要对数据进行子集化,并使用geom_bar
fill
aes()
。
impact_plot_full +
geom_bar(data = subset(tr_sim, estimated_impact < 0),
stat = "identity",
aes(y = estimated_impact, fill = estimated_impact)) +
scale_fill_gradient2(low = "firebrick", mid = "yellow", high =
"green4") +
theme(axis.text.x = element_blank()) +
xlab("site_id")
希望这就是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.