【问题标题】:Label every n-th x-axis tick on boxplot在箱线图上标记每个第 n 个 x 轴刻度
【发布时间】:2020-07-10 17:31:17
【问题描述】:

我想从geom_boxplot (ggplot) 中删除每个第 n 个 x 轴刻度标签。

以这个虚拟数据框为例:

Lat <- c(rep(50.70,3), rep(51.82,3), rep(52.78,3), rep(56.51,3))
y <- c(seq(1,2, by=0.5), seq(1,3, by=1), seq(2,6,by=2), seq(1,5,by=2))
df <- as.data.frame(cbind(Lat, y))

我可以像这样制作ggplot 箱线图:

box_plot <- ggplot(df, aes(x=as.factor(Lat), y=y))+
  geom_boxplot()+
  labs(x="Latitude")+
  scale_y_continuous(breaks = pretty_breaks(n=6)) +
  theme_classic()
box_plot

但是我想从中间两个盒子中删除标签。

我知道我可以通过将标签更改为空白来实现这一点(如下所示)。 但是,我的真实数据框有超过 4 个滴答声,所以这会很耗时,更不用说人为错误!

box_plot2 <- ggplot(df, aes(x=as.factor(Lat), y=y))+
  geom_boxplot()+
  labs(x="Latitude")+
  scale_y_continuous(breaks = pretty_breaks(n=6)) +
  scale_x_discrete(labels=c("50.70", " ", " ", "56.51"))+
  theme_classic()
box_plot2

有没有一种无需手动设置标签即可生成上述图的方法?

例如,在 x 轴上每隔 n 个刻度标记一次?

提前致谢!

【问题讨论】:

    标签: r ggplot2 boxplot


    【解决方案1】:

    这样就可以实现了。作为一个例子,我只是绘制“每”第三个刻度。基本思想是为因子水平添加一个索引。然后,此索引可用于指定要绘制的中断或刻度。试试这个:

    Lat <- c(rep(50.70,3), rep(51.82,3), rep(52.78,3), rep(56.51,3))
    y <- c(seq(1,2, by=0.5), seq(1,3, by=1), seq(2,6,by=2), seq(1,5,by=2))
    df <- as.data.frame(cbind(Lat, y))
    
    library(ggplot2)
    library(scales)
    library(dplyr)
    
    df <- df %>% 
      mutate(Lat1 = as.factor(Lat),
             Lat1_index = as.integer(Lat1))
    
    # Which ticks should be shown on x-axis
    breaks <- df %>% 
      # e.g. plot only every third tick
      mutate(ticks_to_plot = Lat1_index %% 3 == 0) %>% 
      filter(ticks_to_plot) %>% 
      pull(Lat1)
    
    box_plot2 <- ggplot(df, aes(x=Lat1, y=y))+
      geom_boxplot()+
      labs(x="Latitude")+
      scale_y_continuous(breaks = pretty_breaks(n=6)) +
      scale_x_discrete(breaks = breaks)+
      theme_classic()
    box_plot2
    

    reprex package (v0.3.0) 于 2020 年 3 月 30 日创建

    【讨论】:

    • 太棒了,非常感谢!我如何让它绘制第一个然后每第三个刻度?
    • 试试mutate(ticks_to_plot = (Lat1_index - 1) %% 3 == 0)
    • 对不起@stefan 很痛苦有没有办法强制它也标记最后一个刻度?
    • (: 不客气。试试mutate(ticks_to_plot = ((Lat1_index - 1) %% 3 == 0) | (Lat1_index == n_distinct(Lat1_index)))。现在将标记第一个、每三分之一和最后一个刻度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多