Can I somehow modify the legend of the line graph (sgplot) to add information that one of the series has been drawn on the right axis?
Example:
data have;
input year x1 x2;
datalines;
2000 10 200
2001 15 190
2002 12 210
2003 12 220
2004 10 210
;
run;
proc sgplot data=have;
series x=year y=x1;
series x=year y=x2/y2axis;
run;
Now, in the legend, I would like to add info that x2 is measured on the RHS, for example "x2 (RHS)". Can I do it without labelling the variable in the original dataset?
Sure. Put whatever text you want. If you want only one item, use the Keylegend statement shown.
proc sgplot data=have;
series x=year y=x1 / name='a' legendlabel='X1 - On Left Hand Y axis';
series x=year y=x2/y2axis name='b' legendlabel='X2 - On Right Hand Y axis';
keylegend 'b';
run;
Or, you can add an INSET.
Sure. Put whatever text you want. If you want only one item, use the Keylegend statement shown.
proc sgplot data=have;
series x=year y=x1 / name='a' legendlabel='X1 - On Left Hand Y axis';
series x=year y=x2/y2axis name='b' legendlabel='X2 - On Right Hand Y axis';
keylegend 'b';
run;
Or, you can add an INSET.
Thanks a lot. Easier than I expected. I somehow missed this option when I was looking at the syntax detail.
One additional question - can I do something similar with grouped graphs?
data have;
input year group_name $1. x1 x2;
datalines;
2000 A 10 200
2001 A 15 190
2002 A 12 210
2003 A 12 220
2004 A 10 210
2000 B 20 200
2001 B 30 300
2002 B 24 310
2003 B 24 320
2004 B 20 330
;
run;
On the graph there would be 4 series - two on the left axis and two on the right. I would like the legend to be something like that:
A - x1
A - x2 (RHS)
B - x1
B - x2(RHS)
Best
When the plot has a GROUP role, the legend contains the unique values of the group variable (like Male and Female for variable Sex). The LEGENDLABEL is ignored. So, to get what you want, you can format the values from the variable to the strings you want to see in the legend. Or, you can add a separate inset indicating which variables are being plotted on each axis.
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.