R ggplot facet_wrap 有条件
R ggplot facet_wrap with conditions
我可以更改分面某些值的背景吗?
我在分面图中有 50 个图。我想知道我是否可以通过更改所选图的背景来突出显示其中的一些内容。
具体来说,下图就是我的ggplot结果吧。我想通过将背景着色为浅蓝色来突出显示 37 和 42。
我考虑过使用 ifelse
。但是我不确定如何定义控制流。
下面是我的代码
axr_treat_ctrl %>%
ggplot(aes(x= year, y= mtopic,colour= Type,group=Type))+
geom_line( )+
geom_point( size= 1) +
scale_y_continuous(breaks = extended_breaks(n = 5) )+
scale_x_continuous(breaks = extended_breaks(n = 10) )+
geom_vline(xintercept = 2005,linetype=2,color= "brown")+
geom_vline(xintercept = c(2010,2011,2017),linetype=3,color= "blue")+
labs(x= "x-axis",
y ="y-axis ")+
facet_wrap(~topicr )+
guides(x = guide_axis(angle = 90))+
theme(legend.position = "bottom")
# ifelse ( topicr==37, call( expr(panel.background = element_rect(fill = "lightblue"))),
# call( expr( panel.background = element_rect(fill = "white") ))) )
我认为最好的方法是直接操作数据框,axr_treat_ctrl
。这是一个简单的单独示例,因为您的示例不可重现。
library(ggplot2)
mtcars <- data.frame(mtcars)
mtcars$mazda <- ifelse(grepl("Mazda",rownames(mtcars)),1,0)
ggplot(mtcars,aes(x=wt,y=mpg)) +
geom_rect(aes(fill=mazda),xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf,alpha=0.2) +
geom_point() +
facet_wrap(~rownames(mtcars)) +
theme(legend.position="none")
在这个例子中,我想为每辆汽车制作一个单独的图,然后用马自达汽车为背景着色。因此,我添加了一个名为 mazda
的简单二进制指示符变量,用于确定观测值是否为马自达汽车。然后我将 mazda
变量传递给 geom_rect
。输出:
根据@camille 的评论删除了图例。您也可以通过 fill=factor(mazda)
而不是仅 mazda
来获得离散的图例,具体取决于您要查找的内容。
我可以更改分面某些值的背景吗?
我在分面图中有 50 个图。我想知道我是否可以通过更改所选图的背景来突出显示其中的一些内容。
具体来说,下图就是我的ggplot结果吧。我想通过将背景着色为浅蓝色来突出显示 37 和 42。
我考虑过使用 ifelse
。但是我不确定如何定义控制流。
下面是我的代码
axr_treat_ctrl %>%
ggplot(aes(x= year, y= mtopic,colour= Type,group=Type))+
geom_line( )+
geom_point( size= 1) +
scale_y_continuous(breaks = extended_breaks(n = 5) )+
scale_x_continuous(breaks = extended_breaks(n = 10) )+
geom_vline(xintercept = 2005,linetype=2,color= "brown")+
geom_vline(xintercept = c(2010,2011,2017),linetype=3,color= "blue")+
labs(x= "x-axis",
y ="y-axis ")+
facet_wrap(~topicr )+
guides(x = guide_axis(angle = 90))+
theme(legend.position = "bottom")
# ifelse ( topicr==37, call( expr(panel.background = element_rect(fill = "lightblue"))),
# call( expr( panel.background = element_rect(fill = "white") ))) )
我认为最好的方法是直接操作数据框,axr_treat_ctrl
。这是一个简单的单独示例,因为您的示例不可重现。
library(ggplot2)
mtcars <- data.frame(mtcars)
mtcars$mazda <- ifelse(grepl("Mazda",rownames(mtcars)),1,0)
ggplot(mtcars,aes(x=wt,y=mpg)) +
geom_rect(aes(fill=mazda),xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf,alpha=0.2) +
geom_point() +
facet_wrap(~rownames(mtcars)) +
theme(legend.position="none")
在这个例子中,我想为每辆汽车制作一个单独的图,然后用马自达汽车为背景着色。因此,我添加了一个名为 mazda
的简单二进制指示符变量,用于确定观测值是否为马自达汽车。然后我将 mazda
变量传递给 geom_rect
。输出:
根据@camille 的评论删除了图例。您也可以通过 fill=factor(mazda)
而不是仅 mazda
来获得离散的图例,具体取决于您要查找的内容。