2013-08-06 62 views
11

我用vjust作为解决方法,并通过尝试和错误的阐述可接受 距离。但是,这有时非常耗时,并且使用字体大小和轴比例来更改 。对齐geom_text到geom_vline在GGPLOT2

有没有更好的方法来对齐示例中的文本自动?

library(ggplot2) 

ggplot(data=mtcars, aes(x=hp, y=mpg))+ 
geom_point()+ 
theme_bw() + 
    geom_vline(xintercept=200, colour="grey") + 
    geom_text(aes(x=200, label="the strong cars", y=20), colour="blue", angle=90, vjust = 1.2, text=element_text(size=11))+ 
    geom_text(aes(x=200, label="the weak cars", y=20), colour="red", angle=90, vjust = -1, text=element_text(size=11)) 

ggsave(filename="geomline.png", width=5.5, height=2*3, dpi=300) 

enter image description here

+0

你想如何对齐? vjust = 0和vjust = 1似乎做了他们应该做的事情,超出这个范围的值总是比较偏心。 – baptiste

+0

我希望计算机看起来字体大小并将文本框放在正确的距离。因此,用户不必玩弄vjust值。 –

+1

我认为自动定位标签会很难,即使情节总是很简单。你看过['directlabels'](http://cran.r-project.org/web/packages/directlabels/index.html)包吗? – SlowLearner

回答

15

用于一个行标签的情况下的另一种解决办法是前/后添加换行符和保持默认vjust = 0.5。

ggplot(data=mtcars, aes(x=hp, y=mpg)) + 
    geom_point() + 
    theme_bw() + 
    geom_vline(xintercept=200, colour="grey") + 
    geom_text(aes(x=200, label="\nthe strong cars", y=20), colour="blue", angle=90, text=element_text(size=11)) + 
    geom_text(aes(x=200, label="the weak cars\n", y=20), colour="red", angle=90, text=element_text(size=11)) 
+0

简单而有效。我喜欢! – fdetsch

+1

另外,为了避免呈现多个副本,应该使用'annotate'来代替'geom_text',参见https://stackoverflow.com/questions/10952832/ggplot2-is-there-a-fix-for-jagged-poor-a-质量文本生产逐GEOM的文本 – Valentas

相关问题