问题
我正在尝试在不明显扩展x轴的情况下垂直对齐折线图上的geom_label。有什么方法可以在图表的右边留出空白,以便ggrepel函数(如下)有工作空间?
我正在尝试复制Karam Belkar在this帖子上的最后一个图表(有关代码,请参见帖子底部),除非没有facet_wrap并使用economic中的ggplot示例数据集。
当我使用expand_limits时收到错误消息:

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

但是经济学$日期是日期格式!
在那里不安静的代码:
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 Usage Examples page在“线图”的标题下有一些基于橙树生长数据的示例。这涉及在x函数中添加coord_cartesian值以增加x轴。这为我需要的标签行为留出了空间,但是这意味着x轴超出了2020年,没有数据超过图表的那部分,这是不希望的。

最佳答案

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


r - 垂直对齐geom_label元素-LMLPHP

关于r - 垂直对齐geom_label元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49607324/

10-12 18:47