3

问题

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

我正在尝试复制 Karam Belkar 在这篇文章中的最后一张图表(请参阅文章底部的代码),除非没有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

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

4

1 回答 1

2

有必要以日期格式提供轴限制,使用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))

在此处输入图像描述

于 2018-04-02T09:31:37.397 回答