多个直方图与ggplot2 - 位置

时间:2012-01-17 20:31:18

标签: r 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添加选项 position =“dodge”而没有运气。如何更改以下代码以并排绘制直方图列而不重叠??

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")

1 个答案:

答案 0 :(得分:23)

ggplot2最适合" long"数据,其中所有数据都在单个数据帧中,而不同的组由数据帧中的其他变量描述。为此

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