In a dataframe, I have a column which has values(price) from 1 to 500. I need to create a pie chart with 3 buckets, 1-10, 10-50, greater than 100. It should show the percentage contribution to it. How to do this in R?
does that help you:
library(tidyverse)
df <- as_tibble(seq(1,500)) %>% rename(price=value)
so the data looks like (its stupid, but its an example, use your data):
# A tibble: 500 x 1
price
<int>
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
# ... with 490 more rows
than we do:
df %>%
mutate(bucket=ifelse(price<=10, "1-10",
ifelse(price>10 & price<=50, "11-50", "50<"))) %>%
count(bucket) %>%
mutate(percent=n/nrow(df)*100) %>%
ggplot(aes(x="", y=percent, fill=bucket)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0)
with mutate
we define the buckets and the percentage. with ifelse
we simply say: if
price = x, than
mark it as y, else
do ...
That's the resulting chart: