【问题标题】:remove x axis labels for ggplot2?删除 ggplot2 的 x 轴标签?
【发布时间】:2018-06-13 11:43:00
【问题描述】:

给出以下数据:

    data2 <- list(structure(list(super_group = c(1,1), Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(65, 75), Pr2 = c(54, 88), Prh = c(25, 5), SE = c(25, 75 )), row.names = c(NA, -2L), class = "data.frame"), NULL, structure(list(super_group = c(3,3), Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(81,4), Pr2 = c(66, 57),Prh = c(3,3), SE = c(8, 9)), row.names = c(NA,
-2L), class = "data.frame"))

使用 ggplot2 绘图:

 data2 %>%
 bind_rows() %>%
 ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
 geom_bar(stat = "identity") +
 facet_grid(. ~ super_group)

-您在 x 轴上看到 C 和 D 标签,这是不必要的。所以我想删除它们并减小条的宽度。有什么想法吗?

-我们可以将 1 和 3 从 x 轴顶部移动到 x 轴底部吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我们可以使用switch 参数到facet_grid 来更改构面标签的位置。
    参数axis.text.xaxis.ticks.x 控制文本并在x 轴上打勾。要删除它们,请将它们声明为 element_blank()

    library(tidyverse)
    data2 %>%
      bind_rows() %>%
      ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
      geom_bar(stat = "identity") +
      facet_grid(. ~ super_group, switch = "x") +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank()) -> p1
    

    要更改图形的比例,请以不同的尺寸保存它。示例:

    ggsave("p1.pdf", plot = p1, device = "pdf", width = 3, height = 5)
    

    或者如果使用knitr,通过定义更改块选项:

    fig.width=3, fig.height=5 例如:

    ```{r p1, fig.width=3, fig.height=5}  
    data2 %>%
          bind_rows() %>%
          ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
          geom_bar(stat = "identity") +
          facet_grid(. ~ super_group, switch = "x") +
          theme(axis.text.x = element_blank(),
                axis.ticks.x = element_blank())
    ``` 
    

    并使用参数width更改条的宽度:

    data2 %>%
      bind_rows() %>%
      ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
      geom_bar(stat = "identity", width = 0.5) +
      facet_grid(. ~ super_group, switch = "x") +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank())
    

    另一种选择(基于 cmets 在我看来这是想要的)是更改 expand:

    data2 %>%
      bind_rows() %>%
      ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
      geom_bar(stat = "identity") +
      facet_grid(. ~ super_group, switch = "x") +
      scale_x_discrete(expand = c(1,1))+
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank())
    

    【讨论】:

    • 实际上我指的是图中条形的宽度,而不是图的宽度。
    • 使用expand 添加了另一种方式。请检查编辑。
    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2020-05-21
    • 1970-01-01
    • 2023-02-24
    相关资源
    最近更新 更多