【问题标题】:Dividing ggplot in different 2 ggplot将ggplot划分为不同的2 ggplot
【发布时间】:2021-06-25 09:01:29
【问题描述】:

我有这个 ggplot :plot1

我已使用此代码获得了此图:

   g<- ggplot(base__, aes(x=Race_name, y=ec_prem, color=nouv_grp))+scale_color_brewer(palette = "Paired")+
  geom_jitter(position=position_jitter(0.2))+xlab("Course")+ylab("Ecart / 1er (secondes)")+ylim(-1,120)+labs(colour = "Groupe PC1")+theme_minimal()+theme(axis.text.x = element_text(size = 7, angle = 90))
g

我想将其分成 2 个图,以使可视化更易于理解。所以我用了facet_grid()

g=ggplot(base__, aes(x=Race_name, y=ec_prem, color=nouv_grp))+scale_color_brewer(palette = "Paired")+
  geom_jitter(position=position_jitter(0.2))+xlab("Course")+ylab("Ecart / 1er (secondes)")+ylim(-1,120)+labs(colour = "Groupe PC1")+theme_minimal()+theme(axis.text.x = element_text(size = 7, angle = 90))
g+facet_grid(haha~.)

我得到了这个情节:

plot2

但我想获得 2 个不同的 x 轴,并且我希望我的抖动图不那么集中(不那么紧)。

希望有人能给我解决办法。

提前致谢:)

【问题讨论】:

  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example
  • facet_grid() 在单个列中不能有单独的 x 轴。可能facet_wrap() 更适合。
  • 没有看到数据,我会说当然可以:试试facet_grid(haha~., scales = "free_y")

标签: r ggplot2 divide facet-wrap facet-grid


【解决方案1】:

正如 teunbrand 所提到的,facet_grid() 不允许对齐轴使用不同的比例(即一列中的统一 x,一行中的统一 y),但 facet_wrap() 可以帮助您解决这个问题。但是,为了让轴​​文本为每个方面打印,我认为 lemon::facet_rep_wrap() 是您需要的。请参阅下面的小示例。

library(tidyverse)
library(lemon)
#> 
#> Attaching package: 'lemon'
#> The following object is masked from 'package:purrr':
#> 
#>     %||%
#> The following objects are masked from 'package:ggplot2':
#> 
#>     CoordCartesian, element_render

mtcars %>%
  rownames_to_column(var = "car_name") %>%
  ggplot(aes(x = car_name, y = mpg)) +
  geom_col() +
  facet_rep_wrap(
    facets = vars(cyl),
    ncol = 1,
    repeat.tick.labels = TRUE,
    scales = "free"
  ) +
  theme(axis.text.x = element_text(
    angle = 90,
    hjust = 1,
    vjust = 0.5
  ))

reprex package (v1.0.0) 于 2021-03-29 创建

【讨论】:

  • 感谢 Dan Adams,我认为这是我需要的解决方案。我的数据框中与“car_name”对应的变量是“Race_name”,我收到此错误:“列名Race_name 不得重复。”我会试着看看有什么问题
猜你喜欢
  • 1970-01-01
  • 2016-05-25
  • 2021-02-11
  • 1970-01-01
  • 2018-06-06
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多