Ggplot:如何减少x标签文本

use*_*731 4 string label r ggplot2

我用以下代码制作了一个图表:

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))
Run Code Online (Sandbox Code Playgroud)

在x轴上表示不同蛋白质的名称,当这个名称太长时我会遇到麻烦,因为在图形中只看到名称而不是图形.有没有办法减少X标签字符串的字符,而不是"打印"更大的图形?

像这样的东西:

Thisisaveryveryveryloooooongprotein - > Thisisavery [...]

谢谢!

div*_*san 7

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

您可以通过将任何字符串截断函数传递给函数的label=参数来完成此操作scale_*:一些好的函数是stringr::str_trunc和基 Rstrtrim

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Pey*_*ton 6

试试这个abbreviate功能:

qplot(Species, Sepal.Length, data=iris, geom="boxplot") +
  scale_x_discrete(label=abbreviate)
Run Code Online (Sandbox Code Playgroud)

标签缩写的例子

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

qplot(Species, Sepal.Length, data=iris, geom="boxplot") +
  scale_x_discrete(label=function(x) abbreviate(x, minlength=7))
Run Code Online (Sandbox Code Playgroud)

您也可以尝试旋转标签.