簡體   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