anderwyang
anderwyang

Reputation: 2451

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)

Upvotes: 2

Views: 915

Answers (2)

Kota Mori
Kota Mori

Reputation: 6750

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

Upvotes: 3

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8836

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

Upvotes: 1

Related Questions