【发布时间】: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 年之后,图表的该部分上方没有数据,这是不可取的。
【问题讨论】: