1
votes

I am trying to plot two different variables on the Y-axis vs one variable on the X-axis. I am using ggplot geom_bar for the same. However, the results are not coming in the way what I wanted. My data frame looks as below:

      DAY_OF_WEEK CATEGORY_TOTAL OVERALL_TOTAL CAT_PERCENT OVERALL_PERCENT
1          FRIDAY           4893     30542         16              20
2          MONDAY           5198     31197         17              20
3        SATURDAY            133      1139         12               1
4        THURSDAY           4806     29641         16              19
5         TUESDAY           5184     31757         16              21
6       WEDNESDAY           4569     28090         16              18

ggplot(my_data_frame, aes(x=DAY_OF_WEEK,y=CATEGORY_TOTAL,fill=OVERALL_TOTAL)) + 
    geom_bar(stat="identity",position = "dodge")

I need DAY_OF_WEEK on the X-axis, and two bars next to each other for each day. One bar corresponding to CATEGORY_TOTAL and the other one for OVERALL_TOTAL. Similarly I want another plot for the percentages as well. However, with the above ggplot statement, I am only getting one bar i.e. CATEGORY_TOTAL.

Please suggest on how to achieve what I needed.

Thanks

1
Can you provide us with a reproducible example? - Roman Luštrik
Generally, ggplot2 works best with data in long format, so one line for each 'point' (or other thing) you want plotted. - Heroka
Roman, my data frame is as given above and I was two bars next to each other. Can you please let me know what other information is needed. I am a novice in R. So not sure on what is needed here! - greenhorntechie
Here are a few tips on how to produce a great example that will attract more (many?) answerers. - Roman Luštrik

1 Answers

0
votes

Here is a start for you; first we melt the data and then we plot.

library(ggplot2)
library(reshape2)

#relevel days of the week as more logical
dat$DAY_OF_WEEK <- factor(dat$DAY_OF_WEEK, levels=c("MONDAY","TUESDAY","WEDNESDAY","THURSDAY",
                                                    "FRIDAY","SATURDAY","SUNDAY"))

#turn to long
m_dat <- melt(dat,id="DAY_OF_WEEK")

#create grouping variable
m_dat$group <- gsub(".+_","",m_dat$variable)

#plot based on selection
p1 <- ggplot(m_dat[m_dat$group=="TOTAL",],
             aes(x=DAY_OF_WEEK,y=value,group=variable,fill=variable)) +
  geom_bar(stat="identity",position="dodge")
p1

enter image description here