【问题标题】:Barplot with ggplot2带有 ggplot2 的条形图
【发布时间】:2016-11-28 15:10:39
【问题描述】:

我想绘制一个条形图,在每个峰值显示行业 1 和行业 2 的条形

library(ggplot2)
peaks=c(-3:3)
industry1=c(0.05,0.1,0.2,0.3,0.2,0.1,0.05)
data1=data.frame(peaks,industry1)
industry2=c(0.2,0.15,0.12,0.06,0.12,0.15,0.2)
data2=data.frame(peaks,industry2)
ggplot(data=data1,aes(x=peaks,y=industry1,fill=industry1) + geom_bar(stat="identity", position="stack")
gg=g+geom_bar(data=data2,aes(x=peaks,y=industry2,col="blue",show_guide=TRUE))

如果我运行它,它会说它不起作用

【问题讨论】:

    标签: r plot bar-chart


    【解决方案1】:
    library(ggplot2)
    peaks=c(-3:3)
    industry1=c(0.05,0.1,0.2,0.3,0.2,0.1,0.05)
    data1=data.frame(peaks,industry1)
    industry2=c(0.2,0.15,0.12,0.06,0.12,0.15,0.2)
    data2=data.frame(peaks,industry2)
    gg = ggplot(data=data1,aes(x=peaks,y=industry1,fill=industry1)) + geom_bar(stat="identity", position="stack")
    gg
    

    调用 ggplot() 的语法错误

    【讨论】:

      【解决方案2】:

      你是这个意思吗?否则,请提供您尝试绘制的示例图像。

      library(ggplot2)
      peaks <- c(-3:3)
      industry1 <- c(0.05,0.1,0.2,0.3,0.2,0.1,0.05)
      industry2 <- c(0.2,0.15,0.12,0.06,0.12,0.15,0.2)
      dat <- rbind(data.frame(peaks, industry = industry1, ind = "industry1"),
                   data.frame(peaks, industry = industry2, ind = "industry2"))
      ggplot(dat, aes(peaks, industry, fill = ind)) + 
        geom_bar(stat = "identity", position = "dodge")
      

      【讨论】:

        【解决方案3】:

        您可能正在寻找两个行业的合并数据框。

        mrg <- merge(data1, data2, by="peaks")
        mrgmelt <- reshape2::melt(mrg, id="peaks")
        ggplot(mrgmelt, aes(peaks, value, fill=variable)) +
          geom_bar(position="stack", stat="identity")
        

        【讨论】: