【问题标题】:Left-justify geom_text layer with ggplot2使用 ggplot2 左对齐 geom_text 图层
【发布时间】:2018-02-25 19:13:42
【问题描述】:

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:

但是,我想在一个整洁的列中左对齐文本。我本质上是在问如何向text 提供xmin。我是否需要对 x 变量执行数学运算,以相应地缩放 x?或者theme有什么技巧吗?

【问题讨论】:

标签: r ggplot2 geom-text


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多