Problem in plotting the difference between two columns in Dataframe over 4 quarters (Q1, Q2, Q3 and Q4) in a year

Viewed 30

I have a problem in plotting the Diversity graph which shows me the difference between two columns in a datafarme over 4 quarters of the year. This is the dataframe which I have:

df_Total2 = 

       Quarters     X1     X2

1        Q1       390000  375000

2        Q1       675000  693000

3        Q1       350000  346000

4        Q1       950000  925000

5        Q2       395000  382000

6        Q2       800000  837000

7        Q2       350000  342000

8        Q2       850000  890000

9        Q3       400000  390000

10       Q3       750000  713000

11       Q3       350000  340000

12       Q3       875000  976000

13       Q4       410000  408000

14       Q4       750000  790000

15       Q4       350000  367000

16       Q4       900000  930000

This is my code:

library(plotly)
library(readxl)

df =read_excel("DeptYearlyPerfChange.xls")

df

df_Q1 <- cbind (df$Q1Budget,df$Q1Actual)

df_Q2 <- cbind (df$Q2Budget,df$Q2Actual)

df_Q3 <- cbind (df$Q3Budget,df$Q3Actual)

df_Q4 <- cbind (df$Q4Budget,df$Q4Actual)


df_Total <- rbind (df_Q1,df_Q2,df_Q3,df_Q4)

Quarters <- c ("Q1", "Q1","Q1", "Q1",  "Q2", "Q2","Q2", "Q2", "Q3", "Q3","Q3", "Q3"
               , "Q4", "Q4","Q4", "Q4")

df_Total2 <- cbind (Quarters, df_Total)

df_Total2 <- data.frame(Quarters, df_Total)


# Shaded region

ggplot(df_Total2, aes(x=Quarters, y= as.factor(df_Total2[,2]))) +

                  geom_ribbon(aes(ymin=as.factor(df_Total2[,2])-as.factor(df_Total2[,3]), 

                  ymax=as.factor(df_Total2[,2])+as.factor(df_Total2[,3])),

                  alpha=0.2) + geom_line()

I would like to know what is the error of my code. Honestly, I did my best to solve this problem and I need really to your help.

1 Answers

If we need to plot the difference

library(dplyr)
library(ggplot2)
df_Total2 %>% 
  mutate(Diff = X1 - X2, Sum = X1 + X2) %>% 
  group_by(Quarters) %>% 
  mutate(min = min(Diff), max = max(Sum)) %>% 
  ggplot(aes(x = Quarters, y = X1)) + 
    geom_ribbon(aes(ymin = first(min), ymax = first(max)), alpha = 0.2) + 
    geom_line()

data

df_Total2 <- structure(list(Quarters = c("Q1", "Q1", "Q1", "Q1", "Q2", "Q2", 
"Q2", "Q2", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4"), 
    X1 = c(390000L, 675000L, 350000L, 950000L, 395000L, 800000L, 
    350000L, 850000L, 400000L, 750000L, 350000L, 875000L, 410000L, 
    750000L, 350000L, 900000L), X2 = c(375000L, 693000L, 346000L, 
    925000L, 382000L, 837000L, 342000L, 890000L, 390000L, 713000L, 
    340000L, 976000L, 408000L, 790000L, 367000L, 930000L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16"))
Related