按组值分组的箱线图

时间:2018-08-13 09:59:02

标签: r ggplot2

我有以下示例数据框:

Parameter<-c("As","Hg","Pb")
Loc1<-c("1","10","12")
Loc2<-c("3","14","9")  
Loc3<-c("5","12","8")
Loc4<-c("9","20","6")
x<-data.frame(Parameter,Loc1,Loc2,Loc3,Loc4)
x$Loc1<-as.numeric(x$Loc1)
x$Loc2<-as.numeric(x$Loc2)
x$Loc3<-as.numeric(x$Loc3)
x$Loc4<-as.numeric(x$Loc4)

“参数”列保存重金属的名称,“位置1”到“位置4”列保存各个位置的重金属测量值。

我需要一个带有一个箱形图的图,用于每个位置的每种重金属。位置是分组值。我尝试了以下方法:

melt<-melt(x, id=c("Parameter"))
ggplot(melt)+
  geom_boxplot (aes(x=Parameter, y=value, colour=variable))

但是,生成的图并没有以某种方式将盒图按位置分组。

1 个答案:

答案 0 :(得分:2)

每个Parameter中每个Location有一个观察值的箱线图毫无意义(请参阅我的示例结尾的示例)。我假设您实际上是在 barplot 之后。

您可以这样做

library(tidyverse)
x %>%
    gather(Location, Value, -Parameter) %>%
    ggplot(aes(x = Parameter, y = Value, fill = Location)) +
    geom_bar(stat = "identity")

enter image description here

或者带有闪避的杠铃

x %>%
    gather(Location, Value, -Parameter) %>%
    ggplot(aes(x = Parameter, y = Value, fill = Location)) +
    geom_bar(stat = "identity", position = "dodge")

enter image description here


为演示为什么箱形图没有什么意义,让我们展示该图

x %>%
    gather(Location, Value, -Parameter) %>%
    ggplot(aes(x = Parameter, y = Value, colour = Location)) +
    geom_boxplot()

enter image description here

请注意,每组一次观察会导致 bar 减少为一条水平线。这可能不是您想要显示的内容。