ggplot2subset

subsetting withinin ggplot2 command


Sorry if there´s already a thread on this, but I could´t find ther solution for my problem with existing posts! I try to create a barplot subsetting a large dataframe in the gplot2 code. This is a simplified example of how my df looks like:

location year measurement value treatment
1 22 parameter1 3 A
2 23 parameter2 2 B
2 24 parameter1 4 A
1 22 parameter3 2 C

What I try to get are basicly distinct barplots for location 1 and 2, compairing the values from different measurements in dependence of treatment over time. Values should be shown on the y-axis, year on the x-axis and the treatment displayed by the filling. I´d like to understand how to put all this into my ggplot-code instaed of creating 1000 subsets. That´s the code I came up with:

  plot_location1<-
  ggplot(df[df$location=="1",]+
  aes(fill=treatment, y=total[total$measurement=="parameter1",] x=year) + 
  geom_bar(position="stack", stat="identity"))

I´ve been playing around with this structure since a bit and keep receiving different error messages; with the upper code it says list of length 3 not meaningful. I´m happy to learn how to effectively subset within the ggplot command, as I guess that´s what I´m doing wrong :P Many thanks in advance!


Solution

  • Like this?

    library(ggplot2)
    
    df <- data.frame(
      location = c(1, 2, 2, 1),
      year = c(22, 23, 24, 22),
      measurement = c("parameter1", "parameter2", "parameter1", "parameter3"),
      value = c(3, 2, 4, 2),
      treatment = c("A", "B", "A", "C")
    )
    
    ggplot(df, aes(x = factor(year), y = value, fill = treatment)) +
      geom_bar(stat = "identity", position = "stack") +
      facet_wrap(~ location) +
      labs(x = "Year", y = "Value", fill = "Treatment") +
      theme_minimal()
    

    enter image description here