ggplot facet_grid产生错误的结果?

时间:2017-03-10 14:26:57

标签: r ggplot2 facet-grid

我在R中有来自不同部门的约会数据集。

> 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")

我希望构建一个图表,区分每周的每一天的约会类型和部门。我使用以下代码执行此操作:

library(ggplot2)

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

这导致以下情节: Appointments

关于我期望的和我需要的东西(忽略x轴的丑陋)。

然而,在调查好一点后,我发现结果不正确。部门DIE不能有任何“E”或“H”,但在上面的情节中它不知何故。事实上,当我选择DIE时,使用以下代码

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

结果是Appointments DIE,这是正确的。

我做错了什么?或者这是其他R用户已知的故障吗?

0 个答案:

没有答案