我试图在线图上垂直对齐geom_label,而不会明显地扩展x轴。有没有办法可以在图表的右边创建空格,以便ggrepel
函数(下面)有空间可以工作?
我正在尝试复制Karam Belkar发布的this帖子的最后一个图表(请参阅帖子底部的代码),除了facet_wrap
并使用economic
示例数据集{ {1}}。
当我使用ggplot
时收到错误消息:
expand_limits
但经济学$ date是日期格式!
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
Usage Examples page有一些基于橘树生长数据的示例,这些数据位于“线图”的标题下。这涉及在ggrepel
函数中添加x
值以增加x轴。这为我需要的标签行为提供了空间,但这意味着x轴延伸到2020年以后,没有数据高于图的那一部分,这是不可取的。
答案 0 :(得分: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))