Reputation: 343
Is it possible to have a ggplot axis with date-formatted labels and text-formatted labels?
The following code produces a chart with a date formatted x axis that runs from Jan-18 to Jun-19.
#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
geom_line(linetype = "dashed", colour = "grey") +
geom_point(aes(colour = meltdf2$colour, size = 3)) +
geom_point(data = melt_change, aes(shape = value, size = 3)) +
scale_colour_manual(values = pal, limits = names(pal), guide_legend("Risk Level")) +
scale_shape_manual(values = sh_pal, limits = names(sh_pal), guide_legend("Latest Change")) +
scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.line.x = element_line(colour = "darkgrey"), axis.title.x=element_blank(),
panel.background = element_rect(fill = "white"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
legend.position = c(0.2,0.70),
legend.key.size = unit(1.5,"line")) +
guides(colour = guide_legend(override.aes = list(size = 3)), shape = guide_legend(override.aes = list(size = 5))) +
scale_size(guide = "none")
However, I would like the Jun-19 date label to be replaced by a text label that reads "Change". Is there a way to do this without specifying all the labels individually?
I have tried to produce a vector that can be used as a labels
argument in the scale_x_date
function using the following code:
x_labels <- (as.Date(unique(meltdf2$Month)))
x_labels <- sort(x_labels)
x_labels <- c(x_labels,"Change")
But the vector does not seem to sort the dates correctly and the text "Change" value is replaced by an NA.
Upvotes: 1
Views: 287
Reputation: 1599
As the example is not fully reproducible, I have created a response with fictitious data.
Note that I had to create a new column for the period (Period
) under analysis, so that it is a factor and where I added the name "Change".
Later I reordered the levels using forcats
, function fct_reorder
, based on the dates (Dates
) of interest.
library(dplyr)
library(lubridate)
library(ggplot2)
library(forcats)
set.seed(1)
Period_x <- data.frame(Period = seq(lubridate::mdy('jan-01-2018'),
lubridate::mdy('may-01-2019'),
by = 'month'))
Period_x <- Period_x %>%
dplyr::mutate(Period = format(Period, '%b-%y'))
Period_x <- rbind(Period_x, "Change")
Period2 <- seq(lubridate::mdy('jan-01-2018'),
lubridate::mdy('jun-01-2019'),
by = 'month')
Period_x <- Period_x %>%
dplyr::mutate(Dates = Period2,
y = rnorm(18),
Period = as.factor(Period),
Period = forcats::fct_reorder(Period,
Dates))
ggplot2::ggplot(Period_x) +
geom_point(aes(x = Period, y = y))
Upvotes: 1