class: center, middle, inverse, title-slide .title[ # Introduction to Plotting ] .author[ ### Rockefeller University, Bioinformatics Resource Centre ] .date[ ###
http://rockefelleruniversity.github.io/Plotting_In_R/
] --- ## Set Up All prerequisites, links to material and slides for this course can be found on github. * [Plotting_In_R](https://rockefelleruniversity.github.io/Plotting_In_R/) Or can be downloaded as a zip archive from here. * [Download zip](https://github.com/rockefelleruniversity/Plotting_In_R/zipball/master) --- ## Course content Once the zip file in unarchived. All presentations as HTML slides and pages, their R code and HTML practical sheets will be available in the directories underneath. * **presentations/slides/** Presentations as an HTML slide show. * **presentations/singlepage/** Presentations as an HTML single page. * **presentations/r_code/** R code in presentations. * **exercises/** Practicals as HTML pages. * **answers/** Practicals with answers as HTML pages and R code solutions. --- ## Set the Working directory Before running any of the code in the practicals or slides we need to set the working directory to the folder we unarchived. You may navigate to the unarchived Plotting_In_R folder in the Rstudio menu. **Session -> Set Working Directory -> Choose Directory** or in the console. ``` r setwd("/PathToMyDownload/Plotting_In_R-master/r_course") # e.g. setwd("~/Downloads/Plotting_In_R-master/r_course") ``` --- ## Introduction R has excellent graphics and plotting capabilities. In fact this is commonly seen as one of the advantages of R over other competing languages like python and matlab. They are mostly found in following three sources. + base graphics + the lattice package + the ggplot2 package Base R graphics uses a pen and paper model for plotting while Lattice and ggplot2 packages are built on the routines first used in grid graphics. --- ## A pen and paper model - Once plot is produced, can only add more elements, cannot remove. - Makes it hard to update. - But faster than more complex plotting systems. Building a new plot is often a stepwise process with gradual addition of features. It will likely require replotting many times. --- ## What do we use? * Base Plot - Quick and easy plots while we are initially reviewing data * ggplot2 - Producing publication quality figures --- class: inverse, center, middle # Scatter and line Charts <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Scatter and line Charts First we'll produce a very simple graph using the values in a numeric vector: ``` r treatment <- c(0.02,1.8, 17.5, 55,75.7, 80) ``` --- ## Scatter Plot Now we plot the treatment vector with default parameters. ``` r plot(treatment) ``` <img src="basePlotting_files/figure-html/defaultPlotEval_basePlotting-1.png" width="1920px" /> --- class: inverse, center, middle # Plot Customization <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Parameters Many features of pots can be customized, by providing addtional arguments to the *plot()* function. ![](basePlotting_files/figure-html/unnamed-chunk-4-1.png)<!-- --> --- ## Type First we can plot treatment using points overlayed by a line. We control this with the **type** argument. ``` r plot(treatment, type="o") ``` <img src="basePlotting_files/figure-html/plotType_basePlotting-1.png" width="1000px" /> --- ## Type To see a complete list we can use **?plot** .pull-left[ ``` r plot(treatment, type="l") ``` <img src="basePlotting_files/figure-html/plotTypeSEval_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, type="p") ``` <img src="basePlotting_files/figure-html/plotTypeS_basePlotting-1.png" width="1000px" /> ] --- ## Point size We can control the size of points in our plot using the **cex** parameter. .pull-left[ ``` r plot(treatment, cex=2) ``` <img src="basePlotting_files/figure-html/plotAsisCexL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, cex=0.5) ``` <img src="basePlotting_files/figure-html/plotAsisCexR_basePlotting-1.png" width="1000px" /> ] --- ## Point shape We can control the type of points in our plot using the **pch** parameter. .pull-left[ ``` r plot(treatment, pch=1) ``` <img src="basePlotting_files/figure-html/plotAsisPchL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, pch=20) ``` <img src="basePlotting_files/figure-html/plotAsisPchR_basePlotting-1.png" width="1000px" /> ] --- ## Line weight Similarly when plotting a line we control size with **lwd** parameter. .pull-left[ ``` r plot(treatment, type="l",lwd=10) ``` <img src="basePlotting_files/figure-html/plotAsisLwdL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, type="l",lwd=0.5) ``` <img src="basePlotting_files/figure-html/plotAsisLwdR_basePlotting-1.png" width="1000px" /> ] --- ## Line type We can also control the type of line with **lty** parameter. .pull-left[ ``` r plot(treatment, type="l",lty=1) ``` <img src="basePlotting_files/figure-html/plotAsisLtyL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, type="l",lty=2) ``` <img src="basePlotting_files/figure-html/plotAsisLtyR_basePlotting-1.png" width="1000px" /> ] --- ## Color An important parameter we can control is color. We can control color or lines or points using the **col** argument. .pull-left[ ``` r plot(treatment, type="l", col="red") ``` <img src="basePlotting_files/figure-html/plotColL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, type="l", col="blue") ``` <img src="basePlotting_files/figure-html/plotColR_basePlotting-1.png" width="1000px" /> ] --- ## Title We add a title with **main** argument and or a sub-title with the **sub** argument. ``` r plot(treatment, main="My Plot", sub="a plot") ``` <img src="basePlotting_files/figure-html/plotLabels_basePlotting-1.png" width="1000px" /> --- ## Axis labels We can customize our x and y axis label with the **xlab** and **ylab** arguments respectively. ``` r plot(treatment, xlab="Position", ylab="score") ``` <img src="basePlotting_files/figure-html/plotAsisLabels_basePlotting-1.png" width="1000px" /> --- ## Axis labels We can control the orientation of labels on axis using **las** argument. .pull-left[ ``` r plot(treatment, las=1) ``` <img src="basePlotting_files/figure-html/plotAsisLasL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r plot(treatment, las=2) ``` <img src="basePlotting_files/figure-html/plotAsisLasR_basePlotting-1.png" width="1000px" /> ] --- ## Other parameters Review **?plot** and **?par** for complete list of options. --- ## Plot multiple vectors The **plot** function vector will accept two vectors to be plotted against each other. ``` r control <- c(0, 20, 40, 60, 80,100) plot(treatment,control) ``` <img src="basePlotting_files/figure-html/plotTwoVectors_basePlotting-1.png" width="1000px" /> --- ## Plot multiple vectors We often want multiple lines in same plot. So if we want to plot scores for control and treatment against position we will need a new method. We can add an additional line to our existing plot using the **lines()** function. ``` r plot(treatment, type="o", col="blue") lines(control, type="o", pch=22, lty=2, col="red") ``` <img src="basePlotting_files/figure-html/lines_basePlotting-1.png" width="1000px" /> --- ## Setting plot limits The new line doesn't quite fit into our original plot. We can extend our x or y axis by specifying values to **xlim** **ylim** arguments directly. ``` r control <- c(0, 20, 40, 60, 80,100) plot(treatment, type="o", col="blue",ylim=c(0,100)) lines(control, type="o", pch=22, lty=2, col="red") ``` <img src="basePlotting_files/figure-html/yxlim_basePlotting-1.png" width="1000px" /> --- ## Defining your limits Instead of defining the axis limits explicitly we can compute the y-axis values using the **range** function. This means any updates to our data will be automatically reflected in our graph. range() returns a vector containing the minimum and maximum of all the given arguments. Calculate range from 0 to max value of data. ``` r g_range <- range(0, treatment, control) g_range ``` ``` ## [1] 0 100 ``` --- ## Custom axes To be able to customize axes we need to turn off axes and annotations (axis labels). We will then be able to specify them ourselves. We turn of axis and annotation plotting using **axes=FALSE** and **ann=FALSE** ``` r plot(treatment, type="o", col="blue", ylim=g_range, axes=FALSE, ann=FALSE) ``` <img src="basePlotting_files/figure-html/plotNoAxesNoAnnotation_basePlotting-1.png" width="1000px" /> --- ## Creating axes We can create our own X axis by using the **axis()** function. We specify the **side** argument for where to place axis, the **at** argument to specify where to put axis ticks and **lab** argument to specify labels for axis ticks. ``` r axis(side=1, at=1:6, lab=c("Mon","Tue","Wed","Thu","Fri","Sat")) ``` <img src="basePlotting_files/figure-html/axisEval_basePlotting-1.png" width="1000px" /> --- ## Creating axes We can make our y axis with horizontal labels that display ticks at every 20 marks in a similar way. We specify our **side** and use **seq()** function to make axis tick postions for **at** argument. We can use our y-axis range again to help define how many ticks we need. ``` r axis(2, las=1, at=seq(0,g_range[2],by=20)) ``` <img src="basePlotting_files/figure-html/axisSidesEval_basePlotting-1.png" width="1000px" /> --- ## Framing plots We can now add a box around our plot using the **box()** function. ``` r box() ``` <img src="basePlotting_files/figure-html/boxEval_basePlotting-1.png" width="1000px" /> --- ## Plot multiple lines Now I can add my control data using lines argument. ``` r lines(control, type="o", pch=22, lty=2, col="red") ``` <img src="basePlotting_files/figure-html/addLinesEval_basePlotting-1.png" width="1000px" /> --- ## Legends Finally we may wish to add a legend to out plot. We can add a legend to current plot using the **legend()** function. We need to specify where to place legend in plot, the names in legend to **legend** argument and any additional point/line type configuration we used e.g the color and shape. ``` r legend("topleft",legend=c("treatment","control"), col=c("blue","red"), pch=21:22, lty=1:2); ``` <img src="basePlotting_files/figure-html/legendEval_basePlotting-1.png" width="1920px" /> --- ## Making plots readable In our line plot we have already done a good job of making it easier to differentiate the lines as we have different line styles and different shape points. Other things we can do is also differentiate thickness. <img src="basePlotting_files/figure-html/readability_basePlotting-1.png" width="1920px" /> --- ## Put it all together To make that final plot you can see that there are many lines of code we put together. ``` r plot(treatment, type="o", col="blue", lwd=1, ylim=g_range,axes=FALSE, ann=FALSE) axis(1, at=1:6, lab=c("Mon","Tue","Wed","Thu","Fri","Sat")) axis(2, las=1, at=20*0:g_range[2]) box() lines(control, type="o", pch=22, lty=2, col="red", lwd=2.5) legend("topleft",legend=c("treatment","control"),col=c("blue","red"), pch=21:22, lty=1:2, lwd=c(1,2.5)) ``` --- class: inverse, center, middle # Colors <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- --- ## Named Colors and hex codes Most colors can simply be defined by writing them in as a chracter vector i.e. "green". There are a wide variety of named colors available in R. From "darkgoldenrod" to "bisque". And 100 different shades of gray. You can find an extensive list of R colors [here](http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf). You can also use hex codes: a hexadecimal format for identifying colors. This gives greater variety of options as they use the full color spectrum. Each pair of characters corresponds to the Red, Green and Blue content for the color i.e. #ffe4c4 (also known as Bisque) is composed of 100% red, 89.4% green and 76.9% blue. Resources like this [color picker](https://htmlcolorcodes.com/color-picker/) can be used to help you find specific shades, and even create complementary palettes. --- ## Palettes Palettes are prebuilt collections of colors. They can consist of a various numbers of colors and can have different properties i.e. continuous/discrete or divergent Here we acn look at the rainbow palette that comes with R. Often the palettes are functions where we can simply ask for how many colors we want and it pull appropraite numbers back. ``` r rainbow(2) ``` ``` ## [1] "#FF0000" "#00FFFF" ``` Rainbow is continuous so we it will pull as many colors as you ask from the color space, along a specifc gradient defined by the palette. ``` r rainbow(6) ``` ``` ## [1] "#FF0000" "#FFFF00" "#00FF00" "#00FFFF" "#0000FF" "#FF00FF" ``` ![](basePlotting_files/figure-html/unnamed-chunk-8-1.png)<!-- --> Many people have created there own palette packages along many themes including famous artworks, Wes Anderson movies and Birds. [Paleteer](https://r-graph-gallery.com/color-palette-finder) is a package in which many different palettes across many themes are collated. In this case we can grab a discrete palettes. This means it will have a limited number of options. ``` r library(paletteer) my_colors <- paletteer_d("wesanderson::Zissou1") my_colors ``` ``` ## <colors> ## #3B9AB2FF #78B7C5FF #EBCC2AFF #E1AF00FF #F21A00FF ``` ``` r plot(1:length(my_colors), col = my_colors, cex = 5, pch =15) ``` ![](basePlotting_files/figure-html/unnamed-chunk-9-1.png)<!-- --> --- ## Palettes R color brewer is another popular option. It has many built-in [palettes](https://r-graph-gallery.com/38-rcolorbrewers-palettes.html). What makes this package special though is the abilty to customize continuous color palettes with the *colorRampPalette()* function. ``` r library(RColorBrewer) my_pal <- colorRampPalette(c("Red","White","Blue"))(25) plot(1:length(my_pal), col = my_pal, cex = 5, pch =15) ``` ![](basePlotting_files/figure-html/unnamed-chunk-10-1.png)<!-- --> --- ## Color blindness and perceptually uniformity Using custom colors is great and can really help a make a piece of work cohesive and stand out. But you have to be careful. ~4% of people are color blind. In white males this number raises to ~10%. Considering the demographics in science, there will likely be someone with color blindness in your meeting. Furthermore when we pick gradients the ability to see patterns in the data varies depending on the color scales used, even in sighted people. ![monalisa_palettes](imgs/monalisa.png) --- ## Viridis The [viridis](https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html) color palette was designed by color scientists to be perceptually uniform, to have a wide dynamic range, to be accessible to the various forms of color blindness and to work even when converted into gray scale. ``` r install.packages('viridis') library(viridis) viridis(5) ``` ``` ## [1] "#440154FF" "#3B528BFF" "#21908CFF" "#5DC863FF" "#FDE725FF" ``` ![viridis_palettes](imgs/viridis.png) --- ## Good data visualization There are often a trade offs in creating good plots. * Is it easy to digest and accessible to everyone? * Is it engaging and appealing? * Does it contain all the information with nothing superfluous? * Is it the best way to tell the story I want to tell, without being misleading? [Fundamentals of Data Visualization](https://serialmentor.com/dataviz/) by Claus O. Wilke is a good resource on the theory of making data visualizations the right way. --- class: inverse, center, middle # Bar Charts <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Bar Charts Base graphics has a useful built in function for bar charts. The **barplot()** function. We can simply pass our numeric vector to this function to get our barchart. ``` r barplot(treatment) ``` <img src="basePlotting_files/figure-html/barplotEval_basePlotting-1.png" width="1920px" /> --- ## Labels The **barplot()** function hasn't added any labels by default. We can speciy our own however using the **names.arg** argument. **names.arg** is a vector of names to be plotted below each bar or group of bars. ``` r barplot(treatment, names.arg=c("Mon","Tue","Wed","Thu","Fri","Sat")) ``` <img src="basePlotting_files/figure-html/barplotNames_basePlotting-1.png" width="1920px" /> --- ## Labels If my vector was named however, then my vectors names would be used for labels. We use **names()** function to add names to our vector then we replot. ``` r names(treatment) <- c("Mon","Tue","Wed","Thu","Fri","Sat") barplot(treatment) ``` <img src="basePlotting_files/figure-html/barplotPreNames_basePlotting-1.png" width="1920px" /> --- ## Stacking Sometimes you want to have several data series stacked in a single barplot. The **barplot()** function handles this readily. Let's read the data from the example_plot.txt data file. Read values from tab-delimited example_plot.txt ``` r data <- read.table("data/example_plot.txt", header=T, row.names=1, sep=",") ``` --- ## Stacking To build a stacked barplot we need to give the barplot funcion a matrix. We can use **as.matrix()** function to convert our data frame to a matrix. ``` r barplot(as.matrix(data)) ``` <img src="basePlotting_files/figure-html/barplotMatrix_basePlotting-1.png" width="1920px" /> --- ## Grouping Now we can plot data from a matrix with grouped barchart using the **beside** argument. ``` r barplot(as.matrix(data),beside=TRUE) ``` <img src="basePlotting_files/figure-html/barplotMatrixBeside_basePlotting-1.png" width="1920px" /> --- ## Customization Though a different function to plot(), barplot can be customized in much the same way. Most of the parameters have the same names. ``` r barplot(as.matrix(data), main="Daily progression of X in\nControl and Treatment", ylab= "Total", beside=TRUE, col= viridis(6)) legend("topleft", c("Mon","Tue","Wed","Thu","Fri","Sat"), cex=0.8, fill= viridis(6)) ``` <img src="basePlotting_files/figure-html/barplotComplexEval_basePlotting-1.png" width="1920px" /> --- class: inverse, center, middle # Histograms <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Histograms Base graphics has a useful built-in function for histograms too. This is the **hist()** function, which just needs a numeric vector. ``` r hist(treatment) ``` <img src="basePlotting_files/figure-html/hist_basePlotting-1.png" width="1920px" /> --- ## Customization Similar customization exists as for other plots. ``` r hist(treatment, col="lightblue", ylim=c(0,5),cex.main=0.8) ``` <img src="basePlotting_files/figure-html/histcolorYlim_basePlotting-1.png" width="1920px" /> --- ## Breaks We can create more fine grained histogram by specify the number of required bins to the **breaks** argument. .pull-left[ ``` r hist(treatment, col="lightblue", ylim=c(0,5), cex.main=0.8, breaks = 2) ``` <img src="basePlotting_files/figure-html/histBreaksEval_basePlottingL_basePlotting-1.png" width="1000px" /> ] .pull-right[ ``` r hist(treatment, col="lightblue", ylim=c(0,5), cex.main=0.8, breaks = 10) ``` <img src="basePlotting_files/figure-html/histBreaksEval_basePlottingR_basePlotting-1.png" width="1000px" /> ] --- class: inverse, center, middle # Dot Charts <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Dot charts Base graphics also has a **dotchart()** function. Dot charts help compare paired data. First though we need to modify the matrix, as we are comparing in pairs as opposed to all control versus treatment. We use the function **t** to return the transpose of a matrix. This means rows are now columns and the columns are now rows. ``` r dotchart(t(data)) ``` <img src="basePlotting_files/figure-html/dotchartEval_basePlotting-1.png" width="1000px" /> --- ## Customization Again we can use the arguments to modify the layout and appearance. Now we create a colored dotchart for autos with smaller labels. ``` r dotchart(t(data), color=c("red","blue"),main="Dotchart", cex=0.5) ``` <img src="basePlotting_files/figure-html/dotchartColEval_basePlotting-1.png" width="1000px" /> --- class: inverse, center, middle # Box Plots <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Box plots The final plot we will look at is a box and whisker plot. Boxplots allow you to quickly review data distributions, showing the median and 1st/3rd quartile. ![](imgs/box_whisker_describe.png) --- ## Read in bigger data First lets read in the gene expression data ``` r exprs <- read.delim("data/gene_data.txt",sep="\t",h=T,row.names = 1) head(exprs) ``` ``` ## Untreated1 Untreated2 Treated1 Treated2 ## ENSDARG00000093639 0.8616832 1.9311442 0.1041508 0.14055604 ## ENSDARG00000094508 0.9857575 2.0256352 0.1549917 0.20301609 ## ENSDARG00000095893 0.8498889 1.9875580 0.2317969 0.20925123 ## ENSDARG00000095252 0.9242996 2.0857620 0.2562264 0.24669079 ## ENSDARG00000078878 0.3571734 0.4653908 0.1167221 0.09710237 ## ENSDARG00000079403 1.0604071 1.2581398 0.3884836 0.31567299 ``` --- ## Boxplots Now we can use the **boxplot()** function on our data.frame to get our boxplot ``` r boxplot(exprs) ``` <img src="basePlotting_files/figure-html/Boxplot_basePlotting-1.png" width="1920px" /> --- ## Rescaling Perhaps it would look better on a log scale. We can add addition colors and labels as with other plots. ``` r boxplot(log2(exprs),ylab="log2 Expression", col=c("red","red","blue","blue")) ``` <img src="basePlotting_files/figure-html/BoxplotEval_basePlotting-1.png" width="1920px" /> --- class: inverse, center, middle # Going Beyond Base Plotting <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Upset, venns, vioplot, density, heatmap --- class: inverse, center, middle # Combining Plots <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Combining Plots R makes it easy to combine multiple plots into one overall graph, using either the **par( )** or **layout( )** function. With the **par( )** function, you can include the option mfrow=c(nrows, ncols) to create a matrix of nrows *x* ncols plots that are filled in by row. mfcol=c(nrows, ncols) fills in the matrix by columns. Define a layout with 2 rows and 2 columns ``` r par(mfrow=c(2,2)) ``` --- ## Combining Plots Plot histograms for different columns in the data frame separately. This is not very efficient. ``` r par(mfrow=c(2,2)) hist(exprs$Untreated1) hist(exprs$Untreated2) hist(exprs$Treated1) hist(exprs$Treated2) ``` <img src="basePlotting_files/figure-html/setParMfrowEval_basePlotting-1.png" width="490px" /> --- ## Combining Plots You could also do it more efficiently using a for loop. ``` r par(mfrow=c(2,2)) for (i in 1:4){ hist(exprs[,i]) } ``` <img src="basePlotting_files/figure-html/setParMfrowEval_for_basePlotting-1.png" width="490px" /> --- ## Other parameter options The **par()** function can control a variety of other graph parameters. * mar - size of plot margins * mgp - spacing between margin elements i.e. axis labels and titles * fig - dimensions of whole plot --- class: inverse, center, middle # Other Customizations <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Text .pull-left[ Custom text can be added to you plot using the *text()* function. Simply provide the position and the label. You can use the data itself to label data points. The adj argument allows you to nudge the annotation a constant amount away from the defined position. Any labels to be added to the margin need to use *mtext()* instead. ] .pull-right[ ``` r plot(control, treatment) text(20,60, 'THIS IS MY PLOT', col='red') text(control, treatment, letters[1:6], adj=c(0,-1), col='blue') ``` <img src="basePlotting_files/figure-html/unnamed-chunk-22-1.png" width="490px" /> ] --- ## Lines .pull-left[ *abline()* allows you to add specific straight lines. This is often useful to help demonstrate known linear relationships or thresholds as reference points for your data. * h = horizontal line with y-intercept * v = vertical line with x-intercept * a,b = intercept and slope ] .pull-right[ ``` r plot(control, treatment) abline(h=10, col='blue') abline(v=50, col='red', lwd=2) abline(a=0, b=1, lty=2) ``` <img src="basePlotting_files/figure-html/unnamed-chunk-23-1.png" width="490px" /> ] --- ## Shapes *polygon()* allows you to draw specific polygons. You just need to give it the coordinates of each vertex. Again this is often to highlight specific parts of the plot. This can be filled, or if you give the denisty argument there will be a hash fill. ``` r plot(control, treatment) polygon(c(50,50,100,100),c(50,80,80,50), col='gray', density=5) ``` <img src="basePlotting_files/figure-html/unnamed-chunk-24-1.png" width="490px" /> --- class: inverse, center, middle # Saving Plots <html><div style='float:left'></div><hr color='#EB811B' size=1px width=720px></html> --- ## Saving your plots There are many different ways of saving your plots in R. The easiest way is to use the *export* button in the plot pane in RStudio. This is not good reproducible practice though as the code is not tied to the plot. To save plots through the console, the argument you would need is name of file in which you want to save the plot. Plotting commands then can be entered as usual. The output would be redirected to the file. When you're done with your plotting commands, enter the dev.off() command. ``` r bmp(filename, width = 480, height = 480, units = "px", pointsize = 12) jpeg(filename, width = 480, height = 480, units = "px", pointsize = 12, quality = 75) ``` --- ## Saving in bitmap format ``` r bmp(file = "control.bmp") plot(control) dev.off() ``` --- ## Saving in jpeg format ``` r jpeg(file = "control.jpg", quality = 20) plot(control) dev.off() ``` --- ## Saving in postscript format ``` r postscript(file = "control.ps") plot(control) dev.off() ``` --- ## Saving in pdf format PDFs are maybe the most useful format to export into. PDFs are vector-based so each part of the plot is saved as scalable cooridnates as opposed to specific pixels. PDFs can then be opened in imaging software like illustrator or [inkscape](https://inkscape.org/) (this is a open source and free equivalent). When you open a PDF in these programs you can fully customize the plots to your aesthetic with a graphic user interface. Furthermore as they are vector-based, they can be easily assembled into publication quality figures without resolution issues and pixelation. ``` r pdf(file = "control.pdf", paper = "A4") plot(control) dev.off() ``` --- Exercises on base plotting can be found [here](../../exercises/exercises/Plotting_exercise.html) --- Answers for base plotting can be found [here](../../exercises/answers/Plotting_answers.html) --- ## Help while plotting * Data vizualisation theory - [Fundamentals of Data Visualization](https://serialmentor.com/dataviz/) * Example plots - [R Graph Gallery](https://www.r-graph-gallery.com/) --- ## Contact Any suggestions, comments, edits or questions (about content or the slides themselves) please reach out to our [GitHub](https://github.com/RockefellerUniversity/Plotting_In_R/issues) and raise an issue.