class: title-slide, bottom, right background-image: url(https://images.unsplash.com/photo-1570386230314-9fe8204c6f80?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1708&q=80) background-size: cover ### Plotting # ### **Miriam Lerma**<br> June 2023 --- name: index class: title-slide, inverse # Index - [theory](#theory) - [geometries](#geoms) - [maps](#maps) - [aesthetics](#aesthetics) - [layers](#layers) - [export](#export) - [contact](#out) --- class: title-slide, inverse # Today .pull-left[ **Your profile** - You know how to use a Rmd document - You know how to install packages **Goals of today** - Create plots and maps in R - Change the apparence of the plots - Export you plots **Pauses and questions** - Exercises and 10 minute pauses for catching up - You can stop me to ask questions or use [this link
]( https://docs.google.com/document/d/1uG7a2_hkdaKQm5gKXRBFf6gcyoUBan2e69gL3ZKcwg8/edit?usp=sharing) ] .pull-right[ We will use the packages ```r devtools::install_github("MiriamLL/sula") devtools::install_github("MiriamLL/GermanNorthSea") devtools::install_github("MiriamLL/seamonas") install.packages('sf') install.packages('ggspatial') install.packages('plotly') ``` ] --- class: inverse # References .pull-left[ Tutorials/Books ggplot - [gg is for Grammar of Graphics](https://pkg.garrickadenbuie.com/trug-ggplot2)<br> - [Introduccion to ggplot](https://englelab.gatech.edu/useRguide/introduction-to-ggplot2.html) - [r4ds](https://r4ds.had.co.nz/data-visualisation.html) - [R Graphics Cookbook](https://r-graphics.org/) - [Allison Horst tutorial](https://allisonhorst.github.io/rice-data-viz/) - [Coolors](https://coolors.co/) <br> - [Palettes](https://mycolor.space/?hex=%23845EC2&sub=1) - [Size, Shape, Lines](https://ggplot2.tidyverse.org/articles/ggplot2-specs.html) - [Geocomputation with R](https://r.geocompx.org/attr.html) - [Earth Data Science](https://www.earthdatascience.org/) - [r-spatial](https://r-spatial.org/r/2018/10/25/ggplot2-sf-3.html) Gallery/Portafolios - [Data-Viz-Bookmarks](https://spcanelon.notion.site/spcanelon/Data-Viz-Bookmarks-dc01718020bd4fd6a8a4ca80e6bce933)<br> - [RGraphGallery](https://www.r-graph-gallery.com/) <br> - [DataToViz](https://www.data-to-viz.com/) <br> - [Georgios-Mastodon](https://ecoevo.social/@georgios@vis.social) ] .pull-right[ <img src="https://cdn.myportfolio.com/45214904-6a61-4e23-98d6-b140f8654a40/9a306c0a-dac8-413d-ba2e-cc7fd4c4d5c8_rw_1920.png?h=c802991088a9623f1f7aa18c470797ee" height="300" /> ] --- ## 1. Theory A typical R project looks like this: <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/031Program.png?raw=true" height="200" /> .right[ Source: [R4DS](https://r4ds.had.co.nz/introduction.html) ] --- name: theory ## 1.1. Theory The objective of a graph/plot/map/chart is to communicate. <br> In science, the idea is to show information in a clear and understandable way. <img src="http://www.typesofgraphs.com/wp-content/uploads/2015/12/Typesofgraphs.png" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory Plotting is transforming data to visualizations that vary in shape, size and colors. <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_1.jpg" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory There are many ways to plot data, and different ways to interpretate the graphs. <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_2.jpg" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory Which one is more intuitive? <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_4.jpg" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory Which one should I use? You can try different plots and choose the one that betters tells the story. **Tableau Public** has a suggestion on which graph to use according to the type of data you are using. <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_5.jpg" height="300" /> --- name: intro ## 1.2. Intro There are many packages to create plots in R. - Here we will use **ggplot2**. ggplot is the most versatile one, and from which you can find more help and inspiration. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/ggplot2hex.png?raw=true" height="200" /> --- ## 1.2. Intro It can be divided in three main components: - **Data** (data): which are the variables that we plot. - **Geometry** (geom): a geometric object such as dots, lines, bars. - **Aesthetics** (aes): the aesthetic attributes to a geometric object, such as position, color, shape and size. Each component is displayed as **layers**. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/300Geoms.png?raw=true" height="200" /> Source [ggplot2 book](https://englelab.gatech.edu/useRguide/working-with-data-overview.html) --- ## 1.3. Data The package ggplot is already included in tidyverse. <br> If you have installed tidyverse you just need to call your package. ```r library(tidyverse) ``` If not you can also install it separately. ```r install.packages("ggplot2") ``` --- ## 1.3. Data For the exercises, we can use data from packages.<br> Lets add our object to our **environment**. Package with data ```r library(palmerpenguins) penguins<-penguins ``` Call library **ggplot2**. ```r library(ggplot2) ``` --- ## 1.3. Data First step: add data to a plot. ```r ggplot(data=penguins) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-16-1.png)<!-- --> We told ggplot what data frame we want to use, but need to give instruction on how to plot. <br> --- ## 1.3. Add axis Using **mapping** we tell ggplot what to plot in the x and y axis.<br> **Note** that the axis are columns from your data frame. This is when having tidydata is important. ```r ggplot(data=penguins, * mapping=aes(x=bill_length_mm, * y=bill_depth_mm)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-17-1.png)<!-- --> --- ## 1.3. Geometry The next step is to give it a geometry, in this case we say plot points with the argument **geom_point** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_point() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-18-1.png)<!-- --> It would likely show a **warning**. <br> This is because NAs are not going to be plotted and R is trying to warn you. --- ## 1.3. Geometry There are many **geometries**. Most of them start with **geom_*** <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/302geometries.png?raw=true" height="400" /> --- ## 1.3. Geometry Examples of most common geometries are to be found on [R-graph-gallery](https://r-graph-gallery.com/). .pull-left[ <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/302examples.png?raw=true" height="150" /> <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/306examples.png?raw=true" height="200" /> ] .pull-right[ <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/307examples.png?raw=true" height="200" /> ] --- ## 1.4. Common mistakes The most common mistakes with plotting are the same as while writing code. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/023DebuggingBingo.jpg?raw=true" height="450" /> --- ## 1.4. Common mistakes Other common mistakes specific to ggplot are: - Forgetting a plus symbol ( **+** ) ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm)) geom_point() ``` - Adding the **+** on the wrong order ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm)) +geom_point() ``` - Forgetting a parenthesis ```r ggplot(penguins, * aes(x=bill_length_mm,y=flipper_length_mm)+ geom_point() ``` --- ## 1.4. Common mistakes Not having **tidydata** is also a very common problem. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/104TidyData.jpg?raw=true" height="300" /> Source [Allison Horst](https://allisonhorst.com/) --- ## 1.5. Cheat sheet Help>CheatSheets>Data Visualization with ggplot <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/314cheatsheet.png?raw=true" height="400" /> --- ## 1.6. Simplify We can skip writing **data=** and **mapping=** by just following the order of the elements. Both codes give the same output. .pull-left[ Including the elements. ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm, y=flipper_length_mm))+ geom_point() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-29-1.png)<!-- --> ] .pull-right[ Simplified example. ```r ggplot(penguins, aes(x=bill_length_mm, y=flipper_length_mm,))+ geom_point() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-30-1.png)<!-- --> ] --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Create your first plot in R. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/316RmdIcon.png?raw=true" height="50" /> ![](Plotting_0606_files/figure-html/unnamed-chunk-32-1.png)<!-- --> ] .pull-right[ Until here: - [index](#index) - [theory](#theory) Next part: - [geometries](#geoms) - [maps](#maps) - [aesthetics](#aesthetics) - [layers](#layers) - [export](#export) - [contact](#out) ] --- name: geoms class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1639303638626-2003b9ac307e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80) background-size:cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Geometries</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Different displays</span> ] --- name: scatterplot ## 2.1. Scatterplots The scatterplot is most useful for displaying the relationship between two continuous variables. Each dot represents an observation. Their position on the x (horizontal) and y (vertical) axis represents the values of the 2 variables. The argument to create scatterplots is **geom_point** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_point() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-33-1.png)<!-- --> See more [scatterplots](https://r-graph-gallery.com/scatterplot.html) --- name: lines ## 2.2. Line chart A line chart or line graph displays the evolution of one or several numeric variables. <br> Data points are connected by straight line segments. The argument to create line charts is **geom_line()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_line() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-34-1.png)<!-- --> See more [line chart](https://r-graph-gallery.com/line-plot.html) --- name: barplot ## 2.3. Barplot A barplot is used to display the relationship between a numeric and a categorical variable.<br> The argument to create barplots is **geom_bar()** ```r ggplot(data=penguins, mapping=aes(x=species,y=body_mass_g))+ * geom_bar() ``` Error: stat_count() can only have an x or y aesthetic. Different from the logic of the previous plots, we need to tell what do you want inside the bars by adding **stats=**. --- ## 2.3. Barplot The argument **stats=** is to be included inside the parethesis of **geom_bar** ```r ggplot(data=penguins, mapping=aes(x=species,y=body_mass_g))+ * geom_bar(stat='identity') ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-36-1.png)<!-- --> See more [barplots](https://r-graph-gallery.com/barplot.html) --- name: boxplot ## 2.4. Boxplot Boxplot is probably the most commonly used chart type to compare distribution of several groups.<br> It visualises five summary statistics (the median, two percentiles and two whiskers). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/305boxplot.png?raw=true" height="250" /> Source [boxplot explanation](https://www.leansigmacorporation.com/box-plot-with-minitab/) --- ## 2.4. Boxplot The argument to create boxplots is **geom_boxplot()** ```r ggplot(data=penguins, mapping=aes(x=species,y=body_mass_g))+ * geom_boxplot() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-38-1.png)<!-- --> See more [boxplots](https://r-graph-gallery.com/boxplot.html) --- name: trajectory ## 2.5. Trajectory For plotting moving objects, connecting points with a line is the most common visualization used. -- For today exercises, install **sula**. ```r devtools::install_github("MiriamLL/sula") ``` The package **sula** contains tracking data from Masked boobies on Easter Island. ```r library(sula) ``` Load data from the package **sula** into the environment. ```r tracking_data<-sula::GPS_raw ``` The data frame contains the columns **Latitude** and **Longitude**. --- ## 2.5. Trajectory The argument to create trajectories is **geom_path()**. By definition geom_path() connects the observations in the order in which they appear in the data. ```r ggplot(data=tracking_data, mapping=aes(x=Latitude, y=Longitude)) + * geom_path() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-42-1.png)<!-- --> --- ## 2.6. Maps R is an great tool for geospatial data analysis. The book [geocomputation with R](https://r.geocompx.org/attr.html) is a recommended guide to create maps in R (is open access and constantly updated). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/306Book.png?raw=true" height="400" /> --- ## 2.6. Maps For today exercises, install **GermanNorthSea**. ```r devtools::install_github("MiriamLL/GermanNorthSea") ``` The package **GermanNorthSea** compiles shapefiles from the North Sea. ```r library(GermanNorthSea) ``` To see the containing shapefiles go to my [github](https://github.com/MiriamLL/GermanNorthSea). To add shapefile to environment. ```r Europe<-German_land ``` **Note** that shapefiles can be an **sf** object. An sf object is different from a data frame, if we click on the object is not clear what it contains. ```r class(Europe) ``` ``` ## [1] "sf" "data.frame" ``` --- ## 2.6. Maps The argument to create a map is **geom_sf()** ```r ggplot(data=Europe)+ * geom_sf() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-48-1.png)<!-- --> --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Run the code for plotting different geometries. **Note** to see the plot in a separated window, search for the following icon. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/314Icon.jpg?raw=true" height="150" /> ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [geometries](#geoms) Next part: - [maps](#maps) - [aesthetics](#aesthetics) - [layers](#layers) - [export](#export) - [contact](#out) ] --- name: maps class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1518065896235-a4c93e088e7a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80) background-size: cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Maps</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Elements of a map</span> ] --- ## 3.Maps What makes a map a map? A map is a symbolic representation of selected characteristics of a place, usually drawn on a flat surface. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/317PaulaScher.png?raw=true" height="350" /> Source [Paula Scher](https://www.pentagram.com/news/paula-scher-maps) --- ## 3.1. Shapefile A [shapefile](https://en.wikipedia.org/wiki/Shapefile) is a format for geospatial vector data. For the exercises download the shapefile from [Europe](https://github.com/MiriamLL/R_intro/blob/master/Downloads/Europe.shp). Give the directory where you save your shapefile, either by calling the package **here**... ```r library(here) My_directory<-here('Downloads') ``` ... or manually by adding the directory where your shapefile is. ```r My_directory<-"..." ``` Check that the folder contains your shapefile. ```r list.files(My_directory) ``` ```r My_shapefile<-paste0(My_directory,"/Europe.shp") ``` --- ## 3.1. Shapefile The package **sf** contains arguments to load shapefiles in R. ```r library(sf) ``` <img src="https://user-images.githubusercontent.com/520851/34887433-ce1d130e-f7c6-11e7-83fc-d60ad4fae6bd.gif" height="200" /> Visit the [sf page](https://r-spatial.github.io/sf/). --- ## 3.1. Shapefile The argument **st_read** loads the shapefile into the environment. ```r Europe_shp<-st_read(My_shapefile) ``` ``` ## Reading layer `Europe' from data source ## `C:\Users\lerma\OneDrive\Documents\2MonTrack\2023\Teaching\R_intro\R_intro\Downloads\Europe.shp' ## using driver `ESRI Shapefile' ## Simple feature collection with 54 features and 2 fields ## Geometry type: MULTIPOLYGON ## Dimension: XY ## Bounding box: xmin: -31.26575 ymin: 32.39748 xmax: 69.07032 ymax: 81.85737 ## Geodetic CRS: WGS 84 ``` **Note** that it gives us the Geodetic CRS: WGS 84 --- ## 3.2. Create a basic map Load the package ggplot2 ```r library(ggplot2) ``` Plot your shapefile using **geom_sf** ```r ggplot(data = Europe_shp)+ geom_sf() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-59-1.png)<!-- --> --- ## 3.3. Add limits Using the argument **coord_sf** to focus in the area of interest. - Add x axis coordinates in **xlim** - Add y axis coordinates in **ylim** . ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-60-1.png)<!-- --> --- name: scale ## 3.4. Add scale To add more elements on a map, the package [ggspatial](https://paleolimbot.github.io/ggspatial/) contains scale and north arrow. ```r library(ggspatial) ``` The argument **annotation_scale** adds a scale. By including **br** the scale is set to the **b**ottom **r**ight. ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ * annotation_scale(location = "br") ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-62-1.png)<!-- --> --- name: arrow ## 3.5. Add arrow For including an arrow add the argument **annotation_north_arrow**. Include **tl** to set the scale on the **t**op **l**eft ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ annotation_scale(location = "br")+ * annotation_north_arrow(location = "tl") ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-63-1.png)<!-- --> --- ## 3.5. Add arrow There are many options for **annotation_north_arrow**. Including **style = north_arrow_minimal()** makes a more minimalistic type of arrow. ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ annotation_scale(location = "br")+ annotation_north_arrow(location = "tl", * style = north_arrow_minimal()) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-64-1.png)<!-- --> --- ## 3.6. Important A coordinate reference system (CRS) refers to the way in which spatial data that represent the earth’s surface. ⚠️ It is important to understand the coordinate system that your data uses - particularly if you are working with different data stored in different coordinate systems. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/313CRSdeformation.jpg?raw=true" height="350" /> --- ## 3.6. CRS All maps are distorted and all projections have some error to represent the earth perfectly. The error is also depending on the [origin](https://www.earthdatascience.org/courses/use-data-open-source-python/intro-vector-data-python/spatial-data-vector-shapefiles/intro-to-coordinate-reference-systems-python/). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/318CRS.png?raw=true" height="150" /> Not using the correct projection might derive in calculation mistakes (over or under calculating distances for example). I will not go into detaill in CRS but give you some tips to transform to the corresponding system. --- ## 3.6. CRS The argument **st_transform** from the package **sf** allows you to change the CRS of your shapefile. First give the name of your shapefile and later the CRS in 4 digits numbers. **Note** that there are many options available in R to transform your CRS. ```r Europe_3035<-sf::st_transform(Europe_shp, 3035) ``` .pull-left[ CRS **4326** ![](Plotting_0606_files/figure-html/unnamed-chunk-68-1.png)<!-- --> ] .pull-right[ CRS **3035** ![](Plotting_0606_files/figure-html/unnamed-chunk-69-1.png)<!-- --> ] Do you notice the **differences?** --- ## 3.6. CRS **Consider** that when using the map with the **CRS 3035**, the units of **xlim** and my **ylim** need to be changed accordingly. ```r ggplot(data=Europe_3035)+ geom_sf()+ * coord_sf(xlim = c(3790000,4250000), ylim = c(3350000,3680000)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-70-1.png)<!-- --> --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Create a map. ![](Plotting_0606_files/figure-html/unnamed-chunk-71-1.png)<!-- --> ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [geometries](#geoms) - [maps](#maps) Next part: - [aesthetics](#aesthetics) - [layers](#layers) - [export](#export) - [contact](#out) ] --- name: aesthetics class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1653408604619-45713aad6d75?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80) background-size:cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Aesthetics</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Bring some colors</span> ] --- ## 4. Aesthetics **Aesthetics** are for controlling the overall appearance of graphs. You can change almost every tiny detail to create the plot that you want. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/308parts-ggplot.png?raw=true" height="350" /> Source [ggplot2 elements](https://isabella-b.com/blog/ggplot2-theme-elements-reference/)<br> Download [pdf](https://isabella-b.com/files/ggplot2-theme-elements-reference-v2.pdf) --- ## 4. Aesthetics There are many elements, but I will not go into detail to most of them. For going into more detail the book [R Graphics cookbook](https://r-graphics.org/) is a great guide. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/310Cookbook.jpg?raw=true" height="300" /> --- name: color ## 4.1. Color by name To go beyond the default colors, the package ggplot2 allows you to change colors on the elements of your plot. To select the colors there are several ways, I use by **name** or **hex codes**. Using by **name**, the default names are used. .pull-left[ You can see a complete list of the 657 colors typing colors(). ```r colors() ``` ] .pull-right[ You can also see the color and the name by opening this [link](https://github.com/MiriamLL/R_intro/blob/master/Images/311colornamesplot.png?raw=true). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/311colornamesplot.png?raw=true" height="300" /> ] --- ## 4.1. Color by hexcode Colors can also be defined by their **hex code**. An hex code is the code of the color in 6 digits. To find the hex code there are tons of webpages. I personally like [coolors](https://coolors.co/palettes/trending). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/312coolors.png?raw=true" height="300" /> --- ## 4.1. Fill color For a map, we can change the color of our shapefile by adding the argument **colour** and **fill** inside the brackets of **geom_sf()** ```r ggplot(data = Europe_shp)+ * geom_sf(color = "orange", * fill = "yellow")+ coord_sf(xlim = c(3, 9),ylim = c(53, 56)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-77-1.png)<!-- --> --- ## 4.1. Fill color To use the color by **hex code** you need to add a **#**. In [coolors](https://coolors.co/palettes/trending) go to explore>put your cursor on top of the color you like>click>paste on your code ```r ggplot(data = Europe_shp)+ * geom_sf(color = "#e76f51", * fill = "#e9c46a")+ coord_sf(xlim = c(3,9), ylim = c(53,56)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-78-1.png)<!-- --> --- ## 4.2. Object To simplify the process, you can save your plot as an object in the environment. ```r My_plot<-ggplot(data = Europe_shp)+ * geom_sf(color = "#e76f51", * fill = "#e9c46a")+ coord_sf(xlim = c(3,9), ylim = c(53,56)) ``` The map is now contained in an object. ```r My_plot ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-80-1.png)<!-- --> --- name: theme ## 4.3. Theme Themes are a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. Themes can be used to give plots a consistent customized look. .pull-left[ The theme can be changed using **theme_classic()** ```r My_plot+ * theme_classic() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-81-1.png)<!-- --> ] .pull-right[ The theme can be changed using **theme_bw()** ```r My_plot+ * theme_bw() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-82-1.png)<!-- --> ] --- ## 4.3. Theme There are many different themes. It would depend on the type of graph and taste to choose. .pull-left[ The theme can be changed using **theme_minimal()** ```r My_plot+ * theme_minimal() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-83-1.png)<!-- --> ] .pull-right[ T he theme can be changed using **theme_void()** ```r My_plot+ * theme_void() ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-84-1.png)<!-- --> ] --- ## 4.3. Theme For maps, in my opinion **theme_bw** is the one that makes most sense. So lets added to our object using the **+** symbol. ```r My_plot<-My_plot+ * theme_bw() My_plot ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-85-1.png)<!-- --> --- name: background ## 4.4. Background colors Adding the argument **theme** and then **panel.background** we can change the color of the background. ```r My_plot<-My_plot + * theme(panel.background = element_rect(fill = '#a8dadc')) My_plot ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-86-1.png)<!-- --> --- ## 4.4. Background colors In theme, the grid can be removed by adding **panel.grid.major** and **panel.grid.minor** and **element_blank** to make it blank. ```r My_plot<-My_plot + * theme(panel.grid.major = element_blank(), * panel.grid.minor = element_blank()) My_plot ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-87-1.png)<!-- --> --- name: axis ## 4.5. Axis legends To change the legends on the axis, we can add the arguments **xlab** and **ylab** ```r My_plot<-My_plot + * xlab('Longitude')+ylab('Latitude') My_plot ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-88-1.png)<!-- --> --- ## 4.6. Add degrees To add the degrees on the x and y axis legends, use a function on **scale_x_continuous** and **scale_y_continuous**. **This is specific from when plotting maps** ```r My_plot<-My_plot + * scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) + * scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) My_plot ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-89-1.png)<!-- --> --- ## 4.7. Esquisse There is an app to personalize all the parts, and gives you the code afterwards. To install the add-inn go to [Esquisse](https://cran.r-project.org/web/packages/esquisse/vignettes/get-started.html). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/319Esquisse.png?raw=true" height="350" /> --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Create a map with your prefered colors. ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [geometries](#geoms) - [maps](#maps) - [aesthetics](#aesthetics) Next part: - [layers](#layers) - [export](#export) - [contact](#out) ] --- name: layers class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1553864250-05b20249ee0c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80) background-size:cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Layers</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Adding geometries</span> ] --- ## 5. Geometries To add observations on a map, we can add geometries. To practice, the package **seamonas** contains data. ```r library(seamonas) ``` To add the data to your environment. <br> ```r survey_4326<-survey_4326 ``` The data frame contains the columns **latitude** and **longitude**. ```r head(survey_4326,5) ``` --- ## 5.1. Add points Because ggplot functions as layers, we can add geometries on top of each other. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/300Geoms.png?raw=true" height="200" /> --- ## 5.1. Add points For the exercise, lets create a base map. ```r Base_map<-ggplot(data = Europe_shp)+ geom_sf(color = "#e76f51", fill = "#e9c46a")+ coord_sf(xlim = c(3,9), ylim = c(53,56))+ theme_bw()+ theme(panel.background = element_rect(fill = '#a8dadc'), panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ xlab('Longitude')+ylab('Latitude')+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W"))+ scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) ``` --- ## 5.1. Add points The order needs to be considered, the geometry to be on the top should be the last on the list. Using the argument **geom_point** we can add points. ```r Base_map+ * geom_point(data=survey_4326,aes(x = longitude,y= latitude)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-96-1.png)<!-- --> --- ## 5.2. Change color Adding the argument **color** inside the parethesis allows to change the color of the points. ```r Base_map+ geom_point(data=survey_4326,aes(x = longitude,y= latitude), * color='red') ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-97-1.png)<!-- --> --- ## 5.2. Change color If you wish to color by a categorical variable, then add **colour =** within your aes brackets. This tells ggplot that this third variable will colour the points. ```r Base_map+ geom_point(data=survey_4326,aes(x = longitude,y= latitude, * color=month)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-98-1.png)<!-- --> --- ## 5.2. Select colors The colors, when not declared, are selected by default.<br> To customize your colors you can add more arguments. <br> The argument **scale_colour_manual** allows you to customize those colors. <br> You can add colors by **name**.<br> Be careful and always add the same number of colors according to the category. ```r Base_map+ geom_point(data=survey_4326,aes(x = longitude,y= latitude, color=month))+ * scale_colour_manual(values = c("purple", "yellow", "orange","green","blue")) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-99-1.png)<!-- --> --- ## 5.3. Change size Adding the argument **size** inside **geom_point** let us change the size of the point. .pull-left[ Smaller size ```r Base_map+ coord_sf(xlim = c(6.2,6.4), ylim = c(55.1,55.2))+ geom_point(data=survey_4326, aes(x = longitude,y= latitude), * size=0.005) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-100-1.png)<!-- --> ] .pull-right[ Larger size ```r Base_map+ coord_sf(xlim = c(6.2,6.4), ylim = c(55.1,55.2))+ geom_point(data=survey_4326, aes(x = longitude,y= latitude), * size=2) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-101-1.png)<!-- --> ] --- ## 5.4. Change shape Adding the argument **shape** inside **geom_point** let us change the shape of the point. .pull-left[ ```r Base_map+ coord_sf(xlim = c(6.2,6.4), ylim = c(55.1,55.2))+ geom_point(data=survey_4326, aes(x = longitude, y= latitude), * shape=4) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-102-1.png)<!-- --> ] .pull-right[ Other options are: <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/320Shapes.png?raw=true" height="200" /> ] --- ## 5.5. Add path The argument **geom_path** can be used for trajectories. ```r Base_map+ * geom_path(data=survey_4326,aes(x = longitude,y= latitude)) ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-104-1.png)<!-- --> --- ## 5.5. Add path .pull-left[ To change line type add the argument **linetype**. ```r Base_map+ geom_path(data=survey_4326, aes(x = longitude,y= latitude), * linetype = 'dashed') ``` ![](Plotting_0606_files/figure-html/unnamed-chunk-105-1.png)<!-- --> ] .pull-right[ Other line options are: <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/321Lines.png?raw=true" height="200" /> ] --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Create your own map with points or a path. ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [geometries](#geoms) - [maps](#maps) - [aesthetics](#aesthetics) - [layers](#layers) Next part: - [export](#export) - [contact](#out) ] --- class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1501868984184-76121ed6a6e2?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80) background-size: cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Export</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Beyond static maps</span> ] --- ## 6.1. Interactive Graphs can be interactive. -> The package [plotly](https://plotly.com/r/) allows creating interactive maps. -> The package [tmap](https://cran.r-project.org/web/packages/tmap/vignettes/tmap-getstarted.html) is also a recommende alternative.
Consider the elements inside the brackets of **aes** are the ones visible when putting the cursor on top. --- ## 6.1. Interactive To install the package plotly. ```r install.packages('plotly') ``` To call the package. ```r library(plotly) ``` To use, include the argument **ggplotly** and add your ggplot inside the brackets. ```r *ggplotly(Base_map+ geom_point(data=survey_4326,aes(x = longitude,y= latitude, color=date))+ scale_colour_manual(values = c("purple", "yellow", "orange","green","blue")) ) ``` --- ## 6.2. Animate Animated plots can also be created in R. However, doing this during a R session would be very time consuming. To recreate the animation, you can see my [blog](www.miriam-lerma.com/blog). <img src="https://github.com/MiriamLL/miriamlerma_/blob/main/animation.gif?raw=true" height="350" /> --- name: export ## 6.3. export To export a plot as a figure there is **ggsave**. Specify the folder where you want the plot to be exported to. ```r ResultsFolder<-here('Downloads') ``` Using the function **ggsave** it would be exported. You can change the extension (.png, .jpg, etc), the width, length, units and dpi. ```r ggsave(My_plot, filename = paste0(ResultsFolder,"/My_plot.png"), width = 24, height = 24, units = "in", dpi = 500) ``` --- ## 6.4. word Another way to export maps is to use a Rmd file like the one on the [link](https://raw.githubusercontent.com/MiriamLL/R_intro/master/04PlotWord.Rmd). For exporting to word, consider: - Not including the code, write **echo=FALSE** in your code chunk. - Not including messages, write **message=FALSE** in your code chunk. - Not including warnings, write **warning=FALSE** in your code chunk. ```r {r,echo=FALSE, warning=FALSE, message=FALSE} ``` To adjust the size of the maps you can specify the fig.height and fig.width in the code chunk ```r {r,fig.height=10, fig.width=10} ``` --- ## 6.5. html The best way to export interactive maps is to use Rmd to html like the one on the [link](https://raw.githubusercontent.com/MiriamLL/R_intro/master/05PlotInteractive.Rmd). Just remember to change the output on the YAML to **html**. ```r output: html_document ``` --- class: inverse # Pause .pull-left[ Practice
<br> - Export a plot in jpg. - Export the plots in a word document. - Export an interactive plot in html. ] .pull-right[ <img src="https://cdn.myportfolio.com/45214904-6a61-4e23-98d6-b140f8654a40/9a306c0a-dac8-413d-ba2e-cc7fd4c4d5c8_rw_1920.png?h=c802991088a9623f1f7aa18c470797ee" height="300" /> ] --- name: out class: title-slide background-image: url(https://images.unsplash.com/photo-1609875133891-443f423fb378?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=687&q=80) background-size: cover ### Back to - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [aesthetics](#aesthetics) - [theme](#theme) - [background](#background) - [layers](#layers) - [axis](#axis) - [interactive maps](#interactive) - [export](#export) .right[ This materials are free of use <br> Download the presentation here: [
github](https://github.com/MiriamLL/R_intro) and [
webpage](https://www.miriam-lerma.com/posts/2023-06-06-plotting/) ] .center[ <h3>
[Home ](https://www.miriam-lerma.com/teaching.html) ] <br>