Table Of ContentGeoms
Data Visualization - Use a geom to represent data points, use the geom’s aesthetic properties to represent variables. Each function returns a layer.
One Variable Two Variables
with ggplot2
Continuous Continuous X, Continuous Y Continuous Bivariate Distribution
Cheat Sheet
f <- ggplot(mpg, aes(cty, hwy)) i <- ggplot(movies, aes(year, rating))
a <- ggplot(mpg, aes(hwy))
f + geom_blank() i + geom_bin2d(binwidth = c(5, 0.5))
a + geom_area(stat = "bin")
xmax, xmin, ymax, ymin, alpha, color, fill,
Data Visualization Geomsx , - y U, sae lap gheaom, c too lroeprr,e fsielln,t l dinateat pyopinet,s ,s uiszee t he geom’s aesthetic properties to represent variables linetype, size, weight
b + geom_area(aes(y = ..density..), stat = "bin")
with ggplot2 One Variable Two Variablesf + geom_jitter() i + geom_density2d()
Data VCBhieasaust Siahcelseitz ation a <- ggpClootGn(mtienpuog,o mauaess (s+xh, w g-yy U,)e )asoel pma hge_aod,m ce toonl roserpi,tr efyisl(elk,n tle iCdnrafon e<tna-te t gypilngpo p=uienloo t",uts (gs,sm iua zXpsuege, , ,C sta hwoseesni e(agcteiitnngyo,uhm "ho)tw’su y sa))e Ysthetic pro pertiesC thoo <n r-et xgipng,r upeylos,oe utan(smlt p Bvoahvivrieaiaas,r,b iacaleeotsse(l yoDerias,r ,tf rriialblt,iun stgiho))nape, size x, y, alpha, colour, linetype, size
with ggplot2 a + geom_Oarneea( Vstaarti =a b"blbein "+) geom_density(aefs +( yg e=o m..c_bolaunnkt()y ..)) Two Variableshf x++m g aegxo, emxmo_ibnm,i nym2_dap(xb, oyinmiwinnid, tath(lp )=h ac,( c5o, l0o.r5, )f)il l, i + geom_hex()
gifdegwepa lc otohtma2t pi syo obnuae scneatdsn: oban ud itCalhdhteB aee ga vasreseta rtiSmy,c h asgme rsaeeapttr ho o fff rg ogemroam pthhsei—c ssva,i msthueea l aa +xbx +,, +g yyg ,,gea eaaeo <olloppm-mmhh g__aa_gad,, aprCcceeroolanooell(ootsaan(rrei(m,,tts sffiy(iitnypll(all k,,u=g tll e,.ii o .nn=rdaanuee ee"ttans syyb+sxl(pp iih=t,nee y w g,,"."y. g)ssy),,iie a )szz )ateeuao ,st lw sp=mi ea"hibngi_han")"td, ) cootlporl,o ftil(l ) ff C+ x+ ,fog gy<en,e -oa toglimpnmghpu__aljoo,bi tcutlto(aesmlnor (Xpkr), (g ,f)i ,l C la, oeshsna(ctpitney,,u shiozweu ys)) Y Chhoh <nlx+ ix+,-n xtm gy geig,,ne tag eayoyuxplopp,m, loemxoh m,au_ ats_(d,sliim bnzcpe e,oiB onn,yhl owvmis2vaiuiedeatari,sy,(xg r b,l,2hci iyaniadtnom eet(wtse)ilyn (oi pydD, eeart,iah,l sps r fi=,thz ir raelcia l,b( t,c5i uon,s lt0gohi.o)r5),a )nf)ipl l, e, size x, y, alpha, colour, fill size
marks that represent data points, and a coordinate a+bxb g ,+ +ey g,go eaemolopmm_h_d_aad,o rceetonapl(solaiorte,yts f(((iay)ll e,= sl .i(.ndye e=tn y.s.pciteoy,.u. )sn,i sztteya. .t) )= "bin") ff + x+ ,g gye,e oaolmpmh__ap,j ioctoitnelotrr((,) )f ill, shape, size hfh x+ +l+,i ngy g ,ee geatoyloepmpmheo_a,_ sh,m dicezoeexln,o_( w)su qiert,i ygfui2hlldt as (iz)ne tile() j <- ggplotC(eoconntionmuiocsu, sa eFsu(dnacttei,o unnemploy))
system. ax +, yg, eaolpmha_, dcoelnosr,i tfiyll( kearn a+l = g "geaousmsian_"f) reqpoly() x, y, alpha, color, fill, shape, size xx, y,, yal,p haal,p cohloau,r, clinoeltyopre,, sliizne etype, size, weight
F M A +234Basics =234 aa +x+xb, ,ggy +y,ee ,ag ooaleplmmophmh__aaf,d_ ,rc doecoeotqlnoplposrl,roio ,tl yliftnyi((lael)(, e)t l ysinp(yee t=,xby s p.,i. zc e+eyo, u s,g inzateeyl, .opw.))emh igah_,t fcreoqlopro, lliyn(eateff y+ sx+px ,g( ,gy yeey,e ,oa ,oa=l mplsmp h.i_h._azqda,pe ,uc eoco aoinlnnolottrs,r(i ,lli) ieft nil(yel),t . sy.h)pa)e p, esi,z sei,z ew eight g <- ggfgh p+ +x+l ,go gy etgC,e( oaeooelmcpmnooh_nt_aaimoh,n rcmeeuoxa_olioc(()u)sur ,rs u,a feFigllsu s((dinzsaecittdei,o eunnse m=p "loby)l)") j +x ,g ye, oalmph_aa, rceoalo()r, fill, linetype, size
F M A 104 104 bx ,+ y g, eaolpmh_af, rceoqlpoor,l fyi(lla esa(y =+ .. dgenesoitym..)) _histogramff (+ a+b lg pgeihenoaom,wm c_o_liroqdurug, tla(ihnsniedt ti=eyleps (e5=), )s"ib zle" ) x, ay,l aCplpohhnaat, ,icn oculooor,lu foisllr, ,Fli nluienntyceptetio,y snpizee , size
data gxye ==o FAm +1230coso1yrsdt2ienma3te4 =1230 1pl2ot3 4 aa +xb +xb, ,+g y +gy ,eg ,eag oeaoleoplmopmmhmh_a__ah,_ fh,c firciroseseotltqqolooopprgg,r o,rofr aillalliymlny,m( ea(l(i)taen( ybesep(sityen(yxb y,p=w s,= e .i i. +z,dyd. .esdte ,i hgz enae ns=e,is l tw5iopyt.)ey.m h).i.)g) )ha_t, hciosltoorg, rfailml, l(fif an+ x+x e,eg ,gy esyt,e ,oa(y oalympplmp h_=he_asa ,r,m ., cu .csodgooil(olozeosrtei,rnd h,f ,ile(lis lnmws,i e lt=iotneyy d"ep.bite.egyl)l,"p )h=s)e i z,lt mes i, z)we ,e wigehitg ht g <- ggfgg +x p++x, ,gl y goy ,e g,eta oa(oleeplmpmchoho_a_anl,m ai,c oncromoeelo_l(aoi)rc( ,rs )s,l if,mni alel,et lyosinp(deeota,y sttpiezhe,e ,u (snimzeem opdloye))l = lm) j +x ,g ye, oalmph_ali, ncoel(o) r, linetype, size
To display data values,0 0m1ap2 v3ar4iab0l0es1 in2 th3 e4 data set a + geom_hiDstisocgrraemte(binwidth = 5) alpha, color, linetype, size g + xg,e oym, a_sltpehp(ad,ir eccotiloon r=, "fhilvl",) linetype, size, weight
taon dae xs tahnedtFF iycddM aMplatoatracAoAaptgxegi e=oxye roF == otnm FA+im+ es.12304s2340 cocosoof1syo rytsdrsth2dietnieemna3m atgete4e =o=m123042340 li1kppel2olo tst3ize4 , color, bb x+ xbx+, ,, ga +ygaGle ,pleg apaoahreo hl<m aoap<ma-,mhp- ,_gc a_gc_bohg,bog hlapciolapiooDcrlsrrol(,rltao o(,i)oft s)i ftlr(gli ,( lmlc ,rPlmf ,ailr lpilmrlenpi,ng ietlg(mei,eatnb ,tya eyeapiespt ete(yxs+eyis,p( v,, (fs = e fsligea) lz,i.) )z.ess)dleei,pz e,bw ewonh,es ewi<migaitgeyh-h.,it.g )_tcg)htbog lapoDrlro(,i s)fti (lclm,r leipntgfeeffg + ,txh++ D <xxh ,yjga ,,u-jggy iueyy p,ssgeee ,,solt gacooalt,eam s,bpllrmm ipbl,neei(l _nheole__sft,tleat eh,lstaei (h,ae)ezm mlxceXpl)xiepotgihoptg,(lhh(, oaahgoCa ta,retw,,t ,,e ,a sosha afssnii(eze(nnli(lglzmeals,geat li,l(beli g,ibcoevn n,ev jl,edhceu jaulcuo ltess=o oyts=ltls oplt c uo,=cre th,r sty ,l,f y mwas)f a))Yim)zy )m e )i),li ylwy, ,fe ofiognnhttftaf accAee, , eB <d-f Cg <g-p dlaoeftggt a( +x d+++xx., f xh,,fg yr ,ggyy a ,,ea jg,,ee am uoyaaeoolepllmse,VsppmmV( h(oghhltig_aias__raa,rsc,pm lsu,,pcbr liu,cctno oia =eoofaneleisl o_plltclioos(l,eizr(( )b,,zrrty"d i,, hlA ianmaiellinnii"rrnnge,eeilxg( nee"ptcf iatt yeB tgt=yyephtir"pp (otrhfer)eieeaarn,o,t no,,t-fs ,ris=sse, itr =ziie azz"es=s ,ee2h nyi4 ()vzm :l"g5ea)a, l ,sxbe e v=, e= jfcu il1to +:s=2slt)e o c))rt,y fa))m ily, fontface, j +x ,g ye, oalmpVh_iass,t uceoapllo(idzr,i ilrniengcett iyeoprner o,= s ri"zhev")
data ycsgxyio z= el==e oA oFAr= =Am F 100coso1yrsdt2ienma3te4 100 1pl2ot3 4 c +xc, gy <,e -Gao glmprgahp_aplp,o hcoto(ilmlycogara,o lpf ni P,l l (a, arleieinsmse((ltgoyitrpnoiegvu,, espliaG zs=te )g)rroaupp))h ical Prigggm g++xl o+ ,D < ggw yg-,ieei e segaootrolgc,p mmmipmrhevl__iao_dtbb,t ebdec(aol maoerXxslr,(opp (,sur slgt,pCot a,fpa itotale(lt ,en=) r =l ,si tn"x (i",cien diyltdaumyeesponasneutx,,t i ,hss tiytiyw zmyY"ey"i,)n) ) w) , eailgphhta , e <d-f g <g-p dleaoet tg+xsxw a(+xi,,d . zi, g fyy dDfeg<yr,,meat ,eya ho-ymamoie mm(xsgmsaea,(a l(_yxgsgcg_x,meor ,rcy pp ryprigmrrn,m oe eo=lf,i oisnoi artncstm,b,l (, pbta ey"aa_hlA(amprlea"p mr(h,ri,X)(h n r"ac faoaB ,op= ,,rtc "l ctbo of)geoi,aCrlt ,nol-f r,olisr hit =,reno a ,(=f ,e)if2 l i)yte4lnl) y,lm :,lp s5iltniae,n( ie,sx ecsnte =tyi lyz=p feapu ie1,te ,s+: ,o2 ss)e u,)) hsw Yy)) k <d-f g <g-p dlaotta(d.ffr,a amese((ggrrpp, =fi tc,( y"Am",i n"B =" f)i,t -fiste =, y4m:5a, sxe = = f i1t+:2s)e ))
csiozleo r= =A F c <- ggplot(map, aes(long, lat)) cxo, lyo,r a, flpillh, ali,n ceotylopre, ,f isllh, alipnee,t yspizee,, swizeei,g whte ight e +s igzee om_linerange() k + geom_crossbar(fatten = 2)
Build a graph with qplot() or ggplot() g <- gcg +px, l goy,et a(oelmpcho_anp, ocomollyoicgrs,o f,ni all(,e alsien(sde(tagytrpeoe,u ,u spni z=ee mgrpoluopy)))) gg +s +t ga gceekoodmmir_ _=db "ooctexpnpltoleotrt("b()) i naxis = "y", gex +x,+ , y gym megionaem,x y, o_ymmemarixrn,o ,a _arlbplbphahaara,( ,)cr c o(ololsort,r ,l ailninetet ty=yppe e," ,s siizidzee ,e ntity") x, y, ymax, ymin, alpha, color, fill, linetype,
g + geom_path(lineend="bcu <tt"-, ggplot(map, aesxl,o (ywl, oaelrpn, mhgaid, ,cd ollelao, rut, pf)ipl)l er, x, ymax, ymin, alpha, e +w xgid,e toyhm, ( aa_lsplopo gihneotarma, _ncegorerl(oo)r bra, rfhi(l)l), linetype, size, weight size
qplot(x =a cetsyt,Fh ye Mt=i ch Amwya,p cpoilnog4rs = cyl, dadtaat =a 4mpg, geogemo m= "poing t<"- g)g g+lxi,pn gyle,eo jaootl(pimenhc=_ao"r,n ricobooubmlonorid,cn l’s,(i n,al ieaentesey(scpmy(med i+,txa isrnt,ei =ze g=yeu,1 nu,e) en aomelmpmplpohyl_oa -y p9,) 0)co0o, llyogr,o fnill(, algigen +x +css, e otg yga(,lte ogceayorkol,rppm dfmohiile_rla_, u v,=,l dic i n"spoooecllitteoi zpyn=nrpe,l( tof eseigltc,rl (s,a" rbhl)lioe inan pe=uate yx",pp iasseri z)e=, e)sa ",i "zyw)e" e,, iwgheitg ht gexs +xh,+ , y agy,p meygemoi,ne msi,ni zoy_, emylmimnaxaeM,x _ra,a alabpnplhpgosahe,a( xc), o cploollro,o rl,i nftiel(lt, )ylip nee,t syipzee , k +x, gymeoamx, _ymerinro, arblpahra(,) c olor, linetype, size,
Creates a complete plot3 with given d3ata, geom, and gy +m gaexo=umn_empaptlohy(l +in 9e0e0n))d ="butt", x, y, alpha, color, fill data e< -+ d gaetao.fmra_mpeo(imnutrradnerg =e (U) SArrests$Murder, width (also geom_errorbarh())
mappings. Supplies m+a12ny useful d=ef12aults. xlx,i ,ny yme, jaaolxpi,n hy=am", riconou, laonlrdp, hl’,i nalie,n cteyopmloeir,t, s rfeiizl=le, 1 li)n etype, size h <g- +xg, ggDy,pe ialosolpmcth(rd_aevi,t acieomo llXooin,rn, ( Ddfsilcsil,,as lalciener es=et( yt"cpeaue rtYe,, saci"oz)el o, wr)e)ight me <sa-tp ag t<ge-pxs =mlch,l oo yatoat,op w(pylldeom_oa,ewd sitrnaaier,z,t,,r e ayf (amrmi(eo"lsslaw(,tixf and,il ltaailed nml="p )lemhe esatu(,,y Ur cudoSpelAporer)rrp),,e fsiseltlh,sr l),i)an )x ep,ty eype,m ,s iazxe,, ywmeiing,h at lpha, k + geom_linerange()
ggBdpeelfgoaitnu(lsdt sdaa,a t pbatalu Fo=dtdt amM aptttahrapoAagvt,gi g yxydeaxy e== oo== eoeFA mFA ums s+ (mf0x12304i0cn0 coo=oiso1ss ryo1cyrehsrdsttd2 tiy2ecbnienm,oma 3ya3ytnt e ae4= t4 dr =hodwl012304i 0nt0yhg)1a1)p pl nla2lo2o ytqte33prls4o4 tto().. N o d ddd <dg < -xyxx++ -x++ yx,emeg e,mgggx n ngggyenageeddapmeendxpoox lood===a ol=mm=o,mm x u tlll yot,ol(a__n ,o(s__y nntsrsyeemnsr eeeeg+gmaiegcanbgi ln+d+g ptsdl+mb, s (eml, ddd, oaa o, dlaa eeetylaeenepae ln llpes<+ntt(lhs_tta(ahsa (t9aaxl(-(_x_eaa(am0,x_ a s,lltc=0eg odol()c=eioo)y s)nnonl) sg ml(nol ol g( oglx+=o gnrpi,i,n n,r , ,gln , fgo = ligl,yli ,unoelny ,,yne g e l= jtaie,t=no oym(yl elalpemaptipmteynt)cl,iph))o ns)e=oyi _az=, -e"sn ,pl9i arz0coeota0,o ,m utlhonir(csid ,le< sial-’,n i,lg ns lga$eipeznehe l<toh he-y<snt x+( w-x+pm(s, d ,gegyi d gtyeg,aDeh ,=eai plao,a(sitlo sl"spl,msotrpe mahbceaetihe_a(zrl_adsusj,=,e eji,(,c i ti ltcausott1ot eotqmeltnoe l)nrro"Xgrtor (,,r(,(e ),, n df )l ifaD dleimllt,lls i),ts ,s)as hpah_caelarpolspeoen(etc,g e,ysu ^si tz2i)Yz,e ) e+c odleoTlrta)h)_rlaete^2 V))a riabdmele a<saets-tpea agg gi+em t<<+emg+ xe vg--a xp ++sxxgp ajg=medppulepa,,oet o_a ats oa_nggatooiyytmtnd(ipam=ddlmd,,,dceeo_. _0 ,_faa _waa_dra_.mkltlooa5mplialarellpmim,dhaatm,pp rmmha ia(aapnsierapi(tihh,eto(t"( tr,sce(me asssM__wc(aaa oe(rtr(ox=efualpsn(x dvai,,ols=(a ltro a=o m(l rpedccmme "i, rmo=lm ,"aefasos oocaa if)pmrla(eit pptllf _eep,lllsl=i_$ ,upilloo($= id liillUUnodnrl inF o=n=drrnl eSS=An e,,tgeostz (AA gLstyt,er)ff ayts,rrpSy), atiirrpyt ) rhee=Elltcee (ee=ll) ,"jss)m ,) , ,buas m ,ttm) s issamslzia li)$zapite)apene=npM$)p$ l0 =a lu ea=a.= t5mr )tmtdx) , a ye" aipprpsa),) + er+= e , "sayi"z")e, , weight k +xxsh,, gyya,mep yoeimn,m ,si nyi_z,m epyamoxia,n axt,lr paahlnpahg, aec,o( c)lo orl,o lri,n feiltly, plinee, styizpee ,
g ggpeloomt_(pmopign,t (aaeess((hcwoyl,o rc t=y )c)y l+) ) + ellaeaymdered n= lat gsye weorimst,h + + dyxl iyx+mnm,e egxanateexydxn,op dx==emm, , ll yasa_i,nit trzy , e+e e+y cn mddtde(ea,al lxatte,aal pys__m(hlxlaaamintd,t ))c,i) )noa y+l l=opm rh l,go alin,ane cgexoo,t ly=yopmmrue, f,in insl_li ,ez= re ml aibt,p blooysin e< +a-( lg as9g$epz0i ls< o0+-x(t )(,wyg s)yeeim, t aozh,lm( sias,nle _apa=cehlossau(,n, l socntqoonerlguot(,mru dl(raea, tplle)tin)asle(_oztl yo=ypn zeg-),^ )s9 2iz 0+e ,d0 we,eTl tiagh_hrltaete^2 V))a riablesi i+ +xx v,,g jgyyue,,e soaaotllm=ppm0hh__.aat5r,,i, alfc eiionsll(t ltaoeeerrr,s p(f(aiolflei,ll asll i(=tnfe iezl=lt) yF)=p A zeL),S, shEizj)eu st=0.5, data <- data.frame(mMuarpdesr = USArrests$Murder,
gcseocooamrl_des__mccRSoaotuorldiotto® heris a(s_ trmigadearemtnaah(drko)i ofd e RS +ntu= tdi"(o, l)Incm . "+• C) C BY+ R Studio • [email protected] oslmptp i s•en t8cga4i4stf-4i +4c8 -121xyxli2mmnm •e aaratsxyxxt,up= x=de mil o,lo a.sicnnitoz g,m+e y + md dealextl,a ty_aml_alinto),n) a xglp,, hyam, coaloxr,, fiyll,m in, alpha, ic +ox ,g lyeo, ozr,m ,a l_fpichlola,n, cltoionluoeru(rta, yleinspe(zet y=p, zes), )is zizee, weight Learhn m <io r+e-xx ,, ag gyyte ,,d ogaaDollmcppps.hhi_glsaagtop,,i lfclcoeitoltl((2 lrao.doeerr,s gift( ia lf•le i ,lgm llg i =npX lezoot)ty2),np 0eD.d9, .s3si.i1z,s e • a cUperdasete(dtc: e3u/1 5tY, color)) ml <sa-t pga gt<ep- l=mo ttao(pdlo_awdtaae,t raa(re(o"ssw(tfianllta e=m" m)e su(rUdSeAr)r)rests)))
theme_bw() additional e <- ggplot(seals, aes(x = long, y = lat)) h + geom_jitter() l + geom_map(aes(map_id = state), map = map) +
RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] n • t84s4-448-1212 • rstudio.com Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15
expand_limits(x = map$long, y = map$lat)
x, y, alpha, color, fill, shape, size
Add a new layer to a plot with a geom_*() e + geom_segment(aes(
map_id, alpha, color, fill, linetype, size
or stat_*() function. Each provides a geom, a xend = long + delta_long,
set of aesthetic mappings, and a default stat yend = lat + delta_lat))
Three Variables
and position adjustment. x, xend, y, yend, alpha, color, linetype, size
seals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2)) m + geom_raster(aes(fill = z), hjust=0.5,
last_plot() e + geom_rect(aes(xmin = long, ymin = lat,
m <- ggplot(seals, aes(long, lat)) vjust=0.5, interpolate=FALSE)
Returns the last plot xmax= long + delta_long,
x, y, alpha, fill
ymax = lat + delta_lat))
ggsave("plot.png", width = 5, height = 5) m + geom_contour(aes(z = z)) m + geom_tile(aes(fill = z))
xmax, xmin, ymax, ymin, alpha, color, fill,
Saves last plot as 5’ x 5’ file named "plot.png" in linetype, size x, y, z, alpha, colour, linetype, size, weight x, y, alpha, color, fill, linetype, size
working directory. Matches file type to file extension.
RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15
Stats Scales
- An alternative way to build a layer Coordinate Systems Faceting
Facets divide a plot into subplots based on the values
Some plots visualize a transformation of the original data set. Scales control how a plot maps data values to the visual r <- b + geo m_bar()
of one or more discrete variables.
Use a stat to choose a common transformation to visualize, values of an aesthetic. To change the mapping, add a
r + coord_cartesian(xlim = c(0, 5))
t <- ggplot(mpg, aes(cty, hwy)) + geom_point()
e.g. a + geom_bar(stat = "bin") custom scale.
xlim, ylim
fl cty cyl n <- b + geom_bar(aes(fill = fl))
x ..count.. 34 34 n The default cartesian coordinate system t + facet_grid(. ~ fl)
+2 =2 r + coord_fixed(ratio = 1/2) facet into columns based on fl
1 1 scale_ aesthetic prepackaged scale specific t + facet_grid(year ~ .)
0 0 to adjust scale to use arguments ratio, xlim, ylim
data stat geom 0coo1rd2ina3te4 0 1pl2ot3 4 facet into rows based on year
x = x system n + scale_fill_manual( Cartesian coordinates with fixed aspect
y = ..count.. t + facet_grid(year ~ fl)
Each stat creates additional variables to map aesthetics values = c("skyblue", "royalblue", "blue", "navy"), ratio between x and y units
facet into both rows and columns
to. These variables use a common ..name.. syntax. limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", "r"), r + coord_flip()
name = "fuel", labels = c("D", "E", "P", "R")) t + facet_wrap(~ fl)
stat functions and geom functions both combine a stat xlim, ylim wrap facets into a rectangular layout
with a geom to make a layer, i.e. stat_bin(geom="bar") range of values to title to use in labels to use in breaks to use in Flipped Cartesian coordinates
does the same as geom_bar(stat="bin") include in mapping legend/axis legend/axis legend/axis r + coord_polar(theta = "x", direction=1 ) Set scales to let axis limits vary across facets
layer specific variable created theta, start, direction t + facet_grid(y ~ x, scales = "free")
General Purpose scales
stat function mappings by transformation
Polar coordinates x and y axis limits adjust to individual facets
Use with any aesthetic:
i + stat_density2d(aes(fill = ..level..), r + coord_trans(ytrans = "sqrt") • "free_x" - x axis limits adjust
alpha, color, fill, linetype, shape, size
geom = "polygon", n = 100) xtrans, ytrans, limx, limy • "free_y" - y axis limits adjust
scale_*_continuous() - map cont’ values to visual values
Transformed cartesian coordinates. Set
geom for layer parameters for stat scale_*_discrete() - map discrete values to visual values Set labeller to adjust facet labels
extras and strains to the name
a + stat_bin(binwidth = 1, origin = 10) 1D distributions scale_*_identity() - use data values as visual values of a window function. t + facet_grid(. ~ fl, labeller = label_both)
x, y | ..count.., ..ncount.., ..density.., ..ndensity.. scale_*_manual(values = c()) - map discrete values to 60
z + coord_map(projection = "ortho", fl: c fl: d fl: e fl: p fl: r
a + stat_bindot(binwidth = 1, binaxis = "x") manually chosen visual values
x, y, | ..count.., ..ncount.. orientation=c(41, -74, 0)) lat t + facet_grid(. ~ fl, labeller = label_bquote(alpha ^ .(x)))
a + stat_density(adjust = 1, kernel = "gaussian") X and Y location scales projection, orientation, xlim, ylim ↵c ↵d ↵e ↵p ↵r
x, y, | ..count.., ..density.., ..scaled.. Use with x or y aesthetics (x shown here) Map projections from the mapproj package long t + facet_grid(. ~ fl, labeller = label_parsed)
(mercator (default), azequalarea, lagrange, etc.)
f + stat_bin2d(bins = 30, drop = TRUE) 2D distributions scale_x_date(labels = date_format("%m/%d"), c d e p r
x, y, fill | ..count.., ..density.. breaks = date_breaks("2 weeks")) - treat x
f + stat_binhex(bins = 30) values as dates. See ?strptime for label formats.
Position Adjustments Labels
x, y, fill | ..count.., ..density..
scale_x_datetime() - treat x values as date times. Use
f + stat_density2d(contour = TRUE, n = 100) same arguments as scale_x_date(). Position adjustments determ ine how to arrange t + ggtitle("New Plot Title ")
x, y, color, size | ..level..
geoms that would otherwise occupy the same space. Add a main title above the plot
scale_x_log10() - Plot x on log10 scale
m + stat_contour(aes(z = z)) 3 Variables scale_x_reverse() - Reverse di rection of x axis s <- ggplot(mpg, aes(fl, fill = drv)) t + xlab("New X label") Use scale functions
x, y, z, order | ..level.. Change the label on the X axis to update legend
m+ stat_spoke(aes(radius= z, angle = z)) scale_x_sqrt() - Plot x on square root scale s + geom_bar(position = "dodge") labels
t + ylab("New Y label")
angle, radius, x, xend, y, yend | ..x.., ..xend.., ..y.., ..yend.. Arrange elements side by side
m + stat_summary_hex(aes(z = z), bins = 30, fun = mean) Color and fill scales Change the label on the Y axis
x, y, z, fill | ..value.. Discrete Continuous s + geom_bar(position = "fill") t + labs(title =" New title", x = "New x", y = "New y")
m + stat_summary2d(aes(z = z), bins = 30, fun = mean) Stack elements on top of one another,
x, y, z, fill | ..value.. n <- b + geom_bar( o <- a + geom_dotplot( normalize height All of the above
aes(fill = fl)) aes(fill = ..x..))
g + stat_boxplot(coef = 1.5) Comparisons n + scale_fill_brewer( o + scale_fill_gradient( s + geom_bar(position = "stack") Legends
g +x s, tya |t _..ylodweenrs..i,t .y.m(aiddjdulset. .=, .1.u, pkeprenre..,l .=.o "ugtaliuesrssi.a. n", scale = "area") pFoarle ptatele =t t"eB cluheosic")e s: lhoigwh = = " "reyedl"l,o w") Stack elements on top of one another t + theme(legend.positio n = "bottom")
library(RcolorBrewer) o + scale_fill_gradient2(
x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width.. display.brewer.all() low = "red", hight = "blue", f + geom_point(position = "jitter") Place legend at "bottom", "top", "left", or "right"
mid = "white", midpoint = 25) Add random noise to X and Y position t + guides(color = "none")
f + stat_ecdf(n = 40) Functions n + scale_fill_grey( o + scale_fill_gradientn(
x, y | ..x.., ..y.. start = 0.2, end = 0.8, colours = terrain.colors(6)) of each element to avoid overplotting Set legend type for each aesthetic: colorbar, legend,
f + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x), na.value = "red") Also: rainbow(), heat.colors(), or none (no legend)
topo.colors(), cm.colors(), Each position adjustment can be recast as a function
method = "rq") RColorBrewer::brewer.pal() with manual width and height arguments t + scale_fill_discrete(name = "Title",
x, y | ..quantile.., ..x.., ..y.. labels = c("A", "B", "C"))
f + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80, Shape scales
Manual Shape values s + geom_bar(position = position_dodge(width = 1)) Set legend title and labels with a scale function.
fullrange = FALSE, level = 0.95) Manual shape values
x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. p <- f + geom_point( 0 6 12 18 24 00
aes(shape = fl))
+ Themes Zooming
ggfpulno t=( )d +n ostrmat,_ nfu =n 1c0t1io, n a(ragess =(x l i=s t-(3s:d3=),0 .5)) General Purpose p +s oscliadl =e _FsAhLaSpEe) ( 12 78 1134 1290 2*5* +- - Without clipp ing (preferred)
fg g+x ps l|to a .t.ty(_)..i +d esntatitt_yq(q) (aes(sample=1:100), distribution = qt, p +vS sahclauapelees_ =vsa chl(ua3ep:7se )s)_h moawnnu ianl ( 34 190 1156 2212 o.Oo %|%#| count115050000 c d fel p r r +Ww tihthhite egm rbidea c_likbngewrso( u) nd count115050000 c d fel p r r +Wn tohh gitereimd bleainc_ekcsgl raosusnicd( ) t + cxolimor d= _cc(0a,r 1te0s0i)a, nyl(i m = c(10, 20))
dparams = list(df=5)) chart on right 5 11 17 23 O # 150 r + theme_grey() 150 r + theme_minimal() With clipping (removes unseen data points)
f +s satmatp_lseu, mx, (y) | ..x.., ..y.. Size scales count150000 G(dreefya bualtc tkhgermouen)d count150000 Minimal theme t + xlim(0, 100) + ylim(10, 20)
x, y, size | ..size.. c d fel p r c d fel p r t + scale_x_continuous(limits = c(0, 100)) +
q <- f + geom_point( q + scale_size_area(max = 6)
f + stat_summary(fun.data = "mean_cl_boot") Value mapped to area of circle ggthemes - Package with additional ggplot2 themes scale_y_continuous(limits = c(0, 100))
aes(size = cyl))
f + stat_unique() (not radius)
RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15