R:ggplot2轴显示两个范围

时间:2019-05-13 05:07:34

标签: r ggplot2

我正在使用带有facet_wrap()的ggplot,如下所示:

plot <- ggplot(x, aes(Result, values, fill=Month))+
  geom_bar(stat="identity", position=position_dodge())

plot + facet_wrap(~Month)

我的情节如下: enter image description here

如您所见,该图显示了月份中两个不同的范围。

dput(x)是:

structure(list(Result = structure(c(2L, 1L, 2L, 1L), .Label = c("Negative", 
"Positive"), class = "factor"), values = c("100", "0", "66.6666666666667", 
"33.3333333333333"), Month = structure(c(2L, 2L, 1L, 1L), .Label = c("January", 
"February"), class = "factor")), class = "data.frame", row.names = c(NA, 
-4L))

我该如何解决?

1 个答案:

答案 0 :(得分:1)

似乎在某个时刻values被迫成为一个因素,水平为0, 100, 33.33, 66.66。我可以使用以下代码复制该图:

df <- tibble(result = c("neg", "pos", "neg", "pos"),
             values = factor(c(33.33, 66.66, 0, 100),
                             levels = c(0, 100, 33.33, 66.66)
                             ),
             month = factor(c("jan", "jan", "feb", "feb"),
                            levels = c("jan", "feb")
                            )
             )

ggplot(df, aes(result, values, fill=month)) +
    geom_bar(stat="identity", position=position_dodge()) + 
    facet_wrap(~ month)

enter image description here

您只需要将values转换回数字向量即可。请注意不要返回级别的整数表示,而不是返回想要的数字,即执行类似as.numeric(as.character(values))而不是as.numeric(values)的事情:

df %>% mutate(values = as.numeric(as.character(values))) %>% 
    ggplot(aes(result, values, fill=month)) +
    geom_bar(stat="identity", position=position_dodge()) + 
    facet_wrap(~ month)

enter image description here