如何用ggplot填充间隔内的密度图?

下面的代码在曲线区域下用颜色填充两个密度中的每一个:

@Directive({
  selector: '[appBackdropClass]'
})
export class PanelClassDirective implements DoCheck {
  @Input('appBackdropClass') panelClass: string;

  constructor(private _host: MatSelect) {
  }

  ngDoCheck(): void {
    if (this._host.overlayDir) {
      this._host.overlayDir.hasBackdrop = true;
      this._host.overlayDir.backdropClass = this.panelClass;
    }
  }
}

我如何实现以下两个目标?

1)仅在指定间隔内填充每条曲线。例如,“ C”组的间隔为[-1.5,2.0],而“ P”组的间隔为[0.5,2.8]。

2)为每个密度添加一个垂直线段(从x轴到曲线)。例如,“ C”组的x = 0.2,而“ P”组的x = 1.9。

a55713766 回答:如何用ggplot填充间隔内的密度图?

要让您凝视,这是您的第一个问题:

library(dplyr)
library(purrr)
library(tidyr)
library(ggplot2)

as.data.frame.density <- function(x) data.frame(x = x$x,y = x$y)

densities <- dat %>% 
  group_nest(group) %>% 
  mutate(dens = map(data,~as.data.frame(density(.$dens)))) %>% 
  unnest(dens)

ggplot(densities,aes(x = x,y = y,group = group)) + 
  geom_density(stat = 'identity') +
  geom_density(
    aes(fill = group),. %>% filter((group == "C" & between(x,-1.5,2.0)) | (group == "P" & between(x,0.5,2.8))),stat = 'identity',alpha = 0.75
  )

enter image description here

还有其他计算每组密度的方法,使用dplyr只是一种方法。为两个密度估计值设置一个相等的带宽可能是好的。

添加细分与这种方法类似,您只需要在densities data.frame中找到正确的值即可。

本文链接:https://www.f2er.com/2703619.html

大家都在问