在堆叠 geom_col 图上叠加密度曲线? [包括代码和图像]

Overlay Density Curve on stacked geom_col plot? [code & images included]

# Creating overlayed barchart with ggplot 
dist_plot_prom_delv_Mon <-  ggplot(union_df_prom_delv_Mon,aes(x=Promise,y=Orders,fill=Flag)) + 
        geom_bar(stat="identity",position = "identity", alpha= .50, show.legend = FALSE)+
  theme_economist()+
  scale_x_continuous(breaks=seq(0,30,1))+
  xlab("Promise & Delv Days") +
  ylab("Count of Orders") +
 scale_fill_manual(values = c("sandybrown", "cadetblue4"))+
  ggtitle("E2E Promise & Delv Distribution Comparison 2020 YTD - Monday Orders")+
   theme(plot.title = element_text(size=12), axis.text=element_text(size=11), 
        axis.title=element_text(size=11), strip.text = element_text(size=11),
        axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)),
        axis.title.x = element_text(margin = margin(t = 15, r = 15, b = 0, l = 0)))

我目前有一个“直方图”,它是通过使用 geom_col 制作重叠条形图并使用填充使数据看起来像是重叠的来创建的。 查看下面的当前图片

我想叠加一个附加层,它是具有低 alpha 的密度线,类似于此 图像。

我不得不使用 geom_col 来模仿 geom_histogram 因为 geom_histogram 计算我的度量值不正确。这是我的数据示例以及覆盖的内容。

dist_plot_prom_delv <-  ggplot(union_df_prom_delv,aes(x=Promise,y=Orders,fill=Flag)) + 
        geom_bar(stat="identity",position = "identity", alpha= .50, show.legend = FALSE)+
  theme_economist()+
  scale_x_continuous(breaks=seq(0,30,1))+
         geom_density(fill="darkgrey", alpha=0.3)+
  xlab("Promise & Delv Days") +
  ylab("Count of Orders") +
 scale_fill_manual(values = c("sandybrown", "cadetblue4"))+
  ggtitle("E2E Promise & Delv Distribution Comparison 2020 YTD ")+
   theme(plot.title = element_text(size=12), axis.text=element_text(size=11), 
        axis.title=element_text(size=11), strip.text = element_text(size=11),
        axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)),
        axis.title.x = element_text(margin = margin(t = 15, r = 15, b = 0, l = 0)))




plot_prom2_Mon <- step1_fix %>% 
  rename(Promise = E2E_PROMISE_DAYS) %>% 
  group_by(Promise) %>% 
  filter(ORD_DOW == 'Monday') %>% 
  summarise(Orders = n_distinct(ORD_TRACK_KEY)) %>% 
  mutate(Flag = "Promise")

# Creating Logic to create union for overlayed bar chart 
plot_delv2_Mon <- step1_fix %>% 
  rename(Promise = E2E_BUS_DAYS) %>% 
  group_by(Promise) %>% 
  filter(ORD_DOW == 'Monday') %>% 
  summarise(Orders = n_distinct(ORD_TRACK_KEY)) %>% 
  mutate(Flag = "Delv")

# Creating union to create overlayed barchart
union_df_prom_delv_Mon <- union_all(plot_prom2_Mon, plot_delv2_Mon)

添加透明区域命令:

geom_area(aes(color=Fill), alpha=0.3, position="identity") +
theme(legend.position = "none") #for deleting the legend