R语言 位置多行左调整轴.文本居中下打勾

ddrv8njm  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(113)

我有多行x轴标签,我想左调整内的标签(这样两行的左边就在同一个缩进处),但要在轴tick下面居中放置。如果我使用theme(axis.text = element_text(hjust = 0)),文本行被适当地缩进到相同的级别但是定位在滴答声的右边(见MWE)。我如何让它们定位在滴答声的正下方?

library(ggplot2)
    library(stringr)

    ## Create a sample data frame
    df <- data.frame(x = 1:5,
                     y = c(2, 4, 3, 5, 6),
                     label = c("Line 1 Label", "Line 2 Label is a bit longer",
                               "Line 3 Label is even longer than the previous one",
                               "Line 4 Label is not so long", "Line 5 Label"))

    ## Wrap the label text with str_wrap()
    df$label <- str_wrap(df$label, width = 15)

    ## Create the plot
    ggplot(df, aes(x, y)) +
        geom_point() +
        scale_x_continuous(breaks = 1:5, labels = df$label) +
        theme(axis.text.x = element_text(hjust = 0))

bvk5enib

bvk5enib1#

一个选项是使用ggtext::element_markdown,除了hjust对齐轴文本的整个边框外,还有一个额外的参数halign来对齐框内的轴文本,即我们可以使用hjust=.5将框居中,并使用halign=0左对齐文本:

library(ggtext)
library(ggplot2)
library(stringr)

## Create a sample data frame
df <- data.frame(
  x = 1:5,
  y = c(2, 4, 3, 5, 6),
  label = c(
    "Line 1 Label", "Line 2 Label is a bit longer",
    "Line 3 Label is even longer than the previous one",
    "Line 4 Label is not so long", "Line 5 Label"
  )
)

df$label <- str_wrap(df$label, width = 15)
df$label <- str_replace_all(df$label, "\\n", "<br>")

ggplot(df, aes(x, y)) +
  geom_point() +
  scale_x_continuous(breaks = 1:5, labels = df$label) +
  theme(axis.text.x = ggtext::element_markdown(hjust = .5, halign = 0))

相关问题