Ggplot:如何减少x标签文本

时间:2013-07-25 12:47:44

标签: r ggplot2 labels

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

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标签字符串的字符?

这样的事情:

Thisisaveryveryveryloooooongprotein - >这是[...]

谢谢!

2 个答案:

答案 0 :(得分:5)

尝试abbreviate功能:

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

example of label abbreviation

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

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

您也可以尝试旋转标签。

答案 1 :(得分:1)

由于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