I have two dataframes in the long and wide formats, below as a sample:
df_longer <- data.frame(list(Name = c("A", "A", "A", "A", "A",
"B", "B", "B", "B", "B"),
Date_Types = c("Date1", "Date2",
"Date3","Date4", "Date5",
"Date1", "Date2", "Date3",
"Date4", "Date5"), Dates =
structure(c(18903, 18965, 19081,
19116, 19172, 19083, 19097,
19219, 19249, 19341), class =
"Date")))
df_wider <- data.frame(list(Name = c("B", "A"), Date1 = structure(
c(19083, 18903), class = "Date"), Date2 = structure(c(19097,
18965), class = "Date"), Date3 = structure(c(19219, 19081),
class = "Date"), Date4 = structure(c(19249, 19116),
class = "Date"), Date5 = structure(c(19341, 19172),
class = "Date")))
I am trying to plot the data while having limits that cut off the geom_segment lines.
my_date_format <- function()
{
function(x)
{
m <- format(x,"%b")
y <- format(x,"%Y")
ifelse(duplicated(y),m,paste(m,y))
}
}
ggplot(df_longer, aes(x = Dates, y = Name))
theme_classic() geom_point(aes(shapes = Date_Types), size=8)
theme(axis.line.y = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text = element_text(size=22))
scale_x_date(date_break = "1 month",
labels = my_date_format())
geom_segment(data=df_wider, aes(x=Date1, xend=Date2,
y=Name, yend=Name), size=0.6, linetype="dashed")
geom_segment(data=df_wider, aes(x=Date2, xend=Date3,
y=Name, yend=Name), size=0.6, linetype="dashed")
geom_segment(data=df_wider, aes(x=Date3, xend=Date4,
y=Name, yend=Name), size=1)
geom_segment(data=df_wider, aes(x=Date4, xend=Date5,
y=Name, yend=Name), size=0.6, linetype="dashed")
I want to keep the geom_segment lines leaving the plot area even if the start or end dates dont fall within the limits as here:
scale_x_date(date_break = "1 month",
labels = my_date_format(),
limits = as.Date(c('2021-11-11','2022-11-11'))) ...
The desired output would be:
CodePudding user response:
Adding the geom coord_cartesian()
is my preferred method.
ggplot(df_longer, aes(x = Dates, y = Name))
theme_classic() geom_point(aes(shapes = Date_Types), size=8)
theme(axis.line.y = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text = element_text(size=22))
scale_x_date(date_break = "1 month",
labels = my_date_format())
coord_cartesian(xlim = as.Date(c('2021-11-11','2022-11-11')))
geom_segment(data=df_wider, aes(x=Date1, xend=Date2,
y=Name, yend=Name), size=0.6, linetype="dashed")
geom_segment(data=df_wider, aes(x=Date2, xend=Date3,
y=Name, yend=Name), size=0.6, linetype="dashed")
geom_segment(data=df_wider, aes(x=Date3, xend=Date4,
y=Name, yend=Name), size=1)
geom_segment(data=df_wider, aes(x=Date4, xend=Date5,
y=Name, yend=Name), size=0.6, linetype="dashed")