Home > Mobile >  R: how to filter within aes()
R: how to filter within aes()

Time:11-17

As an R-beginner, there's one hurdle that I just can't find the answer to. I have a table where I can see the amount of responses to a question according to gender.

Response Gender n
1 1 84
1 2 79
2 1 42
2 2 74
3 1 84
3 2 79

etc.

I want to plot these in a column chart: on the y I want the n (or its proportions), and on the x I want to have two seperate bars: one for gender 1, and one for gender 2. It should look like the following example that I was given:

enter image description here

CodePudding user response:

Your answer does not work, because you are assigning the x and y variables as if it was two different datasets (one for x and one for y). In line with the solution from TarJae, you need to think of it as the axis in a diagram - so you need for your x axis to assign the categorical variables you are comparing, and you want for the y axis to assign the numerical variables which determines the height of the bars. Finally, you want to compare them by colors, so each group will have a different color - that is where you include your grouping variable (here, I use fill).

    library(dplyr) ## For piping
    library(ggplot2) ## For plotting
    
    df  %>% 
    ggplot(aes(x = Response, y = n, fill = as.character(Gender)))  
      geom_bar(stat = "Identity", position = "Dodge")

I am adding "Identity" because the default in geom_bar is to count the occurences in you data (i.e., if you data was not aggregated). I am adding "Dodge" to avoid the bars to be stacked. I will recommend you, to look at this resource for more information: https://r4ds.had.co.nz/index.html

  • Related