kekoziar
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 2022 UC Carpentries Fall Workshop, R Day 3, Notes and Cheatsheet tags: ggplot2 --- # 2022 UC Carpentries Fall Workshop, R Day 3, Notes and Cheatsheet ## plotting and report building with `ggplot2` and `knitr` ### Lesson Data We're using a teaching version of the gapminder dataset. There are several ways to obtain this. Just choose one. * [Direct csv download](https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder_data.csv) 1. Right-click to save-as onto your computer, or 2. Right-click to copy link to read into R directly from the github-hosted file * `gapminder <- read.csv("copied-link")`, or 3. Load gapminder package in R * `install.packages("gapminder")` *(as with all packages, you only need to do this once)* * `library("gapminder")` #### Gapminder Documentation * Original source, [gapminder.org](https://www.gapminder.org/data/) * R Package [documentation](https://cran.r-project.org/web/packages/gapminder/index.html) on cran.r-project.org * Many references within [r-project.org](https://search.r-project.org/?P=gapminder&SORT=&HITSPERPAGE=10&DB=r-manuals&DB=r-help&DB=cran-views&DB=cran-info&DB=cran-help&DB=cran-news&DB=cran-readme&DB=cran-vignettes&DEFAULTOP=and&FMT=query&xDB=all&xFILTERS=.%7E%7E) * [R Documentation](https://www.rdocumentation.org/packages/gapminder/versions/0.3.0), powered by DataCamp <hr> # Intro - A Quick look at rstudio.cloud Just an introduction, how to check for installed libraries. <hr> # Plotting with `ggplot2` The first session of Day 3 is [Episode 8](https://swcarpentry.github.io/r-novice-gapminder/08-plot-ggplot2/index.html) from the Software Carpentry R for Reproducible Scientific Analysis Lesson. ## `ggplot` Function Basics ### Syntax of a Basic Call ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point() ``` Putting `geom_point()` on its own line aids in readability, which is useful for a plot with many layers. ### `ggplot` Elements * `ggplot()` creates a new [ggplot](https://ggplot2.tidyverse.org/reference/ggplot.html). * `aes()` is how [aesthetic mappings](https://ggplot2.tidyverse.org/reference/aes.html) are constructed and associated with the data. * there are arguments for colors, how things are grouped, line size & shapes, positions, etc. * Aesthetic arguments which are called outside of the `aes()` function will map to all data points. * `geom_()` are [geometric objects](https://ggplot2.tidyverse.org/reference/#geoms). These are added to the plot in layers, which is why a `ggplot` call includes `+` something (geom/stat) * how are your data displayed? lines, bar charts, heatmaps, contours, polygons, segments, etc * individual `geom_...()` calls can include their own aesthetic mappings, both using the `aes()` function, and directly *(remember, aesthetic arguments assigned outside the `aes()` function will apply to all variables/data points)* ### Challenge #1 #### Part A In the gapminder example we've been using, ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point() ``` use the column "year" to show how life expectancy has changed over time. #### Part B We’ve been using the `aes` function to tell the scatterplot geom about the x and y locations of each point. Another aesthetic property we can modify is the point `color`. Modify the code from the Part A to color the points by the “continent” column. Is it easier to detect trends? ### Challenge #1 Solutions #### Part A ```r ggplot(data = gapminder, mapping = aes(x = year, y = lifeExp)) + geom_point() ``` #### Part B ```r ggplot(data = gapminder, mapping = aes(x = year, y = lifeExp, color=continent)) + geom_point() ``` ### About Layers ```r ggplot(data = gapminder, mapping = aes(x=year, y=lifeExp, color=continent)) + geom_line() ``` add `by=`: ```r ggplot(data = gapminder, mapping = aes(x=year, y=lifeExp, by=country, color=continent)) + geom_line() ``` add points: ```r ggplot(data = gapminder, mapping = aes(x=year, y=lifeExp, by=country, color=continent)) + geom_line() + geom_point() ``` move color mapping: ```r ggplot(data = gapminder, mapping = aes(x=year, y=lifeExp, by=country)) + geom_line(mapping = aes(color=continent)) + geom_point() ``` ### Challenge #2 *(2-minute challenge)* Using the previous example: ```r ggplot(data = gapminder, mapping = aes(x=year, y=lifeExp, by=country)) + geom_line(mapping = aes(color=continent)) + geom_point() ``` Switch the order of the point and line layers from the previous example. What happened? *Answer: the layers are drawn in a different order, so the lines now cover the points* ## Transformations and statistics ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point() ``` change scale: ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(alpha = 0.5) + scale_x_log10() ``` add smoothing function, `lm` stands for linear model: ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(alpha = 0.5) + scale_x_log10() + geom_smooth(method="lm") ``` ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(alpha = 0.5) + scale_x_log10() + geom_smooth(method="lm", size=1.5) ``` ### About the Tilde `~` The tilde symbol `~` is often used as an operator to describe a statistical model formula. The left side is optional, and denotes the target or dependent variable. The right side is the predictor or independent variable(s). * [R documentation](https://search.r-project.org/R/refmans/base/html/tilde.html) on `~` ### Challenge #3 #### Part A Given ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(alpha = 0.5) + scale_x_log10() + geom_smooth(method="lm", size=1.5) ``` Modify the color and size of the points on the point layer, but don't use the `aes()` function in that layer. #### Part B Modify your solution to Part A so that the points are now a different shape and are colored by continent with new trendlines. Hint: The color argument can be used inside the `aes()` function. This [cheatsheet](https://kekoziar.github.io/cheatsheets/img/ggplot2_data-visualization-2-1_Page_1.png) helps with syntax on assigning arguments. A PDF version is at [RSudio Cheatsheets](https://www.rstudio.com/resources/cheatsheets/). ### Challenge #3 Solutions #### Part A ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp)) + geom_point(size=3, color="orange") + scale_x_log10() + geom_smooth(method="lm", size=1.5) ``` #### Part B ```r ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point(size=3, shape=17) + scale_x_log10() + geom_smooth(method="lm", size=1.5) ``` ## Multipaneled Figures ```r americas <- gapminder[gapminder$continent == "Americas",] ggplot(data = americas, mapping = aes(x = year, y = lifeExp)) + geom_line() + facet_wrap( ~ country) + theme(axis.text.x = element_text(angle = 45)) ``` ```r ggplot(data = americas, mapping = aes(x = year, y = lifeExp, color=continent)) + geom_line() + facet_wrap( ~ country) + labs( x = "Year", # x axis title y = "Life expectancy", # y axis title title = "Figure 1", # main title of figure color = "Continent" # title of legend ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ``` ```r ``` ## Exporting Plots ```r lifeExp_plot <- ggplot(data = americas, mapping = aes(x = year, y = lifeExp, color=continent)) + geom_line() + facet_wrap( ~ country) + labs( x = "Year", # x axis title y = "Life expectancy", # y axis title title = "Figure 1", # main title of figure color = "Continent" # title of legend ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggsave(filename = "results/lifeExp.png", plot = lifeExp_plot, width = 12, height = 10, dpi = 300, units = "cm") ``` ## Cheatsheets, et al * `ggplot` function reference on [tidyverse](https://ggplot2.tidyverse.org/reference/). * RSudio [cheatsheets](https://www.rstudio.com/resources/cheatsheets/) ![ggplot_cheatsheet_page1](https://kekoziar.github.io/cheatsheets/img/ggplot2_data-visualization-2-1_Page_1.png) ![ggplot_cheatsheet_page2](https://kekoziar.github.io/cheatsheets/img/ggplot2_data-visualization-2-1_Page_2.png) <hr> # Create Reports with `knitr` The second session of Day 3 is [Episode 15](https://swcarpentry.github.io/r-novice-gapminder/15-knitr-markdown/index.html) from the Software Carpentry R for Reproducible Scientific Analysis Lesson. * `knitr` library [reference](https://yihui.org/knitr/). * [Markdown cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Here-Cheatsheet) * [R Markdown Cheat Sheet](https://www.rstudio.com/blog/the-r-markdown-cheat-sheet/) ```r ``` ## Creating a Markdown file Within RStudio, click File → New File → R Markdown. You might need to install packages ![install libraries message](https://raw.githubusercontent.com/kekoziar/cheatsheets/main/img/knitr_load_packages.PNG) Fill out as much info as you want, and it will prepopulate the document header. ### Markdown Basics * **bold** with double-asterisks - italics with _underscores_ (or *single asterisks*) * code-type font with `backticks` 1. be consistent with your methods 1. otherwise it will confuse collaborators 1. or, maybe even your future self! # Title ## Main section ### Sub-section #### Sub-sub section ##### with even smaller type ###### how small can it go? When you knit the document, notice how RStudio jumps between the console and the render tab. Error messages, warnings, and other output involving creating the document will appear in the Render tab ### Challenge 1 Create a new R Markdown document. Delete all of the R code chunks and write a bit of Markdown (some sections, some italicized text, and an itemized list). Convert the document to a webpage. ## More Markdown * hyperlinks: `[Carpentries Home Page](https://carpentries.org/)` * images: `![The Carpentries Logo](https://carpentries.org/assets/img/TheCarpentries.svg)` * superscripts F^2^ `F^2^` * subscripts F~2~ `F~2~` * LaTeX: $$y = \mu + \sum_{i=1}^p \beta_i x_i + \epsilon$$ `$$y = \mu + \sum_{i=1}^p \beta_i x_i + \epsilon$$` ## R Code Chunks ``` ```{r load_data} gapminder <- read.csv("gapminder.csv") ``` ## How things are compiled * `knitr` uses [Pandoc](https://pandoc.org/), which is a really cool tool for document conversion! ## Chunk Options ``` ```{r load_libraries, echo=FALSE, message=FALSE} library("dplyr") library("ggplot2") ``` ``` ```{r global_options, echo=FALSE} knitr::opts_chunk$set(fig.path="Figs/", message=FALSE, warning=FALSE, echo=FALSE, results="hide", fig.width=11) ``` ## Inline R ``` `r round(some_value, 2)` ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully