0

I recently started programming in R and I am trying to plot several columns using ggplot2.

My data frame looks like this:

mydf <- data.frame(Names, Less, Equal, More)
mydf

    Names Less Equal More
1   Sarah    8    25    8
2   Mark    13    13   13
3   Peter   11    26    5

And to give an idea of how I created this data frame, 'Less' looks like this:

[1]  8 13 11

I want to be able to compare for every name if their scores are less, equal, or more. On the x-axis, I actually want to plot "More", "Less", and "Equal", with different bars for each name. On the y-axis I want to print the score (e.g. 8, 25...). I want to create multiple bars for each name.

I have tried several things, but I have only succeeded in adding a single value on the y-axis:

test <- ggplot(mydf, aes(x= Names, y= More)) +
geom_bar(stat = "identity") 

I have a feeling that the problem lies with the way my data is organised, but I am not sure.

1
  • Could you add current and expected plots? Commented May 11, 2020 at 17:27

2 Answers 2

4

you need to change your data to long format where one column is for values and another for labels:

    Names values label
1   Sarah    8    less
2   Mark    13    less
3   Peter   11    less
1   Sarah    25    equal
2   Mark    13    equal
3   Peter   26    equal
1   Sarah    8    more
2   Mark    13    more
3   Peter   5    more

then the code will be

test <- ggplot(mydf, aes(x= label, y= values, fill=names)) +
  geom_bar(position="dodge",  stat="identity") 
test

here is an example:https://www.r-graph-gallery.com/48-grouped-barplot-with-ggplot2.html

Sign up to request clarification or add additional context in comments.

Comments

2

You can use the data.table package to melt the data into long format.

library(data.table)

df <- melt(mydf, id.vars = "Names", variable.name = "category",
           value.name="scores")

If you want to have the grouped chart, you can specify position="dodge".

ggplot(df, aes(x = category , y= scores, fill = Names)) +
  geom_bar(position="dodge", stat = "identity")

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.