2017-09-16 112 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

非常感謝! –