多个直方图与ggplot2 - 位置

Gag*_*lva 13 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))
Run Code Online (Sandbox Code Playgroud)

我试图为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")
Run Code Online (Sandbox Code Playgroud)

Bri*_*ggs 24

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))
Run Code Online (Sandbox Code Playgroud)

我添加了一个fill列,其中包含您在直方图中使用的值.鉴于此,情节可以用:

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

position="dodge"现在在哪里工作.

在此输入图像描述

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

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"))
Run Code Online (Sandbox Code Playgroud)

除了传说之外,这是相同的.

在此输入图像描述