Highlight / Draw a box around some of the plots when using `facet_grid` in ggplot2

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-19 05:01:32

问题


I am creating a matrix of plots similar to

ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(rows = vars(cyl), cols = vars(drv))

Now, I would like to have some way to highlight some of the individual plots, say the ones where cyl is 5 or 6, and drv is f. So, ideally, this might look like this:

But I would also be happy with those panels having a different look by setting ggtheme to classic or similar.

However, it is very unclear to me how I can modify individually selected plots within a matrix of plots generated via facet_grid


回答1:


From @joran answer found here, this is what I get :

[EDIT] code edited to select multiple facets

    if(!require(tidyverse)){install.packages("tidyverse")}
    library(tidyverse)

    #dummy dataset

    df = data.frame(type = as.character(c("a", "b", "c", "d")),
                    id = as.character(c("M5", "G5", "A7", "S3")),
                    val = runif(4, min = 1, max = 10),
                    temp = runif(4))

    # use a rectangle to individually select plots
ggplot(data = df, aes(x = val, y = temp)) + 
  geom_point() +
  geom_rect(data = subset(df, type %in% c("b", "c") & id %in% c("A7","G5")), 
                          fill = NA, colour = "red", xmin = -Inf,xmax = Inf,
            ymin = -Inf,ymax = Inf) +
  facet_grid(type~id)

It does not use theme() but it seems simple enough to highlight some facets.



来源:https://stackoverflow.com/questions/58336449/highlight-draw-a-box-around-some-of-the-plots-when-using-facet-grid-in-ggplo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!