【问题标题】:Wrap the axis text by the delimiter in ggplot用ggplot中的分隔符包装轴文本
【发布时间】:2019-09-04 20:45:11
【问题描述】:

我有我的数据:

new_df <-  structure(list(Group = c("k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella", 
"k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella", 
"k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella", 
"k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella"
), Percentile_0 = c(1, 1, 1, 22), Percentile_25 = c(1, 17.5, 
16.75, 37), Percentile_50 = c(1, 23, 29, 39), Percentile_75 = c(9, 
31.75, 33, 41.75), Percentile_100 = c(35, 47, 93, 50), Type = c("CC", 
"CCS", "CS", "SCS")), row.names = c(NA, -4L), class = "data.frame")

我的情节是这样的

library(stringr) # for strwrap
bp <- ggplot(data = new_df, aes(x = Group, group = Type, fill = Type)) +
  geom_boxplot(
    stat = "identity",
    aes(
      ymin = Percentile_0,
      lower = Percentile_25,
      middle = Percentile_50,
      upper = Percentile_75,
      ymax = Percentile_100
    )
  ) +
  theme_classic() +
  theme(axis.text.x=element_text(size=rel(0.45), angle=90))+
  labs(x="Taxa", y="Sequence abundance") 

我想换行 x 轴文本。我根据这个线程here 尝试了+ scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),这对我不起作用。如何用分隔符分号 ; 包裹轴文本?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我认为 str_wrap 需要一个空格来触发一个新行。这里我给每个分号加一个:

    new_df$Group = stringr::str_replace_all(new_df$Group, ";", "; ")
    
    ggplot(data = new_df, 
           aes(x = stringr::str_wrap(Group, 20), 
           group = Type, fill = Type)) +
    ....
    # clearer formatting for posting purposes
    theme(axis.text.x=element_text(size=rel(1), angle=0))+
    ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-25
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2018-03-10
      • 2018-05-03
      相关资源
      最近更新 更多