Data Management and Statistical Analysis - Basic R Graphics

download Data Management and Statistical Analysis - Basic R Graphics

of 18

Transcript of Data Management and Statistical Analysis - Basic R Graphics

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    1/18

    BASIC R GRAPHICSBASIC R GRAPHICS

    Leilani A. NoraLeilani A. NoraLeilani A. NoraLeilani A. NoraLeilani A. NoraLeilani A. NoraLeilani A. NoraLeilani A. NoraAssistant ScientistAssistant Scientist

    Introduction to R:Introduction to R:

    Data Manipulation and StatisticalData Manipulation and Statistical

    AnalysisAnalysis

    OVERVIEWOVERVIEW

    One of the best things about R is the abilityOne of the best things about R is the abilityto create publicationto create publication--quality graphsquality graphs

    To get an idea you can browse throughTo get an idea you can browse through

    Understanding the graphics will facilitateUnderstanding the graphics will facilitateunderstanding R programming in generalunderstanding R programming in general

    How a plotting function deals with data oftenHow a plotting function deals with data oftendepends on the data type (e.g. matrix,depends on the data type (e.g. matrix,factor, vector) given to it.factor, vector) given to it.

    > demo(graphics)> demo(graphics)

    > demo(persp)> demo(persp)

    OVERVIEWOVERVIEW

    Types of basic graphics that will beTypes of basic graphics that will bediscussed are:discussed are:

    -- HistogramHistogram

    -- BoxplotBoxplot-- ScatterplotScatterplot

    -- Line GraphLine Graph

    -- Bar charts / Bar GraphBar charts / Bar Graph

    -- Error BarsError Bars

    PLOTTING COMMANDSPLOTTING COMMANDS

    HighHigh--level plotting functions:level plotting functions:

    create a new plot on the graphics devicecreate a new plot on the graphics device

    LowLow--level plotting functions:level plotting functions:add more information on existing plotadd more information on existing plot(extra points, lines, and labels)(extra points, lines, and labels)

    Interactive graphics functions:Interactive graphics functions:

    allow you interactively add information toallow you interactively add information toan existing plot using a pointing devicean existing plot using a pointing device

    such as mouse.such as mouse.

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    2/18

    HIGHHIGH--LEVEL PLOTTING FUNCTIONSLEVEL PLOTTING FUNCTIONS

    Produces new graph on the graphics deviceProduces new graph on the graphics device

    Selected high level plotting functionsSelected high level plotting functions

    LOWLOW--LEVEL PLOTTING FUNCTIONSLEVEL PLOTTING FUNCTIONS

    Add additional information to an existingAdd additional information to an existinggraphgraph

    Selected lowSelected low--level plotting functionslevel plotting functions

    GRAPHICAL PARAMETERS: par()GRAPHICAL PARAMETERS: par()

    The graphs can be modified with the function par()The graphs can be modified with the function par()

    There are 73 graphical parameters, some of themThere are 73 graphical parameters, some of themhave very similar functions.have very similar functions.

    The exhaustive list of these parameters can be readThe exhaustive list of these parameters can be readwith ?parwith ?par

    Some par elements can be modified from within highSome par elements can be modified from within highand low level plotting functionsand low level plotting functions

    > par(bg=> par(bg=yellowyellow))

    ## bgbg all subsequent plots will have a yellowall subsequent plots will have a yellowbackgroundbackground

    GRAPHICAL WINDOWGRAPHICAL WINDOW

    When a graphical function is executed, RWhen a graphical function is executed, Ropens the graphical window and displays theopens the graphical window and displays thegraphgraph

    To generate a graphic in a new window, useTo generate a graphic in a new window, usethe command:the command:

    -- x11() in Linuxx11() in Linux

    -- windows() in Windowswindows() in Windows

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    3/18

    SUMMARY OF GRAPHICS ANDSUMMARY OF GRAPHICS AND

    DATA FILEDATA FILE

    ggdatadata1.csv1.csvError BarsError Bars

    gdata3.csv and ggdata3.csv and gdatadata2.csv2.csv(matrix)(matrix)

    Bar GraphBar Graph

    gdata2.csvgdata2.csvLinegraphLinegraph

    gdata2.csvgdata2.csvScatterplotScatterplot

    ggdatadata1.csv1.csvBoxplotBoxplot

    ggdatadata1.csv1.csvHistogramHistogram

    DATA FILEDATA FILEGRAPHICSGRAPHICS

    HISTOGRAMHISTOGRAM

    DATAFRAME :DATAFRAME :gdata1gdata1.csv.csv

    Consider theConsider the

    data from Splitdata from Split

    plot design withplot design with

    Nitrogen as MPNitrogen as MPand Variety asand Variety as

    SP, replicated 4SP, replicated 4times.times.

    DATA FRAME:DATA FRAME: gdata1gdata1

    Read data fileRead data file gdata1gdata1.csv.csv

    >>gdata1gdata1

    gdata1gdata1

    Nitrogen Variety Rep Yield

    1 0 C4-63 1 3464

    2 60 C4-63 1 4768

    3 90 C4-63 1 6224

    4 120 C4-63 1 5792

    . . .

    47 90 Peta 3 414648 120 Peta 3 3638

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    4/18

    HISTOGRAM :HISTOGRAM : hist()hist()

    Histogram is an important tool forHistogram is an important tool for

    exploratory data analysis that provides aexploratory data analysis that provides a

    graphical summary of the shape or datagraphical summary of the shape or datassdistribution.distribution.

    The generic function hist() computes aThe generic function hist() computes a

    histogram of the given data values.histogram of the given data values.

    Details ofDetails ofhist()hist() function.function.> hist(x,> hist(x, ))

    ## xx a vector of valuesa vector of values

    DATAFRAME gdata : hist()DATAFRAME gdata : hist()

    Ex1. To obtain histogram for YEx1. To obtain histogram for Y

    > hist(gdata> hist(gdata11$Yield)$Yield)

    Displays theDisplays thehistogram of Yieldhistogram of Yield

    at Graphicsat Graphicswindowwindow

    Ex2. Modifying HistogramEx2. Modifying Histogram

    > hist(gdata1$Yield, main='Histogram> hist(gdata1$Yield, main='Histogram

    of Yield', col=of Yield', col=yellow2',yellow2',

    border=border= blue', xlab= blue', xlab=Y ClassY Class,,

    ylab="Frequency",ylab="Frequency",xlim=c(0,10000),ylim=c(0, 11))xlim=c(0,10000),ylim=c(0, 11))

    # main# main -- main title of the histogrammain title of the histogram

    # col# col -- color of filled barscolor of filled bars

    # border# border -- foreground colour of barsforeground colour of bars

    # ylab# ylab y axis labely axis label# xlim / ylim# xlim / ylim x and y axis limitx and y axis limit

    GRAPHICAL parGRAPHICAL par EXAMPLE : hist()EXAMPLE : hist()

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    5/18

    BOXPLOTBOXPLOT

    boxplot()boxplot()

    Produce a boxProduce a box--andand--whisker plot(s) of the givenwhisker plot(s) of the given(grouped) values.(grouped) values.

    Details ofDetails ofboxplot()boxplot() function.function.

    > boxplot(formula, data=NULL,> boxplot(formula, data=NULL, ,,

    na.action=NULL)na.action=NULL)

    formulaformula a formula, such as y~grpa formula, such as y~grp

    wherewhere :: yy -- is a numeric vector of datais a numeric vector of datavalues to be split into groupsvalues to be split into groups

    according to the grouping variable,according to the grouping variable,

    grp (factor)grp (factor)

    Ex1. To obtain boxplot of YEx1. To obtain boxplot of Y

    > boxplot(gdata> boxplot(gdata11$Yield)$Yield)

    DATAFRAME gdataDATAFRAME gdata11 : boxplot(): boxplot() Ex2. To obtain boxplot of Y by SiteEx2. To obtain boxplot of Y by Site

    > boxplot(gdata1$Yield~> boxplot(gdata1$Yield~

    gdata$Variety)gdata$Variety)

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    6/18

    SCATTERPLOTSCATTERPLOT

    plot()plot()

    plot(x,y) or plot(y~x)plot(x,y) or plot(y~x)

    -- x and y are the variables to be used forx and y are the variables to be used for

    the x and y axes, respectivelythe x and y axes, respectively

    -- x and y are both numeric variablesx and y are both numeric variables

    DATAFRAME :DATAFRAME :gdata2gdata2.csv.csv

    Nitrogen x Variety Summary of MeansNitrogen x Variety Summary of Means

    DATA FRAME:DATA FRAME: gdata2gdata2

    Read data fileRead data file gdata2gdata2.csv.csv

    >>gdata2gdata2gdata2gdata2

    Nitrogen C463 IR5 IR8 Peta

    1 0 3183 4306 4253 4481

    2 60 5443 5982 5672 4816

    3 90 5987 6259 6400 4812

    4 120 6014 6895 6733 3816

    5 150 6687 6951 7563 2047

    6 180 6065 6540 8701 1881

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    7/18

    > attach(gdata2)> attach(gdata2)> plot(> plot(NitrogenNitrogen,, C463C463,,main=main=PlotPlot

    of Yield at Different Nitrogenof Yield at Different Nitrogen

    RateRate,, xlab=xlab=Nitrogen RateNitrogen Rate",",

    ylab=ylab=Grain Yield,Grain Yield, col="Red")col="Red")

    # x# x NitrogenNitrogen## yy C463C463

    Ex1Ex1. Scatter plot of GY and. Scatter plot of GY and Nitrogen RateNitrogen Rate

    SCATTERPLOT: plot()SCATTERPLOT: plot()SCATTER PLOTSCATTER PLOT

    PLOTTING CHARACTERPLOTTING CHARACTERSS::

    plot(plot(pchpch==))

    # - same content as Ex1

    # pch# pch plotting character that controlsplotting character that controls

    the type of symbol.the type of symbol.

    Can either be an integer from 1Can either be an integer from 1--2525and character (and character (**,, ??,, ..,, ))

    > plot(> plot(, pch=19), pch=19)

    Ex2. With graphical parameter pchEx2. With graphical parameter pch

    PLOTTING CHARACTERSPLOTTING CHARACTERS

    ColoColouurs cars cann be obtained with optionsbe obtained with optionscol=col=blueblue, bg=, bg=yellowyellow (only for the(only for thesymbols 21symbols 21--25)25)

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    8/18

    STYLE OF AXES LABELS:STYLE OF AXES LABELS:

    plot(plot(laslas==))

    # - same content as Ex1

    # las - style of axis labels

    0: always parallel to the axis [default],

    1: always horizontal2: always perpendicular to the axis,

    3: always vertical.

    > plot(> plot(,,pch=19,pch=19, las=3las=3))

    Ex3. With graphical parameter lasEx3. With graphical parameter las

    CUSTOMIZING A PLOTCUSTOMIZING A PLOT

    CUSTOMIZING A PLOTCUSTOMIZING A PLOT

    > par(cex=> par(cex=0.90.9, bg=, bg=lightyellowlightyellow,,

    col.axis=col.axis=blueblue,,

    mar=c(4,4,2.5,0.5))mar=c(4,4,2.5,0.5))

    > plot(> plot())

    # par# par modify graphical parameters such as bg,modify graphical parameters such as bg,

    col.axis and marcol.axis and mar

    # cex# cex controls the size of the textcontrols the size of the text

    # bg# bg background colorbackground color

    # col.axis# col.axiscolor of the numbers on the axescolor of the numbers on the axes

    # mar# mar-- use to set the margin size specified inuse to set the margin size specified in

    inches of the form c(bot, left, top, right).inches of the form c(bot, left, top, right).-- The default is mar=c(5, 4, 4, 2)The default is mar=c(5, 4, 4, 2)

    CUSTOMIZING A PLOTCUSTOMIZING A PLOT

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    9/18

    LINE CHARTLINE CHART

    LINE CHART : plot(type=)LINE CHART : plot(type=)

    # type =# type = pp # point# point

    == ll # line# line

    == oo # overplotted point and line# overplotted point and line== bb # points joined by line# points joined by line

    == ss # stair steps# stair steps

    == hh # histogram like vertical line# histogram like vertical line

    == nn # does not produce points or line# does not produce points or line

    > plot(Nitrogen, C463, main=> plot(Nitrogen, C463, main=Plot ofPlot of

    Yield at Different Nitrogen RateYield at Different Nitrogen Rate,,

    xlab=xlab=Nitrogen Rate", ylab=Nitrogen Rate", ylab=GrainGrain

    Yield, col="RedYield, col="Red,,pch=19, las=3,pch=19, las=3,

    xlim=c(0,180), ylim=c(1000,8000),xlim=c(0,180), ylim=c(1000,8000),

    type=type=oo, lty=1, lty=1))

    ExEx11.. Connecting points using plot()Connecting points using plot()

    LINE CHART : plot(lty=)LINE CHART : plot(lty=)

    ExEx11.. Connecting points using plot()Connecting points using plot()

    # lty - style of axis labels option to change

    line type. The default value is 1.

    LINE CHART : plot()LINE CHART : plot()

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    10/18

    lineslines()()

    Use to create line charts that addsUse to create line charts that adds

    information to a graphinformation to a graph

    > lines(x,y, type=> lines(x,y, type= ))

    > lines(y~x, type=> lines(y~x, type= ))

    ## x and yx and y numeric vectors of points to connectnumeric vectors of points to connect

    ADDING LINE CHARTADDING LINE CHART

    ExEx22.. Adding line charts to plot()Adding line charts to plot()

    > lines(IR5~Nitrogen, pch=19,> lines(IR5~Nitrogen, pch=19,

    col="blue", type="o", lty=1)col="blue", type="o", lty=1)

    > lines(IR8~Nitrogen, pch=19,> lines(IR8~Nitrogen, pch=19,

    col=col=green", type="o", lty=1)green", type="o", lty=1)

    > lines(Peta~Nitrogen, pch=19,> lines(Peta~Nitrogen, pch=19,

    col=col=brownbrown", type="o", lty=1)", type="o", lty=1)

    ADDING LINE CHARTADDING LINE CHART ADDING A LEGEND : legend()ADDING A LEGEND : legend()

    Adds legends to plots.Adds legends to plots.

    > legends(x, legend, pch, col,> legends(x, legend, pch, col,

    lty,lty, ))

    ## xx use to position the legend that can be ause to position the legend that can be a

    single keyword from the list,single keyword from the list, bottomrightbottomright,,

    bottombottom,, bottomleftbottomleft,, leftleft,, toplefttopleft,, toptop,,

    toprighttopright,, rightright andand centercenter

    ## legendlegend a charactera character

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    11/18

    ExEx33.. Adding a legendAdding a legend

    >>legendlegend("topleft", legend=c("C4("topleft", legend=c("C4--

    63", "IR5", "IR8", "Peta"),63", "IR5", "IR8", "Peta"),pch=1:4, bty="n")pch=1:4, bty="n")

    > detach(gdata2)> detach(gdata2)

    ADDING A LEGEND : legend()ADDING A LEGEND : legend()

    ## pchpch plotting symbols appearing in the legendplotting symbols appearing in the legend

    ## colcol color of points or lines appearing in thecolor of points or lines appearing in the

    legendlegend

    ## ltylty line types and widthsline types and widths appearing in theappearing in the

    legendlegend

    ADDING A LEGENDADDING A LEGEND

    ExEx44.. Suppressing plot of axesSuppressing plot of axes

    SUPPRESSING PLOT OF AXESSUPPRESSING PLOT OF AXES

    # xaxt and yaxt# xaxt and yaxt a character which specifies thea character which specifies the

    xx--axis and yaxis and y--axis type. Specifyingaxis type. Specifying nn

    suppresses plotting of the axis.suppresses plotting of the axis.

    > plot(Nitrogen, C463, main=> plot(Nitrogen, C463, main=Plot ofPlot of

    Yield at Different Nitrogen RateYield at Different Nitrogen Rate,,

    xlab=xlab=Nitrogen Rate", ylab=Nitrogen Rate", ylab=GrainGrainYield, col="RedYield, col="Red,,pch=19, las=3,pch=19, las=3,

    type=type=oo, lty=1,, lty=1, xaxt=xaxt=nn, yaxt=, yaxt=nn))

    ADD AN AXIS : axis()ADD AN AXIS : axis()

    Adds an axes to the current plotAdds an axes to the current plot

    >>axisaxis((sideside,, at,at, ))

    ## sideside an integer specifying which side of thean integer specifying which side of the

    axis is to be drawn on.axis is to be drawn on.

    side = 1 : belowside = 1 : below side = 3 : aboveside = 3 : above

    side = 2 : leftside = 2 : left side = 4 : rightside = 4 : right

    # at# at points at which tickpoints at which tick--marks are to be drawnmarks are to be drawn

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    12/18

    ADD AN AXIS : axis()ADD AN AXIS : axis()

    Ex5. Adds an axes to the current plotEx5. Adds an axes to the current plot

    > plot(> plot()) # same as Ex4# same as Ex4

    > axis> axis((side=1side=1,, at=seq(0,180,30))at=seq(0,180,30))

    >>axisaxis((side=2side=2,, at=seq(3000,7000,500))at=seq(3000,7000,500)) BAR GRAPH / BAR PLOTBAR GRAPH / BAR PLOT

    barplot()barplot()

    barplot(height, # vector or matrix of values describing# the bars which make up the plot.

    beside = FALSE, # stacked by default. If# TRUE bars will be side

    # by side

    density = NULL, # a vector giving the density of# shading lines, in lines per inch,

    # for the bars or bar components.

    # The default value of NULL

    # means that no shading lines are

    # drawn.

    xlab = NULL, # label for x-axis

    ylab = NULL, # label for y-axis

    ylim = NULL) # limit for y-axis

    DATAFRAME :DATAFRAME : gdata3gdata3.csv.csv

    Summary of Variety MeansSummary of Variety Means

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    13/18

    DATA FRAME:DATA FRAME: gdata3gdata3

    Read data fileRead data file gdata3gdata3.csv.csv

    >>gdata3gdata3gdata3gdata3

    Variety Yield

    1 V1 4.7559

    2 V2 5.0410

    3 V3 5.0581

    SIMPLE BAR PLOT : gdata3SIMPLE BAR PLOT : gdata3

    >>barplot(gdata3$Yield)barplot(gdata3$Yield)

    WITH LABELS AND COLORSWITH LABELS AND COLORS

    > barplot(> barplot(gdata3$gdata3$Yield, xlab="Variety",Yield, xlab="Variety",

    ylab="Grain Yield",ylab="Grain Yield",

    nnames.arg=c(ames.arg=c(V1V1",",V2V2",",V3V3),),

    col=c(col=c(pink",pink", llightblue",ightblue",

    yellowgreenyellowgreen))))

    # names.arg# names.arg a vectora vector

    of names to be plottedof names to be plotted

    below each bar or groupbelow each bar or group

    of barsof bars

    DATA FRAMEDATA FRAME FOR GROUPEDFOR GROUPED

    BAR PLOT : gdata2.csvBAR PLOT : gdata2.csv

    Read data fileRead data file gdata2gdata2.csv.csv

    > gdata4 gdata4 gdata4 < t(as.matrix(gdata4))> gdata4 < t(as.matrix(gdata4))

    0 60 90 120 150 180

    C463 3183 5443 5987 6014 6687 6065

    IR5 4306 5982 6259 6895 6951 6540

    IR8 4253 5672 6400 6733 7563 8701

    Peta 4481 4816 4812 3816 2047 1881

    GROUPED BAR PLOTGROUPED BAR PLOT d t 4d t 4

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    14/18

    GROUPED BAR PLOTGROUPED BAR PLOT gdata4gdata4

    > barplot(> barplot(gdata4gdata4, beside=T,, beside=T,

    xlab="Variety", ylab="Grain Yield",xlab="Variety", ylab="Grain Yield",

    ccol=c("pink", "lightblue",ol=c("pink", "lightblue",

    "yellowgreen"yellowgreen,, redred))))

    ADD LEGENDADD LEGEND

    > legend("topleft", Vlevel, bty="n",> legend("topleft", Vlevel, bty="n",

    fill=c("pink", "lightblue",fill=c("pink", "lightblue",

    "yellowgreen", "red"))"yellowgreen", "red"))

    ERROR BARSERROR BARS

    PACKAGEPACKAGE sciplotsciplot

    A collection of functions that createsA collection of functions that creates

    graphs with error bars for data collectedgraphs with error bars for data collected

    from onefrom one--way or higher factorial designs.way or higher factorial designs.

    It has three available functions:It has three available functions:

    > bargraph.CI()> bargraph.CI()

    > lineplot.CI()> lineplot.CI()

    >>sse()e()

    BARGRAPH WITH ERROR BARS

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    15/18

    BARGRAPH WITH ERROR BARS:BARGRAPH WITH ERROR BARS:

    bargraph.CI()bargraph.CI()

    Use to obtain barplot of the mean and standardUse to obtain barplot of the mean and standard

    error of a response variable.error of a response variable.

    Usage:Usage:

    > bargraph.CI(x.factor, response,> bargraph.CI(x.factor, response,

    group,group, ))

    # x.factor# x.factor a factor whose levels will form thea factor whose levels will form the

    xx--axisaxis

    # response# response numeric response variablenumeric response variable

    # group# group grouping factor whose levels willgrouping factor whose levels will

    form groups of bars for each level of x.factorform groups of bars for each level of x.factor

    BARGRAPH WITH ERROR BARS:BARGRAPH WITH ERROR BARS:

    bargraph.CI()bargraph.CI()

    Usage:Usage:

    > bargraph.CI(x.factor, response,> bargraph.CI(x.factor, response,group, density, angle, legend,group, density, angle, legend,

    x.leg, cex.legx.leg, cex.leg ))

    # x.leg, y.leg# x.leg, y.leg to over ride the default legendto over ride the default legend

    placementplacement

    # cex.leg# cex.leg character expansion value forcharacter expansion value forlegend valueslegend values

    BARGRAPH WITH ERROR BARS:BARGRAPH WITH ERROR BARS:gdata1gdata1

    > bargraph.CI(Nitrogen, Yield,> bargraph.CI(Nitrogen, Yield,

    group=Variety, data=group=Variety, data=gdata1gdata1,,

    density=45, col=c("pink",density=45, col=c("pink",

    "lightblue", "yellowgreen"lightblue", "yellowgreen,,redred), legend=T, x.leg=1,), legend=T, x.leg=1,

    cex.leg=0.8)cex.leg=0.8)

    BARGRAPH WITH ERROR BARSBARGRAPH WITH ERROR BARS

    LINEGRAPH WITH ERROR BARSLINEGRAPH WITH ERROR BARS

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    16/18

    LINE PLOT WITH ERROR BARS:LINE PLOT WITH ERROR BARS:

    lineplot.CI()lineplot.CI()

    Use to obtain lineplot of the mean and standardUse to obtain lineplot of the mean and standard

    error of a response variable.error of a response variable.

    Usage:Usage:

    > lineplot.CI(x.factor, response,> lineplot.CI(x.factor, response,

    group,group, typetype))

    # group# group grouping factor whose levels willgrouping factor whose levels will

    formform the tracesthe traces

    ## typetype the type of plot: lines, points, or boththe type of plot: lines, points, or both

    LINEGRAPH WITH ERROR BARSLINEGRAPH WITH ERROR BARS

    > lineplot.CI(Nitrogen, Yield,> lineplot.CI(Nitrogen, Yield,

    group=Variety, data=group=Variety, data=gdata1gdata1,,

    density=45, col=c(density=45, col=c(red",red", blue",blue",

    "green"), legend=T, x.leg=1,"green"), legend=T, x.leg=1,

    cex.leg=0.8, xlab=cex.leg=0.8, xlab=NitrogenNitrogen

    RateRate, pch=c(15:18)), pch=c(15:18))

    LINEGRAPH WITH ERROR BARSLINEGRAPH WITH ERROR BARS

    GRAPHICAL DEVICESGRAPHICAL DEVICES

    GRAPHICAL DEVICEGRAPHICAL DEVICE

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    17/18

    GRAPHICAL DEVICEGRAPHICAL DEVICE

    Before you create your graphs, you can decideBefore you create your graphs, you can decideon a format for output. The format is called aon a format for output. The format is called adevice.device.

    A graphical device is a graphical window or aA graphical device is a graphical window or afilefile..

    Some commonly usedSome commonly used graphicalgraphical devicedevice

    Produces a bitmap JPEG fileProduces a bitmap JPEG filejpeg()jpeg()

    Produces a bitmap PNG fileProduces a bitmap PNG filepngpng()()

    Produces PDF fileProduces PDF filepdfpdf()()

    jpeg(filename=jpeg(filename=plot.jpgplot.jpg, width=480,, width=480,

    height=480, pointsize=12,height=480, pointsize=12,

    units=units=pxpx))

    png()png() same parameters as jpegsame parameters as jpeg

    pdf(file=pdf(file=plot.pdfplot.pdf, width=7,, width=7,

    height=7, paper =height=7, paper = a4a4))

    USAGE OF GRAPHICS DEVICEUSAGE OF GRAPHICS DEVICE

    ##

    filenamefilename

    --

    the name of the output filethe name of the output file

    ## width and heightwidth and height width and height of the devicewidth and height of the device

    USAGE OF GRAPHICS DEVICEUSAGE OF GRAPHICS DEVICE

    When you have finished with a device, be sureWhen you have finished with a device, be sure

    to terminate the device driver by using dev.off()to terminate the device driver by using dev.off()

    graphics.off() closes all open graphics devices.graphics.off() closes all open graphics devices.

    ## pointsizepointsize defaultdefault pointsize of plotted text,pointsize of plotted text,

    interpreted as big points(1/72 inch)interpreted as big points(1/72 inch) atat res dpires dpi

    ## unitsunits The units in which height and width areThe units in which height and width are

    given. Can be px(pixels), in, cm or mm.given. Can be px(pixels), in, cm or mm.

    jpeg(jpeg(,,pointsize=12pointsize=12,, units=units=pxpx))

    Plots in JPEG and PNG format can easilyPlots in JPEG and PNG format can easily

    converted to many other bitmap formats.converted to many other bitmap formats.

    PNG format is lossless and is best for linePNG format is lossless and is best for line

    diagrams. While JPEG format is lossydiagrams. While JPEG format is lossy

    InIn pdfpdf() m() multiple graphics can be saved in oneultiple graphics can be saved in onefile.file.

    COMPARISONS OF GRAPHICSCOMPARISONS OF GRAPHICSDEVICEDEVICE

  • 8/8/2019 Data Management and Statistical Analysis - Basic R Graphics

    18/18

    SAVING GRAPHS IN FILESSAVING GRAPHS IN FILES

    Ex. Saving histogram in png deviceEx. Saving histogram in png device

    > png(filename=> png(filename=hist.pnghist.png))

    > hist(gdata$Y)> hist(gdata$Y)> dev.off()> dev.off()

    THANK YOU!THANK YOU!

    Please do Exercise CPlease do Exercise C