Here is my initial data set:
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,
)
Then, I have a new variable that is zet:
data_y <- data_x %>%
mutate(zet = cost/revenue) %>%
mutate_if(is.numeric, list(~na_if(., Inf))) %>%
mutate_all(funs(replace_na(.,0)))
Now, I plot the price distribution while showing the zet distribution, as well. Here is my desired plot:
To do this, I first wanted to see price and zet distribution even they are not percentage now.
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)
I would be grateful if you could help me to plot my desired chart.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.