Home > OS >  In R ggplot2 ,how to draw vertical lines automatically
In R ggplot2 ,how to draw vertical lines automatically

Time:09-17

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)

CodePudding user response:

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

CodePudding user response:

Internally, geom_barplot converts the character labels to integers 1,2,3, .... These are used as the positions of the bars. One way to get the positions of vertical lines is to convert the character vector mperiod to factor, then to numeric, then they will become 1,2,3.... Then plus 0.5 (to locate between bars).

library(magrittr)
library(ggplot2)
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(aes(xintercept=as.numeric(as.factor(mperiod)) 0.5))

enter image description here

If you do not want the line at the right end, here is one way to do this. The trick is to minus 0.5 instead of plus, so that positions are 0.5, 1.5, .... and use pmax to move 0.5 to 1.5.

plot_data %>% ggplot(aes(x=mperiod,y=amount)) 
  geom_bar(stat='identity') 
  geom_vline(aes(xintercept=pmax(1.5, as.numeric(as.factor(mperiod))-0.5)))

enter image description here

  • Related