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

r ggplot添加要显示的因子类别标签,r,ggplot2,R,Ggplot2,我正在Rstudio中使用ggplot尝试创建一个条形图,显示当风来自某个方向时的指示器数量 我的数据不包括来自各个方向的风(分类为“N”、“NE”、“E”、“SE”、“S”、“SW”、“W”、“NW”)。因此,我的情节看起来很奇怪,因为它们错过了某些风向 有没有办法添加类别类并强制它们出现在图表上 更新: 使用dput的我的数据子集是: structure(list(Sum.of.Incidents = c(1L, 2L, 2L, 0L, 1L, 0L, 0L, 2L, 2L, 0L, 1L

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

我的数据不包括来自各个方向的风(分类为“N”、“NE”、“E”、“SE”、“S”、“SW”、“W”、“NW”)。因此,我的情节看起来很奇怪,因为它们错过了某些风向

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

更新: 使用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"))

example$WindDirCompass如果只是因为有0个事件而导致因子级别下降,您可能只需要添加:
+scale\u x\u离散(drop=FALSE)

在您的代码中,如下所示:

ggplot(transect_weather_summary, 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)

如果这不是问题,您应该给出一些数据示例,当您从
aes()
中删除
factor()
并添加
中断时,我认为您得到了所需的绘图:

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

使用
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"

请使用
dput()
显示一些数据,并显示您已经尝试过的内容。是。(如果有人能教你怎么做。)谢谢。但当我尝试这个方法时,它不起作用,因为根本没有这些方向的条目。我意识到我可以通过添加这些空白行来强制实现这一点,但希望有一种更简洁的方法来实现这一点,而不是编造数据。