Search code examples
rggplot2geom-vline

In R ggplot2 ,how to draw vertical lines automatically


In R ggplot2 ,how to draw vertical line between columns

Using 'geom_vline(xintercept=as.numeric(plot_data$mperiod)+0.5)' ,it's can't work

plot_data <- data.frame(mperiod=paste0('Q',1:4),amount=c(1:4))
plot_data %>% ggplot(aes(x=mperiod,y=amount))+
  geom_bar(stat='identity')+
  geom_vline(xintercept=as.numeric(plot_data$mperiod)+0.5)

When using 'geom_vline(xintercept=c(1:3)+0.5)',it's ok ,but i have to input vector manually. Cause in actual, the situation is a little complicated, i want to calculate it automatically. Anyone can help ? thanks

plot_data %>% ggplot(aes(x=mperiod,y=amount))+
      geom_bar(stat='identity')+
     geom_vline(xintercept=c(1:3)+0.5)

Solution

  • Here is a solution, that my help you.

    library(tidyverse)
    
    plot_data %>%
      ggplot(aes(x=mperiod,y=amount))+
      geom_bar(stat='identity')+
      geom_vline(aes(xintercept = parse_number(mperiod) + .5))
    

    enter image description here