绘制条形图以使用ggplot2软件包比较两组数据? [英] Drawing a barchart to compare two sets of data using ggplot2 package?
问题描述
构建一个barplot来比较两组数据的最好方法是什么?
例如,数据集:
数字<-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值。
最好将数据重塑为长格式。你可以通过例如 reshape2 包的 melt
函数来做到这一点(替代方案是 reshape
从基础R开始, melt
from data.table (这是 melt的扩展实现
reshape2 的功能)和从 tidyr 收集
)。
使用你的数据集:
#load needed libraries
library(reshape2)
library ggplot2)
#将数据整形为长格式
nyxlong< - melt(nyx,id = c(Number))
#
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)
给出t他遵循条形图:
What is the best way to construct a barplot to compare two sets of data?
e.g. dataset:
Number <- c(1,2,3,4)
Yresult <- c(1233,223,2223,4455)
Xresult <- c(1223,334,4421,0)
nyx <- data.frame(Number, Yresult, Xresult)
What I want is Number across X and bars beside each other representing the individual X and Y values
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).
Using your dataset:
# 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\n", values = c("red","blue"),
labels = c(" Yresult", " Xresult")) +
labs(x="\nNumber",y="Result\n") +
theme_bw(base_size = 14)
which gives the following barchart:
这篇关于绘制条形图以使用ggplot2软件包比较两组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!