本文介绍了自定义背景以突出显示ggplot中的数据范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想在我的ggplot中设置背景颜色来突出显示数据范围。特别是,我想用绿色, [ - 0.25,-0.1)突出显示 [ - 0.1,0.1] >和(0.1,0.25)换成橙色。换句话说,我需要的是带有一些透明度的酒吧,其y-限制是图的y范围,限制是由我设定的。 理想情况下,我想要对 coord_cartesian(...)(如设置 vline(...,size = X)会)此外,如果有独立于任何数据的东西,并且完全基于plot坐标,我尝试了 geom_segment ,但我无法确定如何设置可以工作的宽度。 library(ggplot2)x< -c(seq(-1,1,by = .001))y< - rnorm(length(x)) df ggplot(df,aes(x,y))+ geom_point(aes(y * = abs(x)),alpha = .2,size = 5)+ theme_bw()+ coord_cartesian(xlim = c( - 。5,.5),ylim = c(-1, 1)) 解决方案您可以使用 geom_rect()并设置 ymin 和 ymax 值改为 -Inf 和 Inf 。但根据@sc_evens回答这个问题您必须将 data 和 aes()移动到 geom_point() code>,并保留 ggplot()空以确保 geom_rect的 alpha = ()按预期工作。 ggplot()+ geom_point(data = df ,aes(x = y * abs(x),y = y),alpha = .2,size = 5)+ geom_rect(aes(xmin = -0.1,xmax = 0.1,ymin = -Inf,ymax (x = -0.25,xmax = -0.1,ymin = -Inf,ymax = Inf),alpha = 0.1,fill =inf,alpha = 0.1,fill =green)+ geom_rect橙色)+ geom_rect(aes(xmin = 0.1,xmax = 0.25,ymin = -Inf,ymax = Inf),alpha = 0.2,fill =orange)+ theme_bw()+ coord_cartesian(xlim = c( - 。5,.5),ylim = c(-1,1)) I want to set background colors in my ggplot to highlight ranges of data. Particularly, I want to highlight [-0.1,0.1] with, say, green,[-0.25,-0.1) and (0.1,0.25] with orange. In other words, what I need are bars with some alpha-transparency whose y-limits are the plot's y range, and x-limits are set by me. Ideally, I would want something that would not be sensitive to coord_cartesian(...) (as setting vline(...,size = X) would). Additionally, it would be nice to have something independent from any data, and based solely on plot coordinates. I tried geom_segment, but I could not figure it our how to set a width that would work.library(ggplot2)x <- c(seq(-1, 1, by = .001))y <- rnorm(length(x))df <- as.data.frame(x=x,y=y)ggplot(df,aes(x,y)) + geom_point(aes(y*abs(x)),alpha=.2,size=5) + theme_bw() + coord_cartesian(xlim = c(-.5,.5),ylim=c(-1,1)) 解决方案 You can add the "bars" with geom_rect() and setting ymin and ymax values to -Inf and Inf. But according to @sc_evens answer to this question you have to move data and aes() to geom_point() and leave ggplot() empty to ensure that alpha= of geom_rect() works as expected.ggplot()+ geom_point(data=df,aes(x=y*abs(x),y=y),alpha=.2,size=5) + geom_rect(aes(xmin=-0.1,xmax=0.1,ymin=-Inf,ymax=Inf),alpha=0.1,fill="green")+ geom_rect(aes(xmin=-0.25,xmax=-0.1,ymin=-Inf,ymax=Inf),alpha=0.1,fill="orange")+ geom_rect(aes(xmin=0.1,xmax=0.25,ymin=-Inf,ymax=Inf),alpha=0.2,fill="orange")+ theme_bw() + coord_cartesian(xlim = c(-.5,.5),ylim=c(-1,1)) 这篇关于自定义背景以突出显示ggplot中的数据范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-27 14:47