Search code examples
rggplot2geom-text

how to increase date range of a plot to make room for geom_text at the end of series?


I am trying to add label to my series at the end using geom_text and for this I have tried to increase the x axis range to make room for series labels but it doesn't increase its range with scale_x_date.

Data

library(tidyverse)
library(lubridate)
library(scales)

file_url1 <- "https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/rtpcr_test_daily_pct.csv"

rtpcr_test_daily_pct <- read.csv(url(file_url1))

rtpcr_test_daily_pct <- rtpcr_test_daily_pct %>%
  mutate(Updated.On = as.Date(Updated.On))

Below is the code I have tried and no matter what value I add to x axis dates using scale_x_date() the x axis frame remains the same.

I am not sure what's wrong with the code that I 'av tried below:

rtpcr_test_daily_pct %>% 
  
  filter(!is.na(pct_rtpcr),
         pct_rtpcr > 0 ) %>% 
  
  ggplot(aes(x = Updated.On, 
             y = pct_rtpcr,
             col = State) 
         ) +
  geom_line(size = 1) +
  
  geom_text(data = rtpcr_test_daily_pct %>% 
              filter(Updated.On == max(Updated.On)-1),
            aes(label = State, 
                x = Updated.On , 
                y = pct_rtpcr ),
            vjust = -1,  
            size = 3) +
  
  scale_y_continuous(labels = percent,
                     breaks = seq(.1,1, by = .1)) +
  
  expand_limits(y = .1 ) + # 
  scale_x_date(aes(limits = as.Date(c("2021-03-01",max(Updated.On) + 15)))) +
  
  theme_minimal() +
  theme(legend.position = "none") +
  
  labs(title = "% RTPCR testing Between Karnataka & Delhi- Mar'21 onwards") +
  coord_equal(ratio = 70)

enter image description here


Solution

  • Use :

    scale_x_date(limits = c(as.Date("2021-03-01"),max(rtpcr_test_daily_pct$Updated.On) + 15))
    

    enter image description here

    complete code -

    library(tidyverse)
    
    rtpcr_test_daily_pct %>% 
      filter(!is.na(pct_rtpcr),
             pct_rtpcr > 0 ) %>% 
      ggplot(aes(x = Updated.On, 
                 y = pct_rtpcr,
                 col = State) 
      ) +
      geom_line(size = 1) +
      geom_text(data = rtpcr_test_daily_pct %>% 
                  filter(Updated.On == max(Updated.On)-1),
                aes(label = State, 
                    x = Updated.On , 
                    y = pct_rtpcr ),
                vjust = -1,  
                size = 3) +
      scale_y_continuous(labels = percent,
                         breaks = seq(.1,1, by = .1)) +
      expand_limits(y = .1 ) + # 
      scale_x_date(limits = c(as.Date("2021-03-01"),max(rtpcr_test_daily_pct$Updated.On) + 15)) + 
      theme_minimal() +
      theme(legend.position = "none") +
      labs(title = "% RTPCR testing Between Karnataka & Delhi- Mar'21 onwards") +
      coord_equal(ratio = 70)