简体   繁体   中英

Create geom_bar with difference of two lines using R and ggplot

I am facing some issues with a chart. I would like to add in my chart a geom_bar with the distance between the line per each of the two facets. I created a reproducible example that might be helpful. Thank you.

library(zoo)
library(ggplot2)
library(tidyr)


    date  <- c("2010 Q1","2010 Q2","2010 Q1","2010 Q2","2010 Q1","2010 Q2","2010 Q3","2010 Q1","2010 Q2","2010 Q3")
    date <- as.yearqtr(date)
    value <- c(0.01,0.02,0.05,0.3,0.03,0.04,0.2,0.04,0.3,0.3)
    variable <- "p_median"
    spec <- c("A","A","B","B","C","C","C","D","D","D")
    spec2 <- c("factor1","factor1","factor1","factor1","factor2","factor2","factor2","factor2","factor2","factor2")

    df1_m <- data.frame(date, spec, spec2, variable, value) #this converts character vectors to factors anyway


    ggplot() +
   # GEOM LINE. 
   # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
   geom_line(data = df1_m, 
            aes(x = date, y = value, colour = spec), size = 1) +
   scale_colour_manual(breaks = c("A", "B")
                      , values = c("red","green","red","green")
                      , name=""
                      , labels = c("A","B"))+
   facet_wrap(~spec2) 

gives

I am not sure if this is what you are looking for.

library(plyr)
library(dplyr)

# convert quarters to factors (otherwise ggplot was getting confused in my case)
df1_m <- df1_m %>% mutate(date=as.factor(date))

# create another dataframe with the difference between A and B in each quarter
df2_m <- df1_m %>% arrange(spec2, date, spec) %>% group_by(spec2, date) %>%
  summarise(delta=max(value) - min(value))

# create plot
ggplot() +
  # put bar plot in the background 
  geom_col(data = df2_m, aes(x = date, y = delta), width=0.2) +
  # note the `group=spec` aesthetic which is necessary because x-axis is a factor
  geom_line(data = df1_m, aes(x = date, y = value, colour = spec, group=spec), size = 1) +
  scale_colour_manual(breaks = c("A", "B")
                      , values = c("red","green","red","green")
                      , name=""
                      , labels = c("A","B"))+
  facet_wrap(~spec2) 

在此处输入图片说明

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM