【问题标题】:How to avoid ggplot to split the expression "N = x" in the axis text如何避免ggplot在轴文本中拆分表达式“N = x”
【发布时间】:2020-11-13 11:35:10
【问题描述】:

我对 R 的经验很少,我必须使用 ggplot 从一些使用 knime 创建的数据集自动创建一个图形,这些数据集的轴文本 (x=specie) 的字母数量可能会有所不同。我为此文本设置了最大宽度 (30)。问题是在这篇文章的末尾我总是有“..., N = x”这个表达式。因为它之间有两个空格,这取决于我可以遇到的文本长度:

........, N
        = x

有没有办法强制表达式“N = x”总是在同一行?

我的代码是这样的:

library(ggplot2)
library(stringr)


ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(color="black", position="stack", stat="identity", width = 4,)+
  scale_fill_manual(values = c("#990000", "#FF3300","#FFCC33","#FFFF99", "#FFFFFF","#99CC99") )+
  coord_flip()+
  scale_x_discrete(limits=data$specie, labels = function(x) str_wrap(str_replace_all(x, "foo" , " "),
                                                 width = 30))+
  labs(fill = " ", y= "Anteil Isolate (%)", x = "Programm")+ theme_minimal()+
  theme(legend.position = "bottom", legend.direction = "horizontal", legend.key.size = unit(0.5, "cm"), legend.text=element_text(size=12),
  legend.key.width = unit(0.5,"cm"), axis.text=element_text(size=12, color="black"), axis.title.y=element_blank(),
        axis.title=element_text(size=13, face="bold"), panel.grid.major.y = element_blank())+
  guides(fill = guide_legend(nrow = 1, byrow = TRUE,reverse=TRUE))

【问题讨论】:

  • 我不确定N = x 来自哪里,但也许你可以str_replace_all(x, "N = ", "N\u00a0=\u00a0")\u00a0non-breaking space character
  • 我不知道那个空格字符!非常感谢!它工作得很好! :-)

标签: r ggplot2 knime


【解决方案1】:

您可以将= 符号周围的空格替换为non-breaking spaces (\u00a0),这样可以防止这些地方出现换行符。像这样的东西应该可以工作:str_replace_all(x, "N = ", "N\u00a0=\u00a0")

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多