How to plot an histogram with y as a sum of the x values for every bin in ggplot2

后端 未结 1 2044
死守一世寂寞
死守一世寂寞 2021-02-10 11:22

I have a pv dataframe containing information regarding solar plants. One variable is the generation power in kw:

id   power
1    20.1
2    110.1
3    3.0
4    2         


        
1条回答
  •  眼角桃花
    2021-02-10 12:15

    This should do what you want:

    set.seed(1)
    df <- data.frame(id=1:100, power=rlnorm(100, log(100)))
    ggplot(df) + 
      geom_histogram(aes(x=power, weight=power), binwidth=50) +
      ylab("Total Power (kW)")
    

    The weight aesthetic forces the stat calculation to multiply each count by the corresponding weight, which in this case is equivalent to summing the power values.

    enter image description here

    And here is a better visualization:

    ggplot(transform(df, power.bin=cut(power, 0:24 * 50, include.lowest=TRUE))) + 
      geom_bar(aes(x=power.bin, y=power), color="white", position="stack", stat="identity") +
      ylab("Total Power (kW)") + 
      scale_x_discrete(drop=F) +
      theme(axis.text.x=element_text(angle=90, vjust=.5, hjust=1))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题