我正在尝试并排绘制以下数据集
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")
最佳答案
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"
现在工作。您不必使用文字填充颜色作为区别。这是一个使用数据集编号的版本。
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"))
除了图异常(exception),这是相同的。
关于r - 带有 ggplot2 的多个直方图 - 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8901330/