如何在 ggplot2 R 中添加辅助轴刻度标签?

问题描述 投票:0回答:1
df <- data.frame (yaxis = rnorm(120,5,1),
                  xaxis = rep(c("A - S. longishname","B - S. longishname","C - S. longishname","A - S. short","B - S. short", "B - S. med"), 20))
                  
ggplot(df, aes(x = xaxis, y  = yaxis)) + geom_point()+ theme_classic() + scale_x_discrete(labels=expression(italic("A - "),italic("B - "),italic("C - "),italic("A - "),italic("B - "), italic("B - ")))  #+ scale_x_discrete(labels=expression(italic("S. longishname"),italic("S. short"),italic("S. med"))) 

代码输出:

我想要什么: Primarily:次要标签,即每几个物种都通用的短语 如果可能的话,括号如下所示(具有足够垂直空间的轴标签是第一优先级)

r ggplot2 axis-labels x-axis
1个回答
0
投票

您可以使用

facet_wrap
将面板添加到您的绘图中,这些面板可以充当辅助标签。

library(ggplot2)
library(dplyr)

# set seed, since using rnorm
set.seed(123)

df <- data.frame (yaxis = rnorm(120,5,1),
                  xaxis = rep(c("A - S. longishname","B - S. longishname","C - S. longishname","A - S. short","B - S. short", "B - S. med"), 20))

# create sublabels and remove unnecessary substr
df <- df |> 
  mutate(
    sublabels = case_when(grepl("longishname", xaxis) ~ "S. longishname",
                          grepl("short", xaxis) ~ "S. short",
                          grepl("med", xaxis) ~ "S. med"
    ),
    # reorder sublabels
    sublabels = factor(x = sublabels, levels = c("S. longishname", "S. short", "S. med")),
    # remove S. short, S. med, S. longishname from xaxis
    xaxis_processed = gsub("S. (short|med|longishname)", "", xaxis)
  )

# plot using facet_wrap
df |> 
  ggplot(aes(x = xaxis_processed, y = yaxis)) + 
  geom_point()+ 
  theme_classic() +
  facet_wrap(~sublabels, strip.position = "bottom", scales = "free_x")

© www.soinside.com 2019 - 2024. All rights reserved.