如何网格化面板图,使其在 R 中的 ggplot 中具有分类变量和不同的 x 变量

Posted

技术标签:

【中文标题】如何网格化面板图,使其在 R 中的 ggplot 中具有分类变量和不同的 x 变量【英文标题】:how to grid panel plots such that they have categorical variables and different x variables in ggplot in R 【发布时间】:2021-12-03 03:08:16 【问题描述】:

我的实际数据类似于下面的数据。我的代码正在生成两个单独的图,如下图中的两个顶部图。但我希望它们在一个情节中,就像图片中的底部情节一样。

data(Salaries, package = "carData")
Salaries <- Salaries[1:15,]
Salaries$name <- c("Jim","Alex","Ray","Dog","Kim",
                   "Michael","Mike","Adrian","Claire","Lucy",
                   "Fray","Lucas","Crraig","Anthony","Harper")
Salaries <- Salaries[order(Salaries$yrs.since.phd), ]
ggplot(Salaries, aes(x = yrs.since.phd , y=reorder(name, yrs.since.phd)))+
  geom_point(size = 3, aes(colour = sex))+
  facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y")+
  theme(legend.position = "none")

Salaries <- Salaries[order(Salaries$salary), ]
ggplot(Salaries, aes(x = salary , y=reorder(name, salary)))+
  geom_point(size = 3, aes(colour = sex))+
  facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y")+
  theme(legend.position = "none")

我不知道该怎么做。感谢您对此提供的任何帮助。

【问题讨论】:

【参考方案1】:

我希望这是你想要的

  library(ggplot2)
  library(gtable)
  library(grid)
  library(gridExtra)
  
  data(Salaries, package = "carData")
  Salaries <- Salaries[1:15,]
  Salaries$name <- c("Jim","Alex","Ray","Dog","Kim",
                     "Michael","Mike","Adrian","Claire","Lucy",
                     "Fray","Lucas","Crraig","Anthony","Harper")
  Salaries <- Salaries[order(Salaries$yrs.since.phd), ]
  p1=ggplot(Salaries, aes(x = yrs.since.phd , y=reorder(name, yrs.since.phd)))+
    geom_point(size = 3, aes(colour = sex))+
    facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y")+
    theme(legend.position = "none",strip.text.y = element_blank())
  
  Salaries <- Salaries[order(Salaries$salary), ]
  p2=ggplot(Salaries, aes(x = salary , y=reorder(name, salary)))+
    geom_point(size = 3, aes(colour = sex))+
    facet_grid(rows = vars(sex), scales = "free_y" ,space = "free_y")+
    theme(axis.text.y = element_blank(), 
          axis.ticks.y = element_blank(), 
          axis.title.y = element_blank(),
          plot.background = element_blank(),
          legend.position = "none")
  gt1 <- ggplotGrob(p1)
  gt2 <- ggplotGrob(p2)
   
  grid.arrange(gt1, gt2, ncol=2)

我的参考来自Getting rid of facet_grid labels on those gray boxes?。

【讨论】:

以上是关于如何网格化面板图,使其在 R 中的 ggplot 中具有分类变量和不同的 x 变量的主要内容,如果未能解决你的问题,请参考以下文章

将刻面ggplots(facet_wrap)与R中的cowplot对齐

如何在第二个 Tailwind CSS 网格列中左对齐内容,使其在所有屏幕尺寸下都保持与第一列之间的间隙?

R 中牛图网格的一个共享图例

R语言可视化包ggplot2包使用facet_wrap绘制多面板图(子图)实战

ggplot 在同一面板中组合线和区域(平面网格)

在 R 中的网格中模拟二维随机游走并使用 ggplot 绘图