Matt
Matt

Reputation: 333

Boxplots grouped by group value

I have the following example data frame:

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)

The Parameter column holds the names of the heavy metal and Loc1 to Loc4 columns hold the measured value of the heavy metal at the individual location.

I need a plot with one boxplot for each heavy metal at each location. The location is the grouping value. I tried the following:

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

However, the resulting plot did not somehow grouped the boxplots by location.

Upvotes: 1

Views: 73

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

A boxplot with one observation per Parameter per Location makes little sense (see my example at the end of my post). I assume you are in fact after a barplot.

You can do something like this

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

enter image description here

Or with dodged bars

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

enter image description here


To demonstrate why a boxplot makes little sense, let's show the plot

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

enter image description here

Note that a single observation per group results in the bar being reduced to a single horizontal line. This is probably not what you want to show.

Upvotes: 2

Related Questions