如何在SAS中绘制简单的线图

D. *_*der 4 aggregate sas timeserieschart sgplot

我的数据结构如下(这些只是示例数据,因为原始数据是秘密的)

id | crime   | location | crimedate
------------------------------
1  | Theft   | public   | 2019-01-04
1  | Theft   | public   | 2019-02-06
1  | Theft   | public   | 2019-02-20
1  | Theft   | private  | 2019-03-10
1  | Theft   | private  | 2019-03-21
1  | Theft   | public   | 2019-03-01
1  | Theft   | private  | 2019-03-14
1  | Theft   | public   | 2019-06-15
1  | Murder  | private  | 2019-01-04
1  | Murder  | private  | 2019-10-20
1  | Murder  | private  | 2019-11-18
1  | Murder  | private  | 2019-01-01
1  | Assault | private  | 2019-03-19
1  | Assault | private  | 2019-01-21
1  | Assault | public   | 2019-04-11
1  | Assault | public   | 2019-01-10
…  | …       | …        | … 
Run Code Online (Sandbox Code Playgroud)

我的目标是创建一个线图(时间序列图),以显示三种犯罪的数量在一年中如何变化。因此,我想在x轴上显示月份数(1-12),在y轴上显示每个月的犯罪数量。应该有两行(每个位置一行)。

我从以下代码开始:

DATA new;
 SET old;
 month=month(datepart(crimedate));
RUN;

PROC sgplot DATA=new;
    series x=month y=no_of_crimes / group=location;
run;
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何汇总每月的犯罪数量。有人可以给我一个提示吗?我一直在互联网上寻找解决方案,但是通常示例仅使用已经聚合的数据。

Ric*_*ard 6

SG例程将为VBARor HBAR语句聚合Y轴值。SERIES语句中显示的相同聚合信息必须来自先验聚合计算,可轻松实现Proc SUMMARY

此外,要在单独的视图中绘制每种犯罪的计数,您需要BY CRIME声明或Proc SGPANEL使用PANELBY crime

犯罪日期时间值不必向下转换为日期值,您可以datetime在过程中使用适当的格式,它们将根据格式化后的值自动汇总。

一些模拟犯罪数据的示例:

data have;
  do precinct = 1 to 10;
    do date = '01jan2018'd to '31dec2018'd;
      do seq = 1 to 20*ranuni(123);
        length crime $10 location $8;
        crime = scan('theft,assault,robbery,dnd', ceil(4*ranuni(123)));
        location = scan ('public,private', ceil(2*ranuni(123)));
        crime_dt = dhms(date,0,0,floor('24:00't*ranuni(123)));
        output;      
      end;
    end;
  end;
  drop date;
  format crime_dt datetime19.;
run;

* shorter graphs for SO answer;
ods graphics / height=300px; 

proc sgplot data=have;
  title "VBAR all crimes combined by location";
  vbar crime_dt 
  / group=location
    groupdisplay=cluster
  ;

  format crime_dt dtmonyy7.;
run;

proc sgpanel data=have;
  title "VBAR crime * location";
  panelby crime;
  vbar crime_dt 
  / group=location
    groupdisplay=cluster
  ;

  format crime_dt dtmonyy7.;
run;

proc summary data=have noprint;
  class crime_dt crime location;
  format crime_dt dtmonyy7.;
  output out=freqs;
run;

proc sgplot data=freqs;
  title "SERIES all crimes,summary _FREQ_ * location";
  where _type_ = 5;
  series x=crime_dt y=_freq_ / group=location;
  xaxis type=discrete;
run;

proc sgpanel data=freqs;
  title "SERIES all crimes,summary _FREQ_ * crime * location";
  where _type_ = 7;
  panelby crime;
  series x=crime_dt y=_freq_ / group=location;
  rowaxis min=0;
  colaxis type=discrete;
run;
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明 在此处输入图片说明