0

I have a data set in R of appointments from different departments.

> dput(head(Data.2016))
structure(list(NUMMER = c(361626L, 411992L, 2752868L, 6592340L, 9017183L, 451010L), 
         DEPARTMENT= structure(c(3L, 3L, 3L, 3L, 3L, 3L), .Label = c("DEA", "DIE", 
             "IAL", "IEN", "IGH", "IHM", "ILN", "INE", "INF", "INT"), class = "factor"),        
         TYPE_APPOINTMENT = structure(c(3L, 3L, 3L, 3L, 3L, 2L), .Label = c("BZ", "E", "H", 
             "NK", "TF", "VP", "VW"), class = "factor"), 
         WEEKDAY = structure(c(5L, 6L, 6L, 6L, 6L, 2L), .Label = c("Sun", "Mon", "Tues", 
            "Wed", "Thurs", "Fri", "Sat"), class = c("ordered", "factor")), 
 .Names = c("NUMMER", "DEPARTMENT", "TYPE_APPOINTMENT", "WEEKDAY"), row.names = c(1L, 2L, 
   4L, 5L, 6L, 7L), class = "data.frame")

I wish to construct a plot which distinguishes both type of appointment and department for every day of the week. I've used the following code to do this:

library(ggplot2)

ggplot(Data.2016,
   aes(x=Data.2016$WEEKDAY, 
       fill=Data.2016$TYPE_APPOINTMENT)) +
  geom_bar() +
  facet_grid(~DEPARTMENT)+
 theme(legend.title=element_blank()) + 
 labs(x = "Days of the week")

This results in the following plot: Appointments

Which is about what I would expect and what I need (ignore the uglyness of x-axis).

However, after investigating the plot a bit better, I find that the outcome is not correct. The department DIE cannot have any "E" or "H", but in the above plot it somehow does. In fact, when I select just DIE, using the following code

ggplot(Data.2016[which(Data.2016$DEPARTMENT == "DIE"),],
   aes(x=Data.2016$WEEKDAY, 
       fill=Data.2016$TYPE_APPOINTMENT)) +
  geom_bar() +
  theme(legend.title=element_blank()) + 
  labs(x = "Days of the week")

the outcome is Appointments DIE, which is correct.

What am I doing wrong? Or is this a malfunction known by other R users?

D.Cirkel
  • 65
  • 1
  • 8
  • A note, when you put `Data.2016` in your inital `ggplot(` you don't need to reference it everytime, you can just use the variable names, so `WEEKDAY` instead of `Data.2016$WEEKDAY` for example. Also without posting a `dput()` of your data it's hard to tell exactly what is going wrong. For more tips on how to make a good r question, see the answers for this question: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Marijn Stevering Mar 10 '17 at 14:35
  • 1
    Never use `$` inside `aes`. Write `ggplot(Data.2016, aes(x = WEEKDAY, fill = TYPE_APPOINTMENT))`. Also, write `facet_grid(~DEPARTMENT)`. There is a reason that you are already supplying something to the `data` argument! – Axeman Mar 10 '17 at 14:35
  • I've editted it, hope this helps. Thanks for the tip: it saves a lot of time! – D.Cirkel Mar 10 '17 at 15:25
  • Wow, nevermind. I've just removed all the $ from my plots and now it works! Thanks! – D.Cirkel Mar 10 '17 at 15:32

0 Answers0