[英]Plot multiple columns with geom_bar()
I recently started programming in R and I am trying to plot several columns using ggplot2.我最近开始在 R 中编程,我正在尝试使用 ggplot2 对 plot 几列进行编程。
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:为了了解我是如何创建这个数据框的,“Less”看起来像这样:
[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.在 x 轴上,我实际上想要 plot “更多”、“更少”和“相等”,每个名称都有不同的条形。 On the y-axis I want to print the score (eg 8, 25...).在 y 轴上,我想打印分数(例如 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:我已经尝试了几件事,但我只成功地在 y 轴上添加了一个值:
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这是一个例子: 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.您可以使用 data.table package 将数据融合为长格式。
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".如果你想要分组图表,你可以指定 position="dodge"。
ggplot(df, aes(x = category , y= scores, fill = Names)) +
geom_bar(position="dodge", stat = "identity")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.