2017-09-16 1506 views
2

ggplot2将文本自动居中在geom_text图层中。例如:使用ggplot2左对齐geom_text图层

library(ggplot2) 
library(tidyverse) 
df <- data_frame(text = c("A short sentence.", 
         "A slightly longer sentence.", 
         "This sentence is the longest of the sentences."), 
      y = row_number(text) - 1, 
      x = 1) 

ggplot(df, aes(x = x, y = y)) + 
    geom_text(aes(label = text), nudge_x = nchar(text)/2) 

产地:

ggplot:

link to ggplot (I'm not allowed to post images yet)

不过,我要左对齐在一个整洁的列中的文本。我本质上是问如何提供xmintext。我是否需要对x变量进行数学运算,该变量相应地缩放x?或者有一个与theme

+0

又见HTTPS: //community.rstudio.com/t/how-do-i-set-an-xmin-argument-to-geom-text/785/3 – baptiste

回答

1

您可以使用hjust

ggplot(df, aes(x = x, y = y)) + 
    geom_text(aes(label = text), hjust = 0) 

您还可以添加一个xlim到列对齐到最左侧的情节:

ggplot(df, aes(x = x, y = y)) + 
    geom_text(aes(label = text), hjust = 0) + xlim(1, 1.5) 

enter image description here

+1

非常感谢! –