生成可以计算恢复百分比的直方图

Generating histogram that can calculate percent recovered

我有以下名为 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 显示(我理解是这种情况,因为后者是条形图而不是直方图)。

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

如果我 运行 你的代码我会出错。您需要使用 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()

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