繁体   English   中英

如何在 R 中将分布绘制为组合图?

[英]How to plot the distribution as combo chart in R?

这是我的初始数据集:

data_x <- tribble(
  ~price,     ~id,     ~cost,    ~revenue,
     1,        10,      0.20,        0,      
     2,        20,      0.30,       60,  
     3,        20,      0.30,        0,
     4,        10,      0.20,      100, 
     5,        30,      0.10,       40,
     6,        10,      0.20,        0,
     1,        20,      0.30,       80,
     2 ,       10,      0.20,        0,
     3,        30,      0.10,       20,
     3,        20,      0.30,       40,
)

然后,我有一个新的变量 zet:

data_y <- data_x %>% 
  mutate(zet = cost/revenue) %>% 
  mutate_if(is.numeric, list(~na_if(., Inf))) %>% 
  mutate_all(funs(replace_na(.,0)))

现在,我在显示 zet 分布的同时绘制价格分布。 这是我想要的情节:

在此处输入图片说明

为此,我首先想查看价格和 zet 分布,即使它们现在不是百分比。

price_dist <- data_y %>% 
  group_by(priceseg = cut(as.numeric(price), c(0, 1, 3, 5, 6))) %>% 
  summarise(price_n = n_distinct(price)) %>% 
  pivot_wider(names_from = priceseg, values_from = price_n)

zet_dist <- data_y %>% 
  group_by(priceseg = cut(as.numeric(price), c(0, 1, 3, 5, 6))) %>% 
  summarise(zet_n = n_distinct(zet)) %>% 
  pivot_wider(names_from = priceseg, values_from = zet_n)

如果您能帮我绘制我想要的图表,我将不胜感激。

d <- data_y %>% 
    group_by(priceseg = cut(as.numeric(price), c(0, 1, 3, 5, 6))) %>% 
    summarise(price_n = n_distinct(price), 
              zet_n = n_distinct(zet)) %>%
    mutate(price_n = 100 * prop.table(price_n),
           zet_n2 = 100 * prop.table(zet_n))
ggplot(d) +
    geom_col(aes(x = priceseg, y = price_n)) +
    geom_line(data = d, mapping = aes(x = priceseg, y = zet_n2, group = 1)) +
    geom_label(data = d, mapping = aes(x = priceseg, y = zet_n2, label = zet_n), nudge_y = 5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM