如何绘制ggplot2中每个bin的y为x值之和的直方图

问题描述:

我有一个PV数据框,其中包含有关太阳能发电厂的信息.一个变量是千瓦的发电功率:

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    231.9
...  

我正在尝试绘制功率为X值且带宽为50 kW的直方图.作为Y,我想显示箱柜范围内每个工厂的累积功率. 我尝试了此代码,但没有成功.

I'm trying to plot an histogram with power as X values with a binwidth of 50 kW. As Y I would like to show the cumulative power for every plant in the range of the bin. I tried this code without success.

ggplot(pv, aes(x = power, y = sum(power)), stat = "bin") + 
    geom_histogram(stat = "identity", binwidth=50)

我需要使用cut函数来计算总和,还是可以使用ggplot2直接生成该图?

I need to calculate the sum by using the cut function or it is possible to generate this graph directly with ggplot2?

这应该做您想要的:

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

weight的审美观迫使stat计算将每个计数乘以相应的权重,在这种情况下,这等同于对幂值求和.

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.

这是更好的可视化效果:

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