I am new to R and ggplot2. I have a dataset that I want to visualize with stacked bar chart, where
Example..
total_bill | tip | sex | smoker | day | time | size |
---|---|---|---|---|---|---|
16.99 | 1.01 | Female | No | Sun | Dinner | 2 |
10.34 | 1.66 | Male | No | Sun | Dinner | 3 |
data(tips, package='reshape2')
ggplot(tips, aes(x=sex)) +
geom_bar(aes(fill=day), width = 0.5, position = 'fill')+
theme(axis.text.x = element_text(angle=65, vjust=0.6))
from here, I want to make the following changes in the chart.
library(tidyverse)
data(tips, package='reshape2')
tips %>%
#Calculating percentage by sex outside ggplot2
count(sex,day) %>%
group_by(sex) %>%
mutate(p = 100*n/sum(n)) %>%
ungroup() %>%
#Removing Friday
filter(day != "Fri") %>%
#Ordering sex by Saturday percentage
mutate(
sex = fct_reorder2(
.f = sex,
.x = p,
.y = day,
.fun = function(x,y) max(x[y == "Sat"])
)
) %>%
ggplot(aes(x = sex, y = p)) +
geom_col(aes(fill=day))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments