2012-01-17 56 views
11

我试图通过边绘制边以下数据集与GGPLOT2多个直方图 - 位置

dataset1=data.frame(obs=runif(20,min=1,max=10)) 
dataset2=data.frame(obs=runif(20,min=1,max=20)) 
dataset3=data.frame(obs=runif(20,min=5,max=10)) 
dataset4=data.frame(obs=runif(20,min=8,max=10)) 

我试图添加选项位置=为没有运气geom_histogram“道奇”。如何更改以下代码以并排绘制直方图列而不重叠?

ggplot(data = dataset1,aes_string(x = "obs",fill="dataset")) + 
geom_histogram(binwidth = 1,colour="black", fill="blue")+ 
geom_histogram(data=dataset2, aes_string(x="obs"),binwidth = 1,colour="black",fill="green")+ 
geom_histogram(data=dataset3, aes_string(x="obs"),binwidth = 1,colour="black",fill="red")+ 
geom_histogram(data=dataset4, aes_string(x="obs"),binwidth = 1,colour="black",fill="orange") 

回答

22

GGPLOT2与“长”数据,其中所有的数据是在一个单一的数据帧和不同基团通过在数据帧中的其他变量描述效果最好。为此

DF <- rbind(data.frame(fill="blue", obs=dataset1$obs), 
      data.frame(fill="green", obs=dataset2$obs), 
      data.frame(fill="red", obs=dataset3$obs), 
      data.frame(fill="orange", obs=dataset3$obs)) 

,我已经添加了一个fill列其中有您在直方图中使用的值。鉴于此,情节可以进行:

ggplot(DF, aes(x=obs, fill=fill)) + 
    geom_histogram(binwidth=1, colour="black", position="dodge") + 
    scale_fill_identity() 

其中position="dodge"现在的作品。

enter image description here

您不必使用文字填充颜色作为区分。这是一个使用数据集编号的版本。

DF <- rbind(data.frame(dataset=1, obs=dataset1$obs), 
      data.frame(dataset=2, obs=dataset2$obs), 
      data.frame(dataset=3, obs=dataset3$obs), 
      data.frame(dataset=4, obs=dataset3$obs)) 
DF$dataset <- as.factor(DF$dataset) 
ggplot(DF, aes(x=obs, fill=dataset)) + 
    geom_histogram(binwidth=1, colour="black", position="dodge") + 
    scale_fill_manual(breaks=1:4, values=c("blue","green","red","orange")) 

这是除了图例相同。

enter image description here