配色: 字号:
ggplot2-cheat sheet
2018-06-21 | 阅:  转:  |  分享 
  
100|Manlat50ft150count6150150100count500050u8al4S60h100ap0val|u50?count?100?o?9?7long50esoOOcount150
Stats-AnalternativewaytobuildalayerScalesCoordinateSystemsFaceting
Facetsdivideaplotintosubplotsbasedonthevalues
Someplotsvisualizeatransformationoftheoriginaldataset.Scalescontrolhowaplotmapsdatavaluestothevisual
r<-b+geom_bar()

ofoneormorediscretevariables.
Useastattochooseacommontransformationtovisualize,
valuesofanaesthetic.Tochangethemapping,adda
r+coord_cartesian(xlim=c(0,5))
t<-ggplot(mpg,aes(cty,hwy))+geom_point()
e.g.a+geom_bar(stat="bin")
customscale.
xlim,ylim
4
flctycyl4n<-b+geom_bar(aes(fill=fl))
x..count..
33t+facet_grid(.~fl)
Thedefaultcartesiancoordinatesystem
n
22
facetintocolumnsbasedonfl
+=
11r+coord_fixed(ratio=1/2)
aestheticprepackagedscalespecific
scale_
00
t+facet_grid(year~.)
arguments
0101toadjustscaletouse
234234
ratio,xlim,ylim
datastatgeomcoordinateplot
facetintorowsbasedonyear
x=x
system
y=..count..n+scale_fill_manual(Cartesiancoordinateswithfixedaspect
t+facet_grid(year~fl)
values=c("skyblue","royalblue","blue","navy"),ratiobetweenxandyunits
Eachstatcreatesadditionalvariablestomapaesthetics
facetintobothrowsandcolumns
limits=c("d","e","p","r"),breaks=c("d","e","p","r"),
to.Thesevariablesuseacommon..name..syntax.
r+coord_flip()
t+facet_wrap(~fl)
name="fuel",labels=c("D","E","P","R"))
xlim,ylim
statfunctionsandgeomfunctionsbothcombineastat
wrapfacetsintoarectangularlayout
rangeofvaluestotitletouseinlabelstouseinbreakstousein
FlippedCartesiancoordinates
withageomtomakealayer,i.e.stat_bin(geom="bar")
includeinmappinglegend/axislegend/axislegend/axis
Setscalestoletaxislimitsvaryacrossfacets
doesthesameasgeom_bar(stat="bin")
r+coord_polar(theta="x",direction=1)
layerspecificvariablecreatedt+facet_grid(y~x,scales="free")
theta,start,direction
GeneralPurposescales
statfunction
mappingsbytransformation
xandyaxislimitsadjusttoindividualfacets
Polarcoordinates
Usewithanyaesthetic:
?"free_x"-xaxislimitsadjust
i+stat_density2d(aes(fill=..level..),r+coord_trans(ytrans="sqrt")
alpha,color,fill,linetype,shape,size
?"free_y"-yaxislimitsadjust
geom="polygon",n=100)xtrans,ytrans,limx,limy
scale__continuous()-mapcont’valuestovisualvalues
Transformedcartesiancoordinates.Set
geomforlayerparametersforstat
scale__discrete()-mapdiscretevaluestovisualvalues
Setlabellertoadjustfacetlabels
extrasandstrainstothename
scale__identity()-usedatavaluesasvisualvalues
a+stat_bin(binwidth=1,origin=10)
ofawindowfunction.
1Ddistributions
t+facet_grid(.~fl,labeller=label_both)
x,y|..count..,..ncount..,..density..,..ndensity..
scale__manual(values=c())-mapdiscretevaluesto
?:c?:d?:e?:p?:r
z+coord_map(projection="ortho",
a+stat_bindot(binwidth=1,binaxis="x")
manuallychosenvisualvalues
orientation=c(41,-74,0))
x,y,|..count..,..ncount..t+facet_grid(.~fl,labeller=label_bquote(alpha^.(x)))
cepr
d
a+stat_density(adjust=1,kernel="gaussian")
XandYlocationscalesprojection,orientation,xlim,ylim
x,y,|..count..,..density..,..scaled..
Usewithxoryaesthetics(xshownhere)
Mapprojectionsfromthemapprojpackage
t+facet_grid(.~fl,labeller=label_parsed)
(mercator(default),azequalarea,lagrange,etc.)
f+stat_bin2d(bins=30,drop=TRUE)
cdepr
scale_x_date(labels=date_format("%m/%d"),
2Ddistributions
x,y,fill|..count..,..density..
breaks=date_breaks("2weeks"))-treatx
f+stat_binhex(bins=30)
valuesasdates.See?strptimeforlabelformats.
PositionAdjustmentsLabels
x,y,fill|..count..,..density..
scale_x_datetime()-treatxvaluesasdatetimes.Use
f+stat_density2d(contour=TRUE,n=100)
t+ggtitle("NewPlotTitle")
Positionadjustmentsdeterminehowtoarrange

sameargumentsasscale_x_date().
x,y,color,size|..level..
geomsthatwouldotherwiseoccupythesamespace.
Addamaintitleabovetheplot
scale_x_log10()-Plotxonlog10scale
m+stat_contour(aes(z=z))

s<-ggplot(mpg,aes(fl,fill=drv))t+xlab("NewXlabel")
3Variables
Usescalefunctions
scale_x_reverse()-Reversedirectionofxaxis
x,y,z,order|..level..
toupdatelegend
ChangethelabelontheXaxis
s+geom_bar(position="dodge")
m+stat_spoke(aes(radius=z,angle=z))scale_x_sqrt()-Plotxonsquarerootscale
labels
t+ylab("NewYlabel")
angle,radius,x,xend,y,yend|..x..,..xend..,..y..,..yend..
Arrangeelementssidebyside
m+stat_summary_hex(aes(z=z),bins=30,fun=mean)Colorand?llscales
ChangethelabelontheYaxis
x,y,z,fill|..value..s+geom_bar(position="fill")
DiscreteContinuous
t+labs(title="Newtitle",x="Newx",y="Newy")
m+stat_summary2d(aes(z=z),bins=30,fun=mean)
Stackelementsontopofoneanother,
Alloftheabove
n<-b+geom_bar(o<-a+geom_dotplot(
x,y,z,fill|..value..
normalizeheight
aes(fill=fl))
aes(fill=..x..))
n+scale_fill_brewer(
g+stat_boxplot(coef=1.5)o+scale_fill_gradient(s+geom_bar(position="stack")
Comparisons
Legends
palette="Blues")low="red",
x,y|..lower..,..middle..,..upper..,..outliers..
Stackelementsontopofoneanother
high="yellow")
t+theme(legend.position="bottom")
Forpalettechoices:

g+stat_ydensity(adjust=1,kernel="gaussian",scale="area")
o+scale_fill_gradient2(
library(RcolorBrewer)
x,y|..density..,..scaled..,..count..,..n..,..violinwidth..,..width..Placelegendat"bottom","top","le",or"right"
low="red",hight="blue",
f+geom_point(position="jitter")
display.brewer.all()
mid="white",midpoint=25)
t+guides(color="none")
AddrandomnoisetoXandYposition
n+scale_fill_grey(
f+stat_ecdf(n=40)
o+scale_fill_gradientn(
Functions
start=0.2,end=0.8,
ofeachelementtoavoidoverplotting
x,y|..x..,..y..colours=terrain.colors(6))Setlegendtypeforeachaesthetic:colorbar,legend,
na.value="red")
Also:rainbow(),heat.colors(),
f+stat_quantile(quantiles=c(0.25,0.5,0.75),formula=y~log(x),ornone(nolegend)
topo.colors(),cm.colors(),
Eachpositionadjustmentcanberecastasafunction
method="rq")
RColorBrewer::brewer.pal()t+scale_fill_discrete(name="Title",
withmanualwidthandheightarguments
x,y|..quantile..,..x..,..y..
labels=c("A","B","C"))
f+stat_smooth(method="auto",formula=y~x,se=TRUE,n=80,
Shapescales
e
s+geom_bar(position=position_dodge(width=1))
Setlegendtitleandlabelswithascalefunction.
Manualshapevalues
fullrange=FALSE,level=0.95)
p<-f+geom_point(
x,y|..se..,..x..,..y..,..ymin..,..ymax..
01218240
0
aes(shape=fl))
+
1131925Themes
+Zooming
ggplot()+stat_function(aes(x=-3:3),
GeneralPurpose
p+scale_shape(
21420-
fun=dnorm,n=101,args=list(sd=0.5))-Withoutclipping(preferred)
solid=FALSE)


r+theme_classic()
r+theme_bw()
.
x|..y..315
21
t+coord_cartesian(
p+scale_shape_manual(
WhitebackgroundWhitebackground
f+stat_identity()
101622%xlim=c(0,100),ylim=c(10,20))
values=c(3:7))
%cdepr
cdepr
withgridlinesnogridlines
ggplot()+stat_qq(aes(sample=1:100),distribution=qt,
Shapevaluesshownin
111723#
#
r+theme_grey()
dparams=list(df=5))r+theme_minimal()
chartonright
Withclipping(removesunseendatapoints)
sample,x,y|..x..,..y..Greybackground
Minimaltheme
t+xlim(0,100)+ylim(10,20)
(defaulttheme)
f+stat_sum()
Sizescalescdeprcdepr
x,y,size|..size..t+scale_x_continuous(limits=c(0,100))+
q+scale_size_area(max=6)
q<-f+geom_point(
ggthemes-Packagewithadditionalggplot2themes
f+stat_summary(fun.data="mean_cl_boot")Valuemappedtoareaofcirclescale_y_continuous(limits=c(0,100))
aes(size=cyl))
(notradius)
f+stat_unique()
RStudio?isatrademarkofRStudio,Inc.?CCBYRStudio?info@rstudio.com?844-448-1212?rstudio.comLearnmoreatdocs.ggplot2.org?ggplot20.9.3.1?Updated:3/15
flfl
fl
fl
献花(0)
+1
(本文系DecenWang首藏)