ggplot2 + facet_: Reverse axes for some facets?

眉间皱痕 提交于 2019-12-24 08:58:18

问题


I've got three subplots I want to put together into one plot, and faceting would be a natural way to do it. However, one of these subplots would be easier/more natural to read with a reversed x-axis (whereas I'd like to leave the others alone). Is there a way to accomplish this using facet_grid() or facet_wrap()?

The other alternative I've considered is grid.arrange(), and the chief problem I've run into there is getting it to align the subplots based on plot area (inside the axes), rather than based on the edges of the images. (My axis titles and labels are not the same size, so the default behavior is fairly ugly.)

Edited to add a MWE with some data for context. Here, since larger is "better" for the beta and R-squared subplots, it would be more natural to reverse the axis for the p subplot. (In this case it would probably also be better to add the log transform to that scale, but my real problem doesn't need to get that fancy.)

df <- data.frame(z=c(rep("R-squared",15),rep("p",15),rep("beta",15)),
                 x=c(runif(15),exp(-runif(15,1,10)),rnorm(15,1,0.5)),
                 y=rep(letters[1:15],3))
plot <- ggplot(df) + geom_point(aes(x=x,y=y)) + facet_grid(.~z, scales="free_x", switch="x")

回答1:


Here's a solution using patchwork

library(ggplot2)
library(dplyr)
df <- data.frame(z=c(rep("R-squared",15),rep("p",15),rep("beta",15)),
                 x=c(runif(15),exp(-runif(15,1,10)),rnorm(15,1,0.5)),
                 y=rep(letters[1:15],3))

p1 <- ggplot(filter(df, z == "beta"), aes(x, y)) +
  geom_point() 

p2 <- ggplot(filter(df, z == "p"), aes(x, y)) +
  geom_point() +
  scale_x_reverse() +
  theme(axis.title.y = element_blank(),
        axis.text.y  = element_blank(),
        axis.ticks.y = element_blank())

p3 <- ggplot(filter(df, z == "R-squared"), aes(x, y)) +
  geom_point() +
  theme(axis.title.y = element_blank(),
        axis.text.y  = element_blank(),
        axis.ticks.y = element_blank())

#devtools::install_github("thomasp85/patchwork")
library(patchwork)
p1 + p2 + p3



来源:https://stackoverflow.com/questions/48331168/ggplot2-facet-reverse-axes-for-some-facets

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