使用ggplot2包绘制条形图来比较两组数据? [英] Drawing a barchart to compare two sets of data using ggplot2 package?

查看:43
本文介绍了使用ggplot2包绘制条形图来比较两组数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构建条形图以比较两组数据的最佳方法是什么?

What is the best way to construct a barplot to compare two sets of data?

例如数据集:

Number <- c(1,2,3,4)
Yresult <- c(1233,223,2223,4455)
Xresult <- c(1223,334,4421,0)
nyx <- data.frame(Number, Yresult, Xresult)

我想要的是 X 上的数字和表示单个 X 和 Y 值的条形图

What I want is Number across X and bars beside each other representing the individual X and Y values

推荐答案

最好将数据重塑为长格式.例如,您可以使用 reshape2 包的 melt 函数来做到这一点(替代方法是基于 R 的 reshapemelt> 来自 data.table(它是 reshape2melt 函数的扩展实现)和 gatherem>整洁).

It is better to reshape your data into long format. You can do that with for example the melt function of the reshape2 package (alternatives are reshape from base R, melt from data.table (which is an extended implementation of the melt function of reshape2) and gather from tidyr).

使用您的数据集:

# load needed libraries
library(reshape2)
library(ggplot2)

# reshape your data into long format
nyxlong <- melt(nyx, id=c("Number"))

# make the plot
ggplot(nyxlong) +
  geom_bar(aes(x = Number, y = value, fill = variable), 
           stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Result
", values = c("red","blue"), 
                    labels = c(" Yresult", " Xresult")) +
  labs(x="
Number",y="Result
") +
  theme_bw(base_size = 14)

给出以下条形图:

这篇关于使用ggplot2包绘制条形图来比较两组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆