How do you create a vertical bar plot that contains a conditional if statement in R?

Viewed 37

I have a data set that is measuring emotions of respondents as they are shown different stimuli. Here is an example:

Sample   Attribute   Score   Rank
A        Delighted   180     High
A        Happy       200     High
A        Tired       130     Medium
B        Delighted   160     Medium
B        Happy       128     Low
B        Tired       115     Low

I am fairly new to R, and I'm having issues actually making a bar chart that only shows sample A. This is what I tried doing:

ggplot(data =
         filter(DATA, Category == "A"), 
       mapping = aes(x = Score, y = Attribute)) +
  geom_

But R gives me this error:

Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class mts/ts.

Ideally, I am trying to get a bar chart that has the attributes listed on the vertical axis, the scores on the x-axis, and only shows sample A, with the bars color coded by Rank. Any help would be great!

1 Answers

Welcome to SO. Starting with the ggplot2 reference site and working through the examples there will help you get oriented to working with your data and plotting it in ggplot2. That said, here are some suggestions to get you started.

First, as indicated by the error, you need a dataframe, rather than whatever format your data is currently stored in. Based on what you gave me, this is how I got a data.frame, but you might use something else.

t <- "Sample   Attribute   Score   Rank
A        Delighted   180     High
A        Happy       200     High
A        Tired       130     Medium
B        Delighted   160     Medium
B        Happy       128     Low
B        Tired       115     Low"

df <- read.table(text=t, header=T)

## this might be more relevant for your current situation
df <- as.data.frame(DATA)

Try not to use "data" as an object name, as it is already a named function.

Second, if you're learning R, it's probably wise to separate steps in your analysis to ensure you understand what each part is doing. So next do the subset to get just Sample A.

library(tidyverse)

df.sub <- df %>%
  filter(Sample=="A")

Now it'll be easier to do the plotting. Your plotting code looked like it was on the right track, but you didn't complete the line.

library(ggplot2)

ggplot(df.sub, aes(x=Score, y=Attribute, fill=Rank)) +
  geom_bar(stat="identity")

You'll need to specify stat="identity" to tell ggplot that you want it to recognize the values you provide as data, rather than generating counts (as for a histogram).

This should get you what you are looking for.

enter image description here

Related