首页 文章

列具有特定值时的百分比图

提问于
浏览
-3

我怎样才能有一个图表,表明列时间为晚餐的天数百分比 . 换句话说,如果我们考虑 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

1 回答

  • 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")
    

    上述数据的样本输出:

    snap1

相关问题