【问题标题】:multiple histograms with ggplot2 - positionggplot2的多个直方图 - 位置
【发布时间】:2012-01-17 20:31:17
【问题描述】:

我正在尝试并排绘制以下数据集

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    除了图例之外,其他都是一样的。

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 2014-12-31
      • 1970-01-01
      • 2013-08-23
      • 2018-08-02
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多