如何制作一个图表,指示列时间为晚餐的天数百分比。换句话说,如果我们考虑time == Dinner
的数据子集,我如何在这个子集中显示Sat,Sun,Mon,Tue,Wed,Thu,Fri的百分比。我想要一个bar_plot来展示这件事。
> library(ggplot2)
> #sample data
> head(tips,3)
total_bill tip sex smoker day time size
1 17 1.0 Female No Sun Dinner 2
2 10 1.7 Male No Sun Dinner 3
3 21 3.5 Male No Sun Dinner 3
答案 0 :(得分:0)
使用count
函数计算每天发生的次数和barplot
函数来绘制
#generating sample dataframe
tips <- data.frame(total_bills=1:10, tip=10:19, sex=sample(c("male","female"),10, replace = TRUE), smoker=sample(c("yes","no"),10, replace = TRUE), day = sample(c("Mon","Tue","Wed","Fri","Sat","Sun"),10, replace = TRUE),time=sample(c("Breakfast","Lunch","Dinner"),10, replace = TRUE),size = sample(1:5,10, replace = TRUE), stringsAsFactors = FALSE)
#count the number of occurences using _count_ function
io <- plyr::count(tips[tips$time == "Dinner",], vars = "day")
#getting days percentage
io$count_percent <- round(io$freq/sum(io$freq) * 100,2)
> io
day freq count_percent
1 Sun 1 20
2 Tue 2 40
3 Wed 2 40
#generate barplot
require(ggplot2)
p <- ggplot(io, aes(day, count_percent))
p + geom_bar(stat = "identity")
以上数据的样本输出: