Limiting dates of the scale_x_date

Hello
Please help I failing to limit the dates of the x-axis using the following code. I do not want 2025 to appear on the graph

Historical_cases_death %>% 
   mutate(year = as.Date(paste0(year, "-01-01"))) %>%
   filter(year >= "1998-01-01" & year <= "2024-12-31") %>% 
  ggplot(aes(x=year))+
  geom_col(aes(y=cases), fill="orange1", size=5)+
  geom_line(aes(y=CFR/0.0001), col="red")+
  scale_y_continuous(
    
    # Features of the first axis
    name = "Cholera cases ",
    
    # Add a second axis and specify its features
    sec.axis = sec_axis(~.*0.0001, name="CFR in Percent")
  )+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 90, size = 12))+
  scale_x_date(date_breaks = "1 year", date_labels = "%Y")+
               # limits = c(as.Date("1999-01-01"),as.Date("2024-12-01")))+
    geom_text(aes(x=year, y=cases,label=cases),
            vjust=-0.5, hjust=-0.01, color="black", size=2.5)+
  labs(
    x="Year", 
    title = "Cholera Epidemiolocail Trends in Malawi, 1998-2024"
    
  )

Using the code above the year 2025 is still showing

If you want to avoid having 2025 as the last label at the right end of your x axis, you can set the x labels manually as I did in the second plot below.

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(ggplot2)
DF <- data.frame(Date = seq.Date(ymd("2015-01-31"), ymd("2024-12-31"), by = "month"),
                 Val = rnorm(120))
ggplot(DF, aes(Date, Val)) + geom_point() + 
  scale_x_date(date_breaks = "1 year", date_labels = "%Y")



DateValues <- seq.Date(ymd("2015-01-01"), ymd("2024-01-01"), by = "year")

ggplot(DF, aes(Date, Val)) + geom_point() + 
  scale_x_date(breaks = DateValues, date_labels = "%Y")

Created on 2024-11-27 with reprex v2.1.1

hey @FJCC ,

thanks a lot ,
I setting x manual has worked

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.