ggplot2 + facet_:某些构面的反转轴? [英] ggplot2 + facet_: Reverse axes for some facets?

查看:67
本文介绍了ggplot2 + facet_:某些构面的反转轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将三个子图放到一个图中,而刻面将是一种很自然的方法.但是,使用反转的x轴阅读这些子图中的一个会更容易/更自然(而我想不理会其他子图).有没有办法使用facet_grid()或facet_wrap()完成此操作?

我考虑过的另一个替代方法是grid.arrange(),我遇到的主要问题是让它根据绘图区域(在轴内)而不是基于边缘对齐子图.的图像.(我的轴标题和标签的大小不同,因此默认行为相当丑陋.)

编辑后添加了MWE ,其中包含一些用于上下文的数据.在这里,由于对于β和R平方子图,越大"越好,因此反转p子图的轴会更自然.(在这种情况下,将对数变换添加到该比例可能会更好,但是我真正的问题不需要那么花哨.)

  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(字母[1:15],3))绘图<-ggplot(df)+ geom_point(aes(x = x,y = y))+ facet_grid(.〜z,scales ="free_x",switch ="x") 

解决方案

以下是使用

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")

解决方案

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

这篇关于ggplot2 + facet_:某些构面的反转轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆