如何对一周中的某天进行直方图绘制并具有字符串标签 [英] How to histogram day-of-week, and have string labels
问题描述
我有一个日期数据框(Date对象);见底部. 我正在尝试将它们转换为星期几,然后绘制直方图,但理想情况下,标签为'Monday'...'Sunday'(非数字)
I have a data-frame of dates (Date object); see bottom. I'm trying to convert them to day-of-week and then draw a histogram, but ideally where the labels are 'Monday'...'Sunday' (not numeric)
我有两个不同的问题:
- 轻松地将Date对象转换为day-of-周,但结果是字符串或数字,而不是对象.
- 当我得到直方图时,垃圾箱和标签是错误的(请参阅下文).
- It's easy to convert a Date object to day-of-week, but the result is string or numeric, not an object.
- When I get a histogram, the bins and labels are wrong (see below).
如果我使用weekdays(dat)
,则输出为字符串(星期一" ...),不能在hist()
中使用.
If I use weekdays(dat)
, the output is string ("Monday"...) which cannot be used in hist()
.
或者,如果我转换为数字数据,如何在hist()
上获取字符串标签?
Alternatively, if I convert to numeric data, how to get string labels on hist()
?
> dotw <- with( month.day.year(dat[,1]), day.of.week(month,day,year) )
> hist(xxx,labels=c('M','Tu','W','Th','F','Sa','Su'),col='black') # WTF?!
> hist(dotw,xlab=list('M','Tu','W','Th','F','Sa','Su'))
不能按预期的方式工作. 0.5宽度的垃圾箱是什么?而且,如何防止在周日-> 0和周一-> 1之间缺少间隔?理想情况下,列之间没有间隙.
Does not work as intended for labeling. What's with the 0.5-width bins? And also, how to prevent the lack of gap between Sunday->0 and Monday->1? Ideally, no gaps between columns.
我的数据如下:
> dat
[1] "2010-04-02" "2010-04-06" "2010-04-09" "2010-04-10" "2010-04-14" "2010-04-15" "2010-04-19"
[8] "2010-04-21" "2010-04-22" "2010-04-23" "2010-04-26" "2010-04-28" "2010-04-29" "2010-04-30"
...
> str(dat)
Date[1:146], format: "2010-04-02" "2010-04-06" "2010-04-09" "2010-04-10" "2010-04-14" "2010-04-15" ...
> str(weekdays(dat))
chr [1:146] "Friday" "Tuesday" "Friday" "Saturday" "Wednesday" "Thursday" "Monday" ...
> hist(weekdays(dat))
Error in hist.default(weekdays(dat)) : 'x' must be numeric
推荐答案
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)]))
这篇关于如何对一周中的某天进行直方图绘制并具有字符串标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!