我有以下格式的数据。我想按周(即按周分组)计算发生次数。
"CaseNumber" "StartDate" "PatAge" "CallerZip"
"a" "7/4/2017 11:21:00 PM" "10" "12345"
"b" "7/5/2017 3:38:03 PM" "10" "12245"
"c" "7/15/2017 3:38:03 PM" "10" "12245"
我可以在另一个程序中将此文件转换为以下格式,但是我想知道是否有办法在gnuplot中进行处理。
Week Count
1 2
2 1
This question建议在另一个程序中进行转换(然后图形化)可能会更容易。我的问题与this one不同,因为我无法通过截断"StartDate"
答案 0 :(得分:2)
Gnuplot的时间格式为%W(请参见help time_specifier
)
%W week of the year (week starts on Monday)
您可以使用strptime()将日期从字符串转换为数字秒,然后使用strftime()从秒返回星期#来读取日期。要查看其工作原理,请尝试以下命令顺序
date1 = "7/15/2017 3:38:03 PM"
s1 = strptime("%m/%d/%Y", date1)
print s1
1500076800.0
week = strftime("%W", s1)
print week
28
输入函数timecolumn(column,format)的工作方式与strptime相同,只是它从输入数据列而不是字符串变量中读取。 要在读取数据文件时将所有这些信息进行一次评估,最简单的方法就是定义一个函数。我将展示使用此功能来简单地绘制星期数,然后将其留给您使用,以便将周数用于您想要的其他内容
weekno(column) = int(strftime("%W", timecolumn(column,"\"%m/%d/%Y")))
plot "file" skip 1 using 0:(weekno(2)) with points
注意:
skip 1
是一种忽略数据第一行中的标题注释的方法答案 1 :(得分:1)
我了解您的问题,您基本上想创建一个间隔为一周的事件直方图。
您可以使用smooth freq
进行此操作。选中help smooth
。
装仓间隔将是一周或3600*24*7
秒。
我稍微修改了您的时间格式。这种带有AM/PM
“总是”的12小时格式会产生问题,并且不能被gnuplot读取(尚未,但是在下一版本中。请参见此处的评论:gnuplot: how to convert 12h time format into 24h time format?)。
代码:
### count occurrences by week
reset session
myTimeFmt = '"%m/%d/%Y %H:%M:%S"'
StartDate = '"01/01/2017 00:00:00"'
EndDate = '"12/31/2017 23:59:59"'
# create some test data
# function for creating a random date between two dates
t(date_str) = strptime(myTimeFmt, date_str)
Random_Date(d0,d1) = strftime(myTimeFmt,rand(0)*(t(d1)-t(d0)) + t(d0))
Alphabet = "abcdedfghijklmnopqrstuvwxyz"
set print $Data
do for [i=1:200] {
rand26 = int(rand(0)*26)+1
RandomChar = Alphabet[rand26:rand26]
print sprintf('"%s" %s "%d" "%d"',RandomChar,Random_Date(StartDate,EndDate), \
int(rand(0)*100)+1, int(rand(0)*9e6)+1e6)
}
set print
# print $Data # uncomment if you want to see the random data
set style fill solid 1.0
set boxwidth 0.7
set xlabel "Weeks after start date"
set xtics out
set ylabel "Occurrences per week"
set ytics out
# binning for histogram
bin(n) = floor((timecolumn(n,myTimeFmt)-strptime(myTimeFmt,StartDate))/3600/24/7)+1
# either print a table or directly plot the result
set table $Occurrences
plot $Data u (bin(2)) smooth freq
unset table
print $Occurrences
plot $Data u (bin(2)) smooth freq w boxes notitle
### end of code
结果: