2017-08-09 20 views
-3

如何获得一个指示列时间为晚餐的天数百分比的图表。换句话说,如果我们考虑数据子集time == Dinner,如何显示星期六,星期日,星期一,星期二,星期三,星期四,星期五的百分比。我想有一个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

+0

如何使用ggplot2包:ggplot()+ geom_bar()? – far

+0

另外我想百分比显示不是计数 – far

+0

oops,我错过了粘贴'%'计数代码在这里,_wait_ – parth