Problem
I am trying to vertically align geom_label's on a line chart without visibly extending the x-axis. Is there a way I can make white space on the right of the chart so that the ggrepel
function (below) has space to work?
I am trying to replicate the last chart on this post by Karam Belkar (see bottom of post for code) except without the facet_wrap
and using the economic
example data set in ggplot
.
When I use expand_limits
get the error message:
Error: Invalid input: date_trans works with objects of class Date only
But economics$date is of Date format!
Code that is not quiet there:
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
The ggrepel
Usage Examples page has some examples based on Orange Tree growth data under the heading of 'Line Plot'. That involves adding an x
value in the coord_cartesian
function to increase the x-axis. That gives room for the label behaviour I need but it means that the x-axis extends out past the year 2020 with no data above that part of the graph, which is undesirable.