I am experiencing this strange error.
Some test data:
library(ggplot2)
library(dplyr)
test <- structure(list(group = structure(c(1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L), .Label = c("G", "N", "P"), class = "factor"),
var = structure(c(1L, 1L, 2L, 3L, 4L, 4L, 4L, 4L, 2L, 2L,
2L, 3L, 2L, 2L, 2L, 5L, 5L, 5L, 4L, 5L, 5L, 5L, 5L, 1L, 1L,
2L, 1L, 1L, 1L, 3L, 3L, 3L, 5L, 3L, 3L, 3L, 4L, 4L, 4L, 1L,
1L, 2L, 2L, 2L, 3L), .Label = c("a", "b", "c", "d", "e"), class = "factor"),
group2 = structure(c(3L, 1L, 3L, 3L, 1L, 2L, 3L, 4L, 1L,
2L, 3L, 4L, 1L, 2L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 2L,
3L, 4L, 1L, 2L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 4L, 1L, 2L, 3L,
4L, 1L, 1L, 2L, 3L, 4L), .Label = c("O", "P", "Q", "R"), class = "factor"),
cor = c(0.270075198428616, 0.262097140096646, -0.331312784846655,
-0.343984945812309, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA)), row.names = c(NA, -45L), .Names = c("group", "var",
"group2", "cor"), class = "data.frame")
I would like to make this plot:
test %>%
ggplot(., aes(x=group2, y=cor)) +
geom_bar(stat="identity", position="dodge", aes(fill=var, group=var)) +
geom_text(aes(label = round(cor,2),
vjust = ifelse(cor >= 0, 0, 1),
group=var),
position = position_dodge(width=1)) +
theme_bw(base_size=18) +
facet_wrap(~group, scales="free_x")
.., that leads to: Error in unit(x, default.units) : 'x' and 'units' must have length > 0
However, without geom_text
it works:
And also only using lines 1:40 it works:
test %>% slice(1:40) %>%
ggplot(., aes(x=group2, y=cor)) +
geom_bar(stat="identity", position="dodge", aes(fill=var, group=var)) +
geom_text(aes(label = round(cor,2),
vjust = ifelse(cor >= 0, 0, 1),
group=var),
position = position_dodge(width=1)) +
theme_bw(base_size=18) +
facet_wrap(~group, scales="free_x")
Thus, up to line 40 there are only two levels for group
, and from line 41 there is a third level. But how can this cause this error? Or is there something else I can't see?