【问题标题】:Vertically align geom_label elements垂直对齐 geom_label 元素
【发布时间】:2018-04-02 07:47:00
【问题描述】:

问题

我正在尝试在折线图上垂直对齐 geom_label,而不会明显地延伸 x 轴。有没有办法可以在图表右侧留出空白,以便ggrepel 函数(如下)有空间工作?

我正在尝试复制 Karam Belkar 发布的 this 上的最后一个图表(代码见帖子底部),除了没有 facet_wrap 并使用 economic 中的示例数据集 ggplot

当我使用expand_limits 时收到错误消息:

Error: Invalid input: date_trans works with objects of class Date only

但economics$date 是日期格式!

那里不安静的代码:

library("tidyverse")
library("ggthemes")
library("ggrepel")

df1 <- gather(economics, variable_name, observation, -date) %>% 
  rename(period = date) %>% 
  filter(variable_name %in% c("pce", "unemploy"))

p <- ggplot(df1, aes(x = period, y = observation, colour = variable_name)) +
  geom_line() +
  coord_cartesian(xlim = c(min(df1$period), max(df1$period))) +
#Alternative line to that above with undesirable result 
#coord_cartesian(xlim = c(min(df1$period), max(df1$period) **+ 3000**)) +
  geom_text_repel(
    data = subset(df1, period == max(period)),
    aes(label = variable_name),
    size = 3,
    nudge_x = 45,
    segment.color = 'grey80'
  ) +
  scale_y_continuous(labels = scales::comma) +
  theme_minimal(base_size = 16) +
  scale_color_tableau() + 
  scale_fill_tableau() +
  theme(legend.position = 'none') +
  labs(x="", y="", title = "Economic Data") 


p + expand_limits(x = 700)
#the data set has 574 observations so I tried to 
#add another 126 to give space to the labels

ggrepelUsage Examples page 在“线图”标题下有一些基于橙树生长数据的示例。这涉及在coord_cartesian 函数中添加x 值以增加x 轴。这为我需要的标签行为提供了空间,但这意味着 x 轴延伸到 2020 年之后,图表的该部分上方没有数据,这是不可取的。

【问题讨论】:

    标签: r ggplot2 ggrepel


    【解决方案1】:

    必须以日期格式提供轴限制,使用expand_limits(x=700) 会引发此问题,以下工作将在scale_x_date 中合并。我使用 1200 而不是 700 来创建附加图表。

    p <- ggplot(df1, aes(x = period, y = observation, colour = variable_name)) +
      geom_line() +
      geom_text_repel(
        data = subset(df1, period == max(as.Date(period, "%Y-%m-%d"))),
        aes(label = variable_name),
        size = 3,
        nudge_x = 45,
        segment.color = 'grey80'
      ) +
      scale_y_continuous(labels = scales::comma) +
      theme_minimal(base_size = 16) +
      scale_color_tableau() + 
      scale_fill_tableau() +
      theme(legend.position = 'none') +
      labs(x="", y="", title = "Economic Data") 
    p + scale_x_date(limits = c(min(df1$period), max(df1$period) + 1200))
    

    【讨论】:

    • 这比我所拥有的有所改进。我想知道是否有可能避免在标签下方的 x 轴上有额外的空间,而只有空白?
    • 您的意思是删除 2020 标签和关联的网格线吗?
    • 是的,x轴的那一段。
    猜你喜欢
    • 2014-04-02
    • 2015-07-15
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多