```{r setup, include=FALSE} opts_chunk$set(cache=TRUE) ``` Introduction to R Graphics ======================================================== author: Le Yan date: HPC@LSU autosize: false font-family: 'Calibri' width: 1440 height: 900 Disclaimer === - Slides were developed with R Presentation (a feature of Rstudio using knitr and Rmarkdown) - Built from a source file that mixes texts and R code chunks - https://support.rstudio.com/hc/en-us/articles/200486468-Authoring-R-Presentations - No hands-on exercises - All code segments are executed in Rstudio, however, so you can play along if you'd like to R Graphic Systems === * There are at least three plotting systems in R + base + lattice + ggplot2 * Today we will touch on "base" briefly then focus on "ggplot2" Outline === - Base plot system - ggplot2 plot system - Basic concepts - Geom and stat functions - Title, axis labels and legends - Themes - Scale functions - Coordination systems - Faceting DataSets === class: small-code left: 35% ```{r, echo=F} library(datasets) library(gcookbook) library(ggplot2) ``` - Datasets are from the packages ```datasets```, ```gcookbook` and ```ggplot2``` - To learn more about those datasets, run ```help(library='')``` - For information on individual datasets, run ```?``` *** ```{r eval=F} library(help='datasets') ``` ``` Information on package 'datasets' Description: Package: datasets Version: 3.3.3 Priority: base Title: The R Datasets Package Author: R Core Team and contributors worldwide Maintainer: R Core Team Description: Base R datasets. License: Part of R 3.3.3 Built: R 3.3.3; ; 2017-03-06 14:15:22 UTC; windows Index: AirPassengers Monthly Airline Passenger Numbers 1949-1960 BJsales Sales Data with Leading Indicator BOD Biochemical Oxygen Demand CO2 Carbon Dioxide Uptake in Grass Plants ChickWeight Weight versus age of chicks on different diets DNase Elisa assay of DNase EuStockMarkets Daily Closing Prices of Major European Stock ... ``` First Plot in R ======================================================== class: small-code - We will use the "pressure" dataset for our first plot. First, let's examine the data: ```{r} str(pressure) summary(pressure) ``` *** ```{r eval=F} ?pressure ``` ``` pressure {datasets} R Documentation Vapor Pressure of Mercury as a Function of Temperature Description Data on the relation between temperature in degrees Celsius and vapor pressure of mercury in millimeters (of mercury). Usage pressure Format A data frame with 19 observations on 2 variables. [, 1] temperature numeric temperature (deg C) [, 2] pressure numeric pressure (mm) Source Weast, R. C., ed. (1973) Handbook of Chemistry and Physics. CRC Press. References McNeil, D. R. (1977) Interactive Data Analysis. New York: Wiley. ``` First Plot in R === class: small-code We can use the ```plot()``` function in the base plot system to create a scatter plot: ```{r} # Simply specify the x and y variables. plot(pressure$temperature,pressure$pressure) ``` *** Since there are only two variables, we can simply run: ```{r} plot(pressure) ``` More Plot Types === class: small-code - The ```type``` argument of ```plot()``` can be used to specify plot type Line plot with "l": ```{r} plot(pressure,type="l") ``` *** Or dot and line with "b": ```{r} plot(pressure,type="b") ``` Adding More Layers === class: small-code left: 35% There are a few functions that can be used to add more elements/layers to the plot - Points - Lines - Texts *** ```{r} # Create the plot with title and axis labels. plot(pressure,type="l", main="Vapor Pressure of Mercury", xlab="Temperature", ylab="Vapor Pressure") # Add points points(pressure,size=4,col='red') # Add annotation text(150,700,"Source: Weast, R. C., ed. (1973) Handbook \n of Chemistry and Physics. CRC Press.") ``` Boxplot === class: small-code - Use ```boxplot()``` for boxplots dataset: ```{r} str(mpg) ``` ```{r} summary(mpg) ``` *** ```{r eval=F} ?mpg ``` ``` Fuel economy data from 1999 and 2008 for 38 popular models of car Description This dataset contains a subset of the fuel economy data that the EPA makes available on http://fueleconomy.gov. It contains only models which had a new release every year between 1999 and 2008 - this was used as a proxy for the popularity of the car. Usage mpg Format A data frame with 234 rows and 11 variables manufacturer model model name displ engine displacement, in litres year year of manufacture cyl number of cylinders trans type of transmission drv f = front-wheel drive, r = rear wheel drive, 4 = 4wd cty city miles per gallon hwy highway miles per gallon fl fuel type class "type" of car ``` Boxplot === class: small-code ```{r} boxplot(hwy ~ cyl, data=mpg) # Use the title function to add title and labels. title("Highway Mileage per Gallon", xlab = "Number of cylinders", ylab = "Mileage (per gallon)") ``` Histogram === class: small-code - Function ```hist()``` can used to create histograms ```{r} hist(mpg$hwy) ``` *** ```{r} hist(mpg$hwy, breaks=c(5,15,25,30,50)) ``` Curve === class: small-code The ```curve()``` function draws a function over a specified range. ```{r} curve(cos,-3*pi, 3*pi) title("Cosine Function") # The abline() function adds one or more straight lines to the current plot abline(h=c(-1,0,1), col = 2, lty = 2, lwd = 1.5) ``` Panel Grid of Plots === class: small-code left: 40% - When datasets with multiple variables are passed to ```plot()``` without X and Y being specified, it will generate a panel grid of plots. ```{r} str(airquality) ``` *** ```{r} plot(airquality) ``` Saving Plots to Files === class: small-code left: 35% - Steps to save a plot to a file - Open a device - Create the plot - Close the device - Supported devices - Vector: svg - Bitmap: jpeg,tiff,png,bmp - PDF: pdf - Postcript: postcript *** Example: saving to a PNG file ```{r, results=F} png("test.png",width=5*240,height=3*240) plot(pressure, type="l") points(pressure,col="red") dev.off() ``` Here is the saved graph: ![Caption](test.png) ggplot2 Package === - "gg" stands for grammar-of-graphics - Any data graphics can be described by specifying - A dataset - Visual marks that represent data points - A coordination system - ```ggplot2``` package in R is an implementation of it - Versatile - Clear and consistent interface - Beautiful output qplot Function === class: small-code - The ```qplot()``` function from ```ggplot2``` package is similar to the ```plot()``` function in the base system. Examine the data: ```{r} str(heightweight) ``` ```{r} summary(heightweight) ``` *** ```{r eval=F} ?heightweight ``` ``` heightweight {gcookbook} R Documentation Height and weight of schoolchildren Description Height and weight of schoolchildren Variables sex ageYear: Age in years. ageMonth: Age in months. heightIn: Height in inches. weightLb: Weight in pounds. Source Lewis, T., & Taylor, L.R. (1967), Introduction to Experimental Ecology, Academic Press. ``` Scatterplot with ```qplot``` Function === class: small-code - Data represented by points ```{r} qplot(weightLb, heightIn, data=heightweight, geom="point") ``` *** - Data represented by labels ```{r} qplot(weightLb, heightIn, data=heightweight, geom ="text", label=ageYear) ``` A Fancier Plot === ```{r,echo=FALSE, fig.width=11, fig.height=9} ggplot(heightweight, aes(x=weightLb, y=heightIn, color=sex, shape=sex)) + geom_point(size=3.5) + ggtitle("School Children\nHeight ~ Weight") + labs(y="Height (inch)", x="Weight (lbs)") + stat_smooth(method=loess, se=T, color="black", fullrange=T) + annotate("text",x=145,y=75,label="Locally weighted polynomial fit with 95% CI",color="Green",size=6) + scale_color_brewer(palette = "Set1", labels=c("Female", "Male")) + guides(shape=F) + theme_bw() + theme(plot.title = element_text(size=20, hjust=0.5), legend.position = c(0.9,0.2), axis.title.x = element_text(size=20), axis.title.y = element_text(size=20), legend.title = element_text(size=15),legend.text = element_text(size=15)) ``` A Fancier Plot === class: small-code This is what is under the hood: ```{r, fig.keep = "none"} ggplot(heightweight, aes(x=weightLb, y=heightIn, color=sex, shape=sex)) + geom_point(size=3.5) + ggtitle("School Children\nHeight ~ Weight") + labs(y="Height (inch)", x="Weight (lbs)") + stat_smooth(method=loess, se=T, color="black", fullrange=T) + annotate("text",x=145,y=75,label="Locally weighted polynomial fit with 95% CI",color="Green",size=6) + scale_color_brewer(palette = "Set1", labels=c("Female", "Male")) + guides(shape=F) + theme_bw() + theme(plot.title = element_text(size=20, hjust=0.5), legend.position = c(0.9,0.2), axis.title.x = element_text(size=20), axis.title.y = element_text(size=20), legend.title = element_text(size=15),legend.text = element_text(size=15)) ``` Don't Panic!!! Basic Concepts of ggplot2 === class: small-code left: 35% Grammar of Graphics components: - Data: Use the ```ggplot``` function to indicate what data to use - Visual marks: Use ```geom_xxx``` functions to indicate what types of visual marks to use - Points, lines, area, etc. - Mapping: Use aesthetic properties (```aes()``` function) to map variables to visual marks - Color, shape, size, x, y, etc. *** ```{r} ggplot(heightweight, # What data to use aes(x=weightLb,y=heightIn)) + # Aesthetic specifies variables geom_point() # Geom specifies visual marks ``` This is equivalent to: ```{r eval = F} qplot(weightLb, heightIn, data=heightweight, geom="point") ``` Histogram with ggplot2 === class: small-code ```{r} ggplot(mpg,aes(x=hwy)) + geom_histogram(binwidth=5, fill="white", color="black") ``` Contour Plots with ggplot2 === class: small-code ```{r} ggplot(faithfuld, aes(waiting, eruptions, z = density))+ geom_raster(aes(fill = density)) + geom_contour(colour = "white") ``` Maps with ggplot2 === class: small-code left: 80% ```{r echo=F} library(maps) ``` - Combined with the ```maps``` package, one can create geographical graphs ```{r fig.width=12,fig.height=7.5} east_asia <- map_data("world", region=c("Japan","China","North Korea","South Korea")) ggplot(east_asia, aes(x=long,y=lat,group=group, fill=region)) + geom_polygon(color="black") + scale_fill_brewer(palette="Set2") ``` *** List of Geoms in ggplot2 === There are more than 30 geoms in ggplot2 - One variable - geom_bar - geom_area - Two variables - geom_point - geom_smooth - geom_text - geom_boxplot *** - Graphic primitives - geom_path - geom_polygon - Error visualizatoin - geom_errorbar - Special - geom_map - geom_contour Customizing Appearance of Data Points === class: small-code left: 40% - Appearance of Data Points can be customized with the ```geom``` functions - Color - Shape (symbol) - Size - Alpha (transparency) *** ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(shape=13,size=5,color='red',alpha=0.5) ``` List of Symbols === - There are 25 built-in shapes ```{r echo=F} df_shapes <- data.frame(shape = 0:24) ggplot(df_shapes, aes(0, 0, shape = shape)) + geom_point(aes(shape = shape), size = 5, fill = 'red') + scale_shape_identity() + facet_wrap(~shape) + theme_void() ``` Notes on Colors === class: small-code - A list of possible color names can be obtained with the function ```colors()``` - Can also use hex values - Starts with a "#" ```{r} colors() ``` Adding More Layers to A Plot === class: small-code - New layers can be added to a plot by using ```geom_xxx``` functions ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point() + geom_quantile(quantiles = c(0.25,0.5,0.75)) + geom_text(label=rownames(heightweight), vjust=-0.5) ``` More on Aesthetic Mapping === class: small-code - Aesthetic mappings describe how variables in the data are mapped to visual properties - Colors, shapes, sizes, transparency etc. - Controlled by the ```aes()``` function - Can be specified in either ``ggplot`` function or individual layers - Aesthetic mappings specified in ```ggplot``` are default, but can be overriden in individual layers Mapping Discrete Variables to Aesthetic Properties === class: small-code - Discret data values can be mapped to an aesthetic value to group data points Example: use the "sex" variable to group data points by shape and color: ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(aes(shape=sex,color=sex)) ``` *** Specify the shapes and colors manually (more on ```stat``` function later): ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(aes(shape=sex,color=sex),size=4) + scale_shape_manual(values=c(1,4)) + scale_color_manual(values=c("blue","green")) ``` Mapping Continuous variables to Aesthetic Properties === class: small-code - Continuous variables can be mapped to aesthetic values too ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(aes(shape=sex,color=sex,size=ageYear)) ``` Adding Fitted Models === class: small-code Use ```stat_smooth``` function to add a fitted model to the plot: ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(aes(shape=sex,color=sex),size=4) + scale_shape_manual(values=c(1,4)) + scale_color_manual(values=c("blue","green")) + stat_smooth(method = lm, level=0.95) ``` *** Moving the ```color=sex``` statement to the ```ggplot``` function produces two lines: ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn, color=sex)) + geom_point(aes(shape=sex),size=4) + scale_shape_manual(values=c(1,4)) + scale_color_manual(values=c("blue","green")) + stat_smooth(method = lm, level=0.95) ``` Labeling individual points === class: small-code To label data points, use either ```annotate``` or ```geom_text``` ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(aes(shape=sex,color=sex,size=ageYear)) + annotate("text",x=150,y=68,label="Some label",color="darkgreen",size=12) ``` *** ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn)) + geom_point(aes(shape=sex,color=sex,size=ageYear)) + geom_text(aes(label=ageYear),vjust=0.5) ``` Stat Functions === class: small-code - Some plots visualize a transformation of the original dataset. - Use a ```stat_xxx``` function to choose a common transformation to visualize. We have seen the ```stat_smooth()``` function: ```{r} ggplot(heightweight, aes(x=weightLb,y=heightIn, color=sex)) + geom_point(aes(shape=sex),size=4) + scale_shape_manual(values=c(1,4)) + scale_color_manual(values=c("blue","green")) + stat_smooth(method = lm, level=0.95) ``` Stat Functions === class: small-code left: 40% Another example: ```stat_bin()``` function creates a frequency count: ```{r} ggplot(mpg,aes(x=hwy)) + stat_bin(binwidth = 5) ``` *** This is equivalent to: ```{r eval=F} ggplot(mpg,aes(x=hwy)) + geom_histogram(binwidth = 5) ``` Or: ```{r eval=F} ggplot(mpg,aes(x=hwy)) + geom_histogram(stat="bin", binwidth = 5) # The "bin" stat is the implied default for histogram ``` Stat Functions === class: small-code Density plot with ```stat_density```: ```{r} ggplot(mpg,aes(x=hwy)) + stat_density() ``` *** Or the same plot with ```geom_histogram```: ```{r} ggplot(mpg,aes(x=hwy)) + geom_histogram(stat="density") ``` Saving Plot to An Object === class: small-code - A ```ggplot``` plot can be saved in an object - More convenient when you are experienting ```{r} p <- ggplot(heightweight, aes(x=weightLb,y=heightIn)) p + geom_point(aes(shape=sex,color=sex,size=ageYear)) ``` *** ```{r} # Here we use the saved plot object "p" p + geom_smooth(method=lm) ``` Saving Plots to Files === class: small-code With ```ggplot2``` one can use the ```ggsave()``` function to save a plot: ```{r echo=T, results=F, fig.keep='none'} ggplot(heightweight, aes(x=weightLb,y=heightIn, color=sex)) + geom_point(aes(shape=sex),size=4) + scale_shape_manual(values=c(1,4)) + scale_color_manual(values=c("blue","green")) + stat_smooth(method = lm, level=0.99) ggsave("hw.png",width=6,height=6) ``` Plot Titles === class: small-code To add a title, use either ```ggtitle``` or ```labs(title=)``` ```{r} p <- ggplot(heightweight, aes(x=weightLb,y=heightIn, color=sex)) + geom_point(aes(shape=sex),size=4) + scale_shape_manual(values=c(1,4)) + scale_color_manual(values=c("blue","green")) p + ggtitle("Height ~ weight of school children") ``` Note the title is left-aligned by default. Axis Labels === class: small-code To add axis labels, use either ```(x|y)lab``` or ```labs(x=,y=)``` ```{r} p + ggtitle("Height ~ weight of school children") + xlab("Weight (lbs)") + ylab("Height (inch)") ``` Legend Titles === class: small-code - Use ```labs(=)``` to specify legend titles ```{r} p + ggtitle("Height ~ weight of school children") + xlab("Weight (lbs)") + ylab("Height (inch)") + labs(color='Gender', shape='Gender') ``` Legends === class: small-code - Use the ```guides``` function to set legend type for each aesthetic properties. Before: ```{r} p <- ggplot(heightweight, aes(x=weightLb,y=heightIn,color=ageYear)) + geom_point(aes(shape=sex)) p ``` *** After: ```{r} p + guides(shape='none',color='legend') ``` Themes === class: small-code - Themes decide the appearance of a plot - ```ggplot2``` provides a few pre-defined themes for users to choose from The classic theme: ```{r } p <- ggplot(heightweight, aes(x=weightLb,y=heightIn, color=sex)) + geom_point(aes(shape=sex),size=4) p + theme_classic() ``` *** The dark theme: ```{r} p + theme_dark() ``` Package ggthemes === class: small-code ```{r echo=F} library(ggthemes) ``` - Additional themes are available from the ```ggthemes``` package Example: Excel theme ```{r} p + theme_excel() ``` Fine-tuning the Theme === class: small-code - Most elements related to appearance are controlled by the ```theme()``` function. - Fonts (family, size, color etc.) - Background color - Grid lines - Axis ticks *** Removing the grid lines: ```{r} p + theme_bw() + theme(panel.grid = element_blank()) ``` Fine-tuning the Theme === class: small-code - Most elements related to appearance are controlled by the ```theme()``` function. - Fonts (family, size, color etc.) - Background color - Grid lines - Axis ticks *** Or just removing the vertical ones: ```{r} p + theme_bw() + theme(panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank()) ``` Customizing Fonts === class: small-code left: 30% Change the base size and font family: ```{r} p + theme_bw(base_size = 24, base_family = "Times") ``` *** Or fine tune each element: ```{r fig.width=6,fig.height=6} p + theme_bw(base_size = 24, base_family = "Times") + theme(legend.title = element_text(size=20,color="blue"),# Legend title legend.text = element_text(size=18,color="red"), # Legend text axis.title.x = element_text(size=18,color="red"), # X axis label axis.title.y = element_blank(), # Remove Y axis label ) ``` The ```element_blank()``` function can be used to remove undesired elements. Changing Legend Position === class: small-code ```{r} p + theme_bw(base_size = 24, base_family = "Times") + theme(legend.position = "bottom") ``` *** ```{r} p + theme_bw(base_size = 24, base_family = "Times") + theme(legend.position = c(0.9,0.1)) ``` List of Theme Elements === class: small-code Elements that can be adjusted with the theme() function: ``` theme(line, rect, text, title, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.y, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.y, axis.text.y.right, axis.ticks, axis.ticks.x, axis.ticks.y, axis.ticks.length, axis.line, axis.line.x, axis.line.y, legend.background, legend.margin, legend.spacing, legend.spacing.x, legend.spacing.y, legend.key, legend.key.size, legend.key.height, legend.key.width, legend.text, legend.text.align, legend.title, legend.title.align, legend.position, legend.direction, legend.justification, legend.box, legend.box.just, legend.box.margin, legend.box.background, legend.box.spacing, panel.background, panel.border, panel.spacing, panel.spacing.x, panel.spacing.y, panel.grid, panel.grid.major, panel.grid.minor, panel.grid.major.x, panel.grid.major.y, panel.grid.minor.x, panel.grid.minor.y, panel.ontop, plot.background, plot.title, plot.subtitle, plot.caption, plot.margin, strip.background, strip.placement, strip.text, strip.text.x, strip.text.y, strip.switch.pad.grid, strip.switch.pad.wrap, ..., complete = FALSE, validate = TRUE) ``` Reset the default theme === class: small-code - The default them is ```theme_grey()``` - Use ```theme_set()``` to change the default With old default: ```{r} p ``` *** With new default: ```{r} theme_set(theme_light()) p ``` Creating Your Own Theme === class: small-code - You can create your own theme and reuse later: ```{r} mytheme <- theme_bw(base_size = 24, base_family = "Times") + theme(legend.title = element_text(size=20,color="blue"),# Legend title legend.text = element_text(size=18,color="red"), # Legend text axis.title.x = element_text(size=18,color="red"), # X axis label axis.title.y = element_blank(), # Remove Y axis label ) p + mytheme ``` Coordination systems === Functions that control the coordination system - ```coord_cartesian``` - the default cartesian coordinates - ```coord_flip``` - flip X and Y - ```coord_polar``` - polar coordinates - ```coord_trans``` - transform cartesian coordinates Coordination systems === class: small-code Original: ```{r} g <- ggplot(mpg,aes(x=hwy)) + geom_histogram(binwidth=5, fill="white", color="black") g ``` *** With flipped coorinates: ```{r} g + coord_flip() ``` Coordination systems === class: small-code Original: ```{r} g ``` *** With transformed Y coordinate: ```{r} g + coord_trans(y="sqrt") ``` Axis Limits === class: small-code - Use the ```xlim()``` and ```ylim()``` functions to set the range of axes: ```{r} p + theme_light() + xlim(0,200) + ylim(50,100) ``` Scales === class: small-code - The ```scale__(continuous|discrete|manual|identity|...)``` family of functions controls how data points are mapped to aesthetic values - Color - Shape - Size - Alpha (transparency) - X and Y location ```{r} ``` X and Y scales === class: small-code ```scale_x_continuous```: scale for X, which is a continuous variable ```{r} p + theme_bw() + ylim(50,100) + scale_x_continuous(limits=c(0,200), breaks=c(50,110,170), labels=c("Thin","Medium\nSize","Chubby")) ``` X and Y scales === class: small-code ```{r} p + theme_economist_white() + scale_x_log10(breaks=c(10,20,50,100,200), limits=c(5,500)) + # Plot X on a log10 scale scale_y_reverse() # Reverse the Y scale ``` Legend Labels === class: small-code left: 45% - Scale functions can be used to customize legend labels - Color, shape, size, fill etc. ```{r} ggplot(mpg,aes(x=drv,y=cty,fill=drv)) + geom_boxplot() ``` *** ```{r} ggplot(mpg,aes(x=drv,y=cty,fill=drv)) + geom_boxplot() + scale_fill_discrete(limits=c("f","r","4"), labels=c("Front","Rear","4 Wheel Drive")) ``` Other scales === class: small-code left: 43% By default: ```{r} ggplot(mpg,aes(x=displ,y=hwy,size=cyl, color=drv,shape=fl)) + geom_point(aes(alpha=cty)) ``` *** Re-scaled ```{r} ggplot(mpg,aes(x=displ,y=hwy,size=cyl,color=drv, alpha=cty)) + geom_point() + scale_size_identity() + # Use the values of "cyl" variable for size scale_color_manual(values=c("darkblue","rosybrown2","#24FA22")) + scale_alpha_continuous(range=c(0.1,1)) ``` Faceting === class: small-code left: 40% - Facets divide a plot into subplots based on the values of one or more discrete variables. - Faceting in ```ggplot2``` is managed by the functions ```facet_grid``` and ```facet_wrap```. *** ```facet_grid```: create a row of panels defined by the variable "drv": ```{r} ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(. ~ drv) ``` Facet_grid === class: small-code ```facet_grid```: creates a column of panels defined by the variable "fl": ```{r} ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(fl ~ .) ``` Facet_grid === class: small-code ```facet_grid```: creates a matrix of panels defined by the variables "fl" and "drv": ```{r} ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(fl ~ drv) ``` Facet_wrap === class: small-code ```facet_wrap```: wraps 1d sequence of panels into 2d: ```{r} ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(~class, nrow=3) ``` Online Interactive Graphics === class: small-code - Plot.ly - https://plot.ly/ - Interactive charts - Both online and offline - R Shiny - https://shiny.rstudio.com/gallery/ - Web application with R Plot.ly === class: small-code Open your browser and try: https://plot.ly/~lyan1/2/ The code: ```{r eval=F} library(plotly) nmmaps<-read.csv("chicago-nmmaps.csv", as.is=T) nmmaps$date<-as.Date(nmmaps$date) nmmaps<-nmmaps[nmmaps$date>as.Date("1996-12-31"),] nmmaps$year<-substring(nmmaps$date,1,4) g <- ggplot(nmmaps, aes(date, temp, color=factor(season)))+ geom_point() + scale_color_manual(values=c("dodgerblue4", "darkolivegreen4", "darkorchid3", "goldenrod1")) #ggplotly(g) # offline api_create(g, filename = NULL, fileopt = "new", sharing = "public") ``` Further Reading === - Good cheat sheets are always welcome - https://github.com/rstudio/cheatsheets/raw/master/data-visualization-2.1.pdf - http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/ - ```R Graphics Cookbook``` is a good reference - R documentation