【问题标题】:align variable width font strings in ggplot2 ggrepel geom_label_repel对齐ggplot2中的可变宽度字体字符串ggrepel geom_label_repel
【发布时间】:2019-12-09 15:18:39
【问题描述】:

我正在尝试在ggrepel::geom_label_repel 中使用多个行标签。似乎geom_label_repel 想要将所有文本居中 - 而我想将它向左冲洗。 hjust = 0geom_label 做我想做的事,但用geom_label_repel 做不到。我创建了一个函数来通过插入空格来做我想做的事——但它只适用于等宽字体。

有没有办法让geom_label_repel 与可变宽度字体左对齐?

library(tidyverse)
library(ggrepel)
site_timeline_dfx <- tribble(
  ~startDate, ~endDate, ~Event,
  1984, NA,   "Lorem ipsum dolor sit amet, sed, vestibulum, in lacinia erat arcu. Quis magnis sed phasellus ac",
  2001, NA,  "Vel cursus hac in. Nulla cum quam cum, amet tellus hendrerit.",
  2008, 2009, "Adipiscing ut pellentesque malesuada sit venenatis integer proin sapien. Scelerisque ipsum ut.")

my_xwrapFun = function(x, width = 75){
   x_wrap <- strwrap(x, width = width)
   i <- length(x_wrap)
   max_strln <- max(str_length(x_wrap))
   x_wrap <- encodeString(x_wrap, width = width, justify ="l")
   paste(x_wrap, collapse = "\n")
}

site_timeline_dfx <- 
  group_by(site_timeline_dfx, Event) %>% 
  mutate(Event_wrap = my_xwrapFun(Event))

ggplot(site_timeline_dfx, aes(x = startDate, y = 0.5, label  = Event_wrap)) + geom_point() + 
  geom_label(hjust = 0, size = 2) +
  xlim(c(1984,2050))

ggplot(site_timeline_dfx, aes(x = startDate, y = 0.5, label  = Event_wrap)) + geom_point() + 
  geom_label_repel(hjust = 0, size = 2) +
  xlim(c(1984,2050))

ggplot(site_timeline_dfx, aes(x = startDate, y = 0.5, label  = Event_wrap)) + geom_point() + 
  geom_label_repel(hjust = 0, size = 2, family = "mono") +
  xlim(c(1984,2050))

【问题讨论】:

    标签: r ggplot2 ggrepel


    【解决方案1】:

    此问题已在 ggrepel(版本 0.8.1.9000)的开发版本中得到修复。

    您的代码现在应该可以按预期工作了。

    devtools::install_github("slowkow/ggrepel")
    
    ggplot(site_timeline_dfx, aes(x = startDate, y = 0.5, label  = Event_wrap)) + 
      geom_point() + 
      geom_label_repel(hjust = 0, direction="y") +
      xlim(c(1984,2050))
    

    【讨论】:

    • 谢谢!也不需要用空格填充。
    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2012-02-20
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多