r ggplot添加要显示的因子类别标签

时间:2017-01-27 10:51:49

标签: r ggplot2

我在Rstudio中使用ggplot尝试创建一个条形图,显示当风来自某个方向时的指示数量。

我的数据不包括来自各个方向的风(分类为" N"," NE"," E"," SE&#34 ;," S"" SW"" W"" NW&#34)。因此,我的阴谋看起来很奇怪,因为它们错过了某些风向。

有没有办法添加类别类并强制它们出现在图表上?

更新: 使用dput的数据子集是:

structure(list(Sum.of.Incidents = c(1L, 2L, 2L, 0L, 1L, 0L, 0L, 
2L, 2L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 5L, 0L, 4L, 1L, 
1L, 0L, 0L, 0L, 0L), WindDirCompass = structure(c(2L, 2L, 7L, 
8L, 6L, 5L, 2L, 1L, 1L, 2L, 8L, 8L, 7L, 3L, 7L, 1L, 8L, 6L, 6L, 
3L, 8L, 6L, 7L, 7L, 7L, 8L, 8L, 6L), .Label = c("N", "NE", "E", 
"SE", "S", "SW", "W", "NW"), class = "factor")), row.names = c(NA, 
-28L), .Names = c("Sum.of.Incidents", "WindDirCompass"), spec = structure(list(
    cols = structure(list(Sum.of.Incidents = structure(list(), class = c("collector_integer", 
    "collector")), WindDirCompass = structure(list(), class = c("collector_character", 
    "collector"))), .Names = c("Sum.of.Incidents", "WindDirCompass"
    )), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"), class = c("tbl_df", 
"tbl", "data.frame"))

我正在运行的当前代码用于生成图:

ggplot(example, aes(x = factor(WindDirCompass),
                                     y = Sum.of.Incidents)) +
     geom_bar(stat = "identity", fill = "#990033") +
     labs(title = "", x = "Wind direction", y = "Number of incidents") +
 scale_x_discrete(drop = FALSE)

我也按指示命令:

example$WindDirCompass <-
     factor(example$WindDirCompass,
            c("N", "NE","E","SE","S","SW","W","NW"))

因此&#34; SE&#34;不见了。有没有办法强制出现这个因素。 我还有其他情况,只有一个或两个方向发生事故,因此大多数风向都会丢失。

2 个答案:

答案 0 :(得分:1)

当您从factor()移除aes()并添加breaks时,我认为您获得了所需的情节:

ggplot(example, aes(x = WindDirCompass,
                    y = Sum.of.Incidents)) +
  geom_bar(stat = "identity", fill = "#990033") +
  labs(title = "", x = "Wind direction", y = "Number of incidents") +
  scale_x_discrete(drop = FALSE, breaks = levels(example$WindDirCompass)) 

enter image description here

使用factor()导致未使用的级别被删除:

> levels(example$WindDirCompass)
[1] "N"  "NE" "E"  "SE" "S"  "SW" "W"  "NW"
> levels(factor(example$WindDirCompass))
[1] "N"  "NE" "E"  "S"  "SW" "W"  "NW"

答案 1 :(得分:0)

如果只是因为他们有0个事件导致因子水平下降,你可能只需要添加: OnTerminate

在您的代码中,这看起来像:

+ scale_x_discrete(drop=FALSE)

如果这不是问题,您应该提供一些数据示例