Ggplot:如何减少x标签文本

问题描述 投票:4回答:2

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

plot1=ggplot (prot_Hit_selected, aes (x=V2,y=V1)) + geom_bar (stat ="identity", fill="#009E73",colour="black") +  theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs (title="More representative proteins", x="Protein", y= "Count") + geom_text(aes(label = V3, stat="identity", vjust="1.5" ))

在x轴上代表不同蛋白质的名称,当该名称太长时,我会遇到麻烦,因为在图形中只能看到名称,而不能看到图形。除了“打印”更大的图形,还有什么方法可以减少X标签字符串的字符?

类似这样的东西:

Thisisaveryveryveryloooooongongong蛋白-> Thisisavery [...]

谢谢!

r ggplot2 labels
2个回答
6
投票

尝试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))

您也可以尝试旋转标签。


0
投票

abbreviate可能导致一些奇怪的缩写。在许多情况下,最好截断标签。您可以将任何函数传递给label=函数的scale_*参数:一些不错的函数是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

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