【问题标题】:Generating histogram that can calculate percent recovered生成可以计算回收百分比的直方图
【发布时间】:2015-07-26 19:20:28
【问题描述】:

我有以下名为 df 的数据集:

  Amp Injected Recovered Percent less_0.1_True
  0.13175 25.22161274 0.96055540 3.81 0
  0.26838 21.05919344 21.06294791 100.02 1
  0.07602 16.88526724 16.91541763 100.18 1
  0.04608 27.50209048 27.55404507 100.19 0
  0.01729 8.31489333 8.31326976 99.98 1
  0.31867 4.14961918 4.14876247 99.98 0
  0.28756 14.65843377 14.65248551 99.96 1
  0.26177 10.64754579 10.76435667 101.10 1
  0.23214 6.28826689 6.28564299 99.96 1
  0.20300 17.01774090 1.05925850 6.22 0
  ...

这里,less_0.1_True 列标记了恢复期是否足够接近注入期以被视为成功恢复。如果标志为 1,则表示恢复成功。基于此,我需要生成如下图(Henderson & Stassun, the Astrophysical Journal, 747:51, 2012):

我不确定如何创建这样的直方图。我最接近的重现是带有以下代码的条形图:

breaks <- seq(0,30,by=1)
df <- split(dat, cut(dat$Injected,breaks)) # I make bins with width = 1 day
x <- seq(1,30,by=1)

len <- numeric() #Here I store the total number of objects in each bin
sum <- numeric() #Here I store the total number of 1s in each bin

for (i in 1:30){
n <- nrow(df[[i]])
len <- c(len,n)

s <- sum(df[[i]]$less_0.1_True == 1, na.rm = TRUE)
sum <- c(sum,s)
}

percent = sum/len*100 #Here I calculate what the percentage is for each bin
barplot(percent, names = x, xlab = "Period [d]" , ylab = "Percent Recovered", ylim=c(0,100))

它会生成以下条形图:

显然,这个图看起来不像第一个图,并且存在一些问题,例如它不像第一个图那样从 0 到 1 显示(我理解是这种情况,因为后者是条形图而不是直方图)。

谁能指导我如何根据我的数据集重现第一个数字?

【问题讨论】:

    标签: r plot histogram


    【解决方案1】:

    如果我运行你的代码,我会得到错误。您需要使用border = NA 来摆脱条形边框:

    set.seed(42)
    hist(rnorm(1000,4), xlim=c(0,10), col = 'skyblue', border = NA, main = "Histogram", xlab = NULL)
    

    另一个使用ggplot2的例子:

    ggplot(iris, aes(x=Sepal.Length))+
      geom_histogram()
    

    【讨论】:

      【解决方案2】:

      我终于在 StackOverflow 中找到了解决问题的方法。我想解决的问题的措辞与我的不同,所以当我最初寻找它时找不到它。解决方法在这里:How to plot a histogram with a custom distribution?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        • 2022-11-25
        • 1970-01-01
        相关资源
        最近更新 更多