如何在ggplot中缩短x轴标签文本?

8
我正在使用ggplot制作一个图表,其中x轴标签包含不同蛋白质的名称。由于某些名称过长,标签变得过大,导致很难看到整个图表。除了“打印”更大的图表外,有没有减少x轴标签中字符数量的方法?以下是一个示例,展示了我的问题:
library(ggplot2)
dat <- mtcars
# Make the x-axis labels very long for this example
dat$car <- paste0(rownames(mtcars),rownames(mtcars),rownames(mtcars),rownames(mtcars))

ggplot(dat, aes (x=car,y=hp)) +
    geom_bar(stat ="identity", fill="#009E73",colour="black") +
    theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

我希望将标签从以下形式转换为另一种形式:
Thisisaveryveryveryloooooongprotein

到这里

Thisisavery[...]   

为了使我的图表始终可见

2个回答

15

尝试使用abbreviate函数:

qplot(Species, Sepal.Length, data=iris, geom="boxplot") +
  scale_x_discrete(label=abbreviate)

标签缩写示例

如果默认设置不适用于您的情况,您可以定义自己的函数:

qplot(Species, Sepal.Length, data=iris, geom="boxplot") +
  scale_x_discrete(label=function(x) abbreviate(x, minlength=7))
你可以尝试旋转标签。

9

由于abbreviate函数是通过从字符串中删除空格和小写元音字母来缩写字符串的,因此可能会导致一些奇怪的缩写。在许多情况下,最好的做法是截断标签。

您可以通过将任何字符串截断函数传递给scale_*函数的label=参数来实现这一点:一些很好的函数包括stringr::str_trunc和基本R中的strtrim

mtcars$name <- rownames(mtcars)

ggplot(mtcars, aes(name, mpg)) +
    geom_col() +
    scale_x_discrete(label = function(x) stringr::str_trunc(x, 12)) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接