如何使用geom_text position_stack作为其aes的一部分?

时间:2018-01-24 16:46:02

标签: r ggplot2

我有以下数据框:

df <- data.frame(x=c(1,2,3,4,5),
                 y=c(2,3,5,9,9),
                 label=c('blah1','blah2','blah3','blah4','blah5'),
                 vjust=c('top','bottom','top','bottom','top'),
                 posVjust=c(0.9,1.1,0.9,1.1,0.9),
                 stringsAsFactors=FALSE)

并且可以直接绘制它:

p <- ggplot(df, aes(x=x,y=y,label=label)) + geom_point() + geom_line() +
         geom_text(aes(vjust=vjust))
p

但是,我想将posVjust列作为geom_text的{​​{1}}的一部分,但我不能这样:

aes

我收到以下错误:

geom_text(aes(vjust=vjust,position=position_stack(vjust=posVjust))) 

有没有办法在Warning: Ignoring unknown aesthetics: position > p Don't know how to automatically pick scale for object of type PositionStack/Position/ggproto. Defaulting to continuous. Error: Aesthetics must be either length 1 or the same as the data (5): vjust, position, x, y, label 电话中使用我的posVjust列?

1 个答案:

答案 0 :(得分:1)

position不是审美,而是超越aes。据我所知,position_stack只取一个值,而不是矢量。但是,您可以将posVjust更改为posVjust=c(-0.1,0.1,-0.1,0.1,-0.1),然后执行以下操作:

ggplot(df, aes(x=x, y=y,label=label)) + geom_point() + geom_line() +
  geom_text(aes(y=y + posVjust))

你也可以免除posVjust,只需这样做:

ggplot(df, aes(x=x, y=y,label=label)) + geom_point() + geom_line() +
  geom_text(aes(y=y + c(-0.1,0.1)))

您也可以添加vjust=vjust,这会增加一个额外的垂直偏移量。

另一种选择是删除点,只使用标签而不是点标记。然后,不再需要抵消geom_text标签。例如:

ggplot(df, aes(x=x, y=y, label=label)) + 
  geom_line(linetype="12", colour="grey50") +
  geom_text() +
  theme_bw()