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 (eg 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.
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
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.