How to histogram day-of-week, and have string labels

纵然是瞬间 提交于 2019-12-05 10:19:44
dat <- as.Date( c("2010-04-02", "2010-04-06", "2010-04-09", "2010-04-10", "2010-04-14", 
       "2010-04-15", "2010-04-19",   "2010-04-21", "2010-04-22", "2010-04-23","2010-04-24", 
        "2010-04-25", "2010-04-26", "2010-04-28", "2010-04-29", "2010-04-30"))
 dwka <- format(dat , "%a")
 dwka
# [1] "Fri" "Tue" "Fri" "Sat" "Wed" "Thu" "Mon"
#  [8] "Wed" "Thu" "Fri" "Sat" "Sun" "Mon" "Wed"
# [15] "Thu" "Fri"
dwkn <- as.numeric( format(dat , "%w") ) # numeric version
hist( dwkn , breaks= -.5+0:7, labels= unique(dwka[order(dwkn)]))

I suspect you want a barplot rather than a histogram. You can use table to count the days.

barplot(table(weekdays(dat)))

Note that by default the days will be sorted alphabetically, so to order it more naturally you will have to reorder the levels in a factor call:

barplot(table(factor(weekdays(dat),levels=c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"))))

Convert your weekdays(dat) to a factor (data type for categorical variables), and unclass it (which will convert to integer) for the histogram. There are operations on the factor class which makes it easy to create the custom x-axis.

## days of the week
days <- c('Sun','Mon','Tues','Wed','Thurs','Fri','Sat')

## sample with replacement to generate data for this example
samples <- sample(days,100,replace=TRUE)

## convert to factor
## specify levels to specify the order
samples <- factor(samples,levels=days)

hist(unclass(samples),xaxt="n")
axis(1,at=1:nlevels(samples),lab=levels(samples))
box()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!