diff --git a/dev/articles/profiling.html b/dev/articles/profiling.html index 9ce6f33604..a2a1c459aa 100644 --- a/dev/articles/profiling.html +++ b/dev/articles/profiling.html @@ -130,7 +130,7 @@

Thomas Lin profile
-

In general, a minimal plot is used so that profiles are focused on +

In general, a minimal plot is used so that profiles are focused on low-level, general code, rather than implementations of specific geoms. This might be expanded at the point where improving performance of specific geoms becomes a focus. Further, the profile focuses on the diff --git a/dev/news/index.html b/dev/news/index.html index 3bee6ffed9..b5aa3d6f0f 100644 --- a/dev/news/index.html +++ b/dev/news/index.html @@ -67,7 +67,8 @@

ggplot2 (development version)

-
diff --git a/dev/reference/coord_trans.html b/dev/reference/coord_trans.html index 019616c41d..55e0e1a796 100644 --- a/dev/reference/coord_trans.html +++ b/dev/reference/coord_trans.html @@ -120,7 +120,11 @@

Argumentsexpand

If TRUE, the default, adds a small expansion factor to the limits to ensure that data and axes don't overlap. If FALSE, -limits are taken exactly from the data or xlim/ylim.

+limits are taken exactly from the data or xlim/ylim. +Giving a logical vector will separately control the expansion for the four +directions (top, left, bottom and right). The expand argument will be +recycled to length 4 if necessary. Alternatively, can be a named logical +vector to control a single direction, e.g. expand = c(bottom = FALSE).

diff --git a/dev/reference/ggsf.html b/dev/reference/ggsf.html index 7dfbdf5c54..efa55229cf 100644 --- a/dev/reference/ggsf.html +++ b/dev/reference/ggsf.html @@ -183,7 +183,11 @@

Argumentsexpand

If TRUE, the default, adds a small expansion factor to the limits to ensure that data and axes don't overlap. If FALSE, -limits are taken exactly from the data or xlim/ylim.

+limits are taken exactly from the data or xlim/ylim. +Giving a logical vector will separately control the expansion for the four +directions (top, left, bottom and right). The expand argument will be +recycled to length 4 if necessary. Alternatively, can be a named logical +vector to control a single direction, e.g. expand = c(bottom = FALSE).

crs
diff --git a/dev/reference/summarise_plot.html b/dev/reference/summarise_plot.html index 76e5c22fe0..e9a69098a0 100644 --- a/dev/reference/summarise_plot.html +++ b/dev/reference/summarise_plot.html @@ -169,13 +169,13 @@

Examples#> 6 6 2 3 subcompact 1.33 7.27 10.4 45.6 #> 7 7 3 1 suv 1.33 7.27 10.4 45.6 #> xscale yscale -#> 1 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> -#> 2 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> -#> 3 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> -#> 4 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> -#> 5 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> -#> 6 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> -#> 7 <environment: 0x5611aa1a18b8> <environment: 0x5611a6108978> +#> 1 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> +#> 2 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> +#> 3 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> +#> 4 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> +#> 5 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> +#> 6 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> +#> 7 <environment: 0x55b94f2d3860> <environment: 0x55b94ef00760> summarise_coord(b) #> $xlog #> [1] NA diff --git a/dev/search.json b/dev/search.json index 2f5668ae34..28a127d6e1 100644 --- a/dev/search.json +++ b/dev/search.json @@ -1 +1 @@ -[{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"our-pledge","dir":"","previous_headings":"","what":"Our Pledge","title":"Contributor Covenant Code of Conduct","text":"members, contributors, leaders pledge make participation community harassment-free experience everyone, regardless age, body size, visible invisible disability, ethnicity, sex characteristics, gender identity expression, level experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, sexual identity orientation. pledge act interact ways contribute open, welcoming, diverse, inclusive, healthy community.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"our-standards","dir":"","previous_headings":"","what":"Our Standards","title":"Contributor Covenant Code of Conduct","text":"Examples behavior contributes positive environment community include: Demonstrating empathy kindness toward people respectful differing opinions, viewpoints, experiences Giving gracefully accepting constructive feedback Accepting responsibility apologizing affected mistakes, learning experience Focusing best just us individuals, overall community Examples unacceptable behavior include: use sexualized language imagery, sexual attention advances kind Trolling, insulting derogatory comments, personal political attacks Public private harassment Publishing others’ private information, physical email address, without explicit permission conduct reasonably considered inappropriate professional setting","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"enforcement-responsibilities","dir":"","previous_headings":"","what":"Enforcement Responsibilities","title":"Contributor Covenant Code of Conduct","text":"Community leaders responsible clarifying enforcing standards acceptable behavior take appropriate fair corrective action response behavior deem inappropriate, threatening, offensive, harmful. Community leaders right responsibility remove, edit, reject comments, commits, code, wiki edits, issues, contributions aligned Code Conduct, communicate reasons moderation decisions appropriate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"scope","dir":"","previous_headings":"","what":"Scope","title":"Contributor Covenant Code of Conduct","text":"Code Conduct applies within community spaces, also applies individual officially representing community public spaces. Examples representing community include using official e-mail address, posting via official social media account, acting appointed representative online offline event.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"enforcement","dir":"","previous_headings":"","what":"Enforcement","title":"Contributor Covenant Code of Conduct","text":"Instances abusive, harassing, otherwise unacceptable behavior may reported community leaders responsible enforcement codeofconduct@posit.co. complaints reviewed investigated promptly fairly. community leaders obligated respect privacy security reporter incident.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"enforcement-guidelines","dir":"","previous_headings":"","what":"Enforcement Guidelines","title":"Contributor Covenant Code of Conduct","text":"Community leaders follow Community Impact Guidelines determining consequences action deem violation Code Conduct:","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_1-correction","dir":"","previous_headings":"Enforcement Guidelines","what":"1. Correction","title":"Contributor Covenant Code of Conduct","text":"Community Impact: Use inappropriate language behavior deemed unprofessional unwelcome community. Consequence: private, written warning community leaders, providing clarity around nature violation explanation behavior inappropriate. public apology may requested.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_2-warning","dir":"","previous_headings":"Enforcement Guidelines","what":"2. Warning","title":"Contributor Covenant Code of Conduct","text":"Community Impact: violation single incident series actions. Consequence: warning consequences continued behavior. interaction people involved, including unsolicited interaction enforcing Code Conduct, specified period time. includes avoiding interactions community spaces well external channels like social media. Violating terms may lead temporary permanent ban.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_3-temporary-ban","dir":"","previous_headings":"Enforcement Guidelines","what":"3. Temporary Ban","title":"Contributor Covenant Code of Conduct","text":"Community Impact: serious violation community standards, including sustained inappropriate behavior. Consequence: temporary ban sort interaction public communication community specified period time. public private interaction people involved, including unsolicited interaction enforcing Code Conduct, allowed period. Violating terms may lead permanent ban.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_4-permanent-ban","dir":"","previous_headings":"Enforcement Guidelines","what":"4. Permanent Ban","title":"Contributor Covenant Code of Conduct","text":"Community Impact: Demonstrating pattern violation community standards, including sustained inappropriate behavior, harassment individual, aggression toward disparagement classes individuals. Consequence: permanent ban sort public interaction within community.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"attribution","dir":"","previous_headings":"","what":"Attribution","title":"Contributor Covenant Code of Conduct","text":"Code Conduct adapted Contributor Covenant, version 2.1, available https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. Community Impact Guidelines inspired [Mozilla’s code conduct enforcement ladder][https://github.com/mozilla/inclusion]. answers common questions code conduct, see FAQ https://www.contributor-covenant.org/faq. Translations available https://www.contributor-covenant.org/translations.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CONTRIBUTING.html","id":null,"dir":"","previous_headings":"","what":"Contributing to ggplot2 development","title":"Contributing to ggplot2 development","text":"goal guide help get contributing ggplot2 quickly possible. guide divided two main pieces: Filing bug report feature request issue. Suggesting change via pull request. Please note ggplot2 released Contributor Code Conduct. contributing project, agree abide terms.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CONTRIBUTING.html","id":"issues","dir":"","previous_headings":"","what":"Issues","title":"Contributing to ggplot2 development","text":"filing issue, important thing include minimal reproducible example can quickly verify problem, figure fix . three things need include make example reproducible: required packages, data, code. Packages loaded top script, ’s easy see ones example needs. easiest way include data use dput() generate R code recreate . example, recreate mtcars dataset R, ’d perform following steps: Run dput(mtcars) R Copy output reproducible script, type mtcars <- paste. even better can create data.frame() just handful rows columns still illustrates problem. Spend little bit time ensuring code easy others read: make sure ’ve used spaces variable names concise, informative use comments indicate problem lies best remove everything related problem. shorter code , easier understand. can check actually made reproducible example starting fresh R session pasting script . (Unless ’ve specifically asked , please don’t include output sessionInfo().)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CONTRIBUTING.html","id":"pull-requests","dir":"","previous_headings":"","what":"Pull requests","title":"Contributing to ggplot2 development","text":"contribute change ggplot2, follow steps: Create branch git make changes. Push branch github issue pull request (PR). Discuss pull request. Iterate either accept PR decide ’s good fit ggplot2. steps described detail . might feel overwhelming first time get set , gets easier practice. get stuck point, please reach help ggplot2-dev mailing list. ’re familiar git github, please start reading https://r-pkgs.org/software-development-practices.html Pull requests evaluated seven point checklist: Motivation. pull request clearly concisely motivate need change. Unfortunately neither Winston much time work ggplot2 days, need describe problem show pull request solves concisely possible. Also include motivation NEWS new release ggplot2 comes ’s easy users see ’s changed. Add item top file use markdown formatting. news item end (@yourGithubUsername, #the_issue_number). related changes. submit pull request, please check make sure haven’t accidentally included unrelated changes. make harder see exactly ’s changed, evaluate unexpected side effects. PR corresponds git branch, expect submit multiple changes make sure create multiple branches. multiple changes depend , start first one don’t submit others first one processed. Use ggplot2 coding style. Please follow official tidyverse style. Maintaining consistent style across whole code base makes much easier jump code. ’re modifying existing ggplot2 code doesn’t follow style guide, separate pull request fix style greatly appreciated. ’re adding new parameters new function, ’ll also need document roxygen2. Make sure re-run devtools::document() code submitting. fixing bug adding new feature non-graphical function, please add testthat unit test. fixing bug visual output, please add visual test. (Instructions follow soon) ’re adding new graphical feature, please add short example appropriate function. seems like lot work don’t worry pull request isn’t perfect. ’s learning process members ggplot2 team hand help . pull request (“PR”) process, unless ’ve submitted past ’s unlikely pull request accepted . PRs require review approval least one member ggplot2 development team merge. Finally, remember ggplot2 mature package used thousands people. means ’s extremely difficult (.e. impossible) change existing functionality without breaking someone’s code (another package CRAN). Please don’t submit pull requests change existing behaviour. Instead, think can add new feature minimally invasive way.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":null,"dir":"","previous_headings":"","what":"Roles and responsibilities","title":"Roles and responsibilities","text":"project large community users contributors, team core developers, project lead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"users","dir":"","previous_headings":"","what":"Users","title":"Roles and responsibilities","text":"People create visualizations ggplot2 important members community; without users, project purpose. Users encouraged participate life project community much possible. User contributions help ensure project satisfying users’ needs. Common user activities include (limited ): evangelising project asking answering community forums providing moral support (‘thank ’ goes long way) Users continue engage project community often find becoming involved. users may go become contributors, described .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"contributors","dir":"","previous_headings":"","what":"Contributors","title":"Roles and responsibilities","text":"Contributors interact project GitHub filing new issues, improving existing issues, submitting pull requests. Anyone can become contributor: expectation commitment project, required set skills, selection process. obligation follow code conduct. Specific advice contributing project can found CONTRIBUTING.md.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"core-developers","dir":"","previous_headings":"","what":"Core developers","title":"Roles and responsibilities","text":"Core developers collectively responsible day--day development package, including responding issues reviewing pull requests. GitHub administrators package authors, means ability make changes project code, receive credit others cite package. core developers can modify code directly, ability rarely used. Instead, changes proposed pull requests, merged reviewed least one core developer. Changes API (especially breaking changes) must also approved project lead. Core developers recruited contributors. invitation join core team can extended anyone made major contribution, either small number large changes, consistent pattern smaller contributions. existing core developer can propose contributor invited core team emailing project lead. project lead confirm invitation core developers. core developers ggplot2 : Winston Chang Lionel Henry Thomas Lin Pedersen Kohske Takahashi Claus Wilke Kara Woo Hiroaki Yutani Dewey Dunnington Teun van den Brand core developers bound code conduct.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"project-lead","dir":"","previous_headings":"","what":"Project lead","title":"Roles and responsibilities","text":"project lead, Hadley Wickham, responsible : Setting, clearly communication strategic objectives project. Mediating conflicts amongst core developers. Ensuring project survives long term. project lead bound code conduct.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"decision-making-process","dir":"","previous_headings":"","what":"Decision-making process","title":"Roles and responsibilities","text":"project makes decisions according consensus model suggestions considered discussed community core developers, typically GitHub issues. consensus reached, project lead’s word final. community questions decision, project lead may review either uphold reverse .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/LICENSE.html","id":null,"dir":"","previous_headings":"","what":"MIT License","title":"MIT License","text":"Copyright (c) 2020 ggplot2 authors Permission hereby granted, free charge, person obtaining copy software associated documentation files (“Software”), deal Software without restriction, including without limitation rights use, copy, modify, merge, publish, distribute, sublicense, /sell copies Software, permit persons Software furnished , subject following conditions: copyright notice permission notice shall included copies substantial portions Software. SOFTWARE PROVIDED “”, WITHOUT WARRANTY KIND, EXPRESS IMPLIED, INCLUDING LIMITED WARRANTIES MERCHANTABILITY, FITNESS PARTICULAR PURPOSE NONINFRINGEMENT. EVENT SHALL AUTHORS COPYRIGHT HOLDERS LIABLE CLAIM, DAMAGES LIABILITY, WHETHER ACTION CONTRACT, TORT OTHERWISE, ARISING , CONNECTION SOFTWARE USE DEALINGS SOFTWARE.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"ggproto","dir":"Articles","previous_headings":"","what":"ggproto","title":"Extending ggplot2","text":"ggplot2 objects built using ggproto system object oriented programming. OO system used one place: ggplot2. mostly historical accident: ggplot2 started using proto needed mutable objects. well creation (briefly lived) mutatr, reference classes R6: proto game town. ggproto? Well turned add official extension mechanism ggplot2, found major problem caused problems proto objects extended different package (methods evaluated ggplot2, package extension added). tried converting R6, poor fit needs ggplot2. ’ve modified proto, ’ve first involved understanding exactly proto worked, secondly making sure changes didn’t affect users proto. ’s strange say, case inventing new OO system actually right answer problem! Fortunately Winston now good creating OO systems, took day come ggproto: maintains features proto ggplot2 needs, allowing cross package inheritance work. ’s quick demo ggproto action: majority ggplot2 classes immutable static: methods neither use modify state class. ’re mostly used convenient way bundling related methods together. create new geom stat, just create new ggproto inherits Stat, Geom override methods described .","code":"A <- ggproto(\"A\", NULL, x = 1, inc = function(self) { self$x <- self$x + 1 } ) A$x #> [1] 1 A$inc() A$x #> [1] 2 A$inc() A$inc() A$x #> [1] 4"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"the-simplest-stat","dir":"Articles","previous_headings":"Creating a new stat","what":"The simplest stat","title":"Extending ggplot2","text":"’ll start creating simple stat: one gives convex hull (c hull) set points. First create new ggproto object inherits Stat: two important components compute_group() method (computation), required_aes field, lists aesthetics must present order stat work. Next write layer function. Unfortunately, due early design mistake called either stat_() geom_(). better decision call layer_() functions: ’s accurate description every layer involves stat geom. layer functions follow form - specify defaults function arguments call layer() function, sending ... params argument. arguments ... either arguments geom (’re making stat wrapper), arguments stat (’re making geom wrapper), aesthetics set. layer() takes care teasing different parameters apart making sure ’re stored right place: (Note ’re writing package, ’ll either need call ggplot2::layer() explicitly, import layer() function package namespace.) layer function can try new stat: (’ll see later change defaults geom don’t need specify fill = NA every time.) ’ve written basic object, ggplot2 gives lot free. example, ggplot2 automatically preserves aesthetics constant within group: can also override default geom display convex hull different way:","code":"StatChull <- ggproto(\"StatChull\", Stat, compute_group = function(data, scales) { data[chull(data$x, data$y), , drop = FALSE] }, required_aes = c(\"x\", \"y\") ) stat_chull <- function(mapping = NULL, data = NULL, geom = \"polygon\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatChull, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + stat_chull(fill = NA, colour = \"black\") ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + stat_chull(fill = NA) ggplot(mpg, aes(displ, hwy)) + stat_chull(geom = \"point\", size = 4, colour = \"red\") + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"stat-parameters","dir":"Articles","previous_headings":"Creating a new stat","what":"Stat parameters","title":"Extending ggplot2","text":"complex stat computation. Let’s implement simple version geom_smooth() adds line best fit plot. create StatLm inherits Stat layer function, stat_lm(): StatLm inflexible parameters. might want allow user control model formula number points used generate grid. , add arguments compute_group() method wrapper function: Note don’t explicitly include new parameters arguments layer, ... get passed right place anyway. ’ll need document somewhere user knows . ’s brief example. Note @inheritParams ggplot2::stat_identity: automatically inherit documentation parameters also defined stat_identity(). stat_lm() must exported want people use . also consider exporting StatLm want people extend underlying object; done care.","code":"StatLm <- ggproto(\"StatLm\", Stat, required_aes = c(\"x\", \"y\"), compute_group = function(data, scales) { rng <- range(data$x, na.rm = TRUE) grid <- data.frame(x = rng) mod <- lm(y ~ x, data = data) grid$y <- predict(mod, newdata = grid) grid } ) stat_lm <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatLm, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + stat_lm() StatLm <- ggproto(\"StatLm\", Stat, required_aes = c(\"x\", \"y\"), compute_group = function(data, scales, params, n = 100, formula = y ~ x) { rng <- range(data$x, na.rm = TRUE) grid <- data.frame(x = seq(rng[1], rng[2], length = n)) mod <- lm(formula, data = data) grid$y <- predict(mod, newdata = grid) grid } ) stat_lm <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, n = 50, formula = y ~ x, ...) { layer( stat = StatLm, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(n = n, formula = formula, na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + stat_lm(formula = y ~ poly(x, 10)) + stat_lm(formula = y ~ poly(x, 10), geom = \"point\", colour = \"red\", n = 20) #' @export #' @inheritParams ggplot2::stat_identity #' @param formula The modelling formula passed to \\code{lm}. Should only #' involve \\code{y} and \\code{x} #' @param n Number of points used for interpolation. stat_lm <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, n = 50, formula = y ~ x, ...) { layer( stat = StatLm, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(n = n, formula = formula, na.rm = na.rm, ...) ) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"picking-defaults","dir":"Articles","previous_headings":"Creating a new stat","what":"Picking defaults","title":"Extending ggplot2","text":"Sometimes calculations performed complete dataset, group. useful picking sensible default values. example, want density estimate, ’s reasonable pick one bandwidth whole plot. following Stat creates variation stat_density() picks one bandwidth groups choosing mean “best” bandwidth group (theoretical justification , doesn’t seem unreasonable). override setup_params() method. ’s passed data list params, returns updated list. recommend using NULL default value. pick important parameters automatically, ’s good idea message() user (printing floating point parameter, using signif() show significant digits).","code":"StatDensityCommon <- ggproto(\"StatDensityCommon\", Stat, required_aes = \"x\", setup_params = function(data, params) { if (!is.null(params$bandwidth)) return(params) xs <- split(data$x, data$group) bws <- vapply(xs, bw.nrd0, numeric(1)) bw <- mean(bws) message(\"Picking bandwidth of \", signif(bw, 3)) params$bandwidth <- bw params }, compute_group = function(data, scales, bandwidth = 1) { d <- density(data$x, bw = bandwidth) data.frame(x = d$x, y = d$y) } ) stat_density_common <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, bandwidth = NULL, ...) { layer( stat = StatDensityCommon, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(bandwidth = bandwidth, na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, colour = drv)) + stat_density_common() #> Picking bandwidth of 0.345 ggplot(mpg, aes(displ, colour = drv)) + stat_density_common(bandwidth = 0.5)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"variable-names-and-default-aesthetics","dir":"Articles","previous_headings":"Creating a new stat","what":"Variable names and default aesthetics","title":"Extending ggplot2","text":"stat illustrates another important point. want make stat usable geoms, return variable called density instead y. can set default_aes automatically map density y, allows user override use different geoms: However, using stat area geom doesn’t work quite right. areas don’t stack top : density computed independently, estimated xs don’t line . can resolve issue computing range data setup_params().","code":"StatDensityCommon <- ggproto(\"StatDensity2\", Stat, required_aes = \"x\", default_aes = aes(y = after_stat(density)), compute_group = function(data, scales, bandwidth = 1) { d <- density(data$x, bw = bandwidth) data.frame(x = d$x, density = d$y) } ) ggplot(mpg, aes(displ, drv, colour = after_stat(density))) + stat_density_common(bandwidth = 1, geom = \"point\") ggplot(mpg, aes(displ, fill = drv)) + stat_density_common(bandwidth = 1, geom = \"area\", position = \"stack\") StatDensityCommon <- ggproto(\"StatDensityCommon\", Stat, required_aes = \"x\", default_aes = aes(y = after_stat(density)), setup_params = function(data, params) { min <- min(data$x) - 3 * params$bandwidth max <- max(data$x) + 3 * params$bandwidth list( bandwidth = params$bandwidth, min = min, max = max, na.rm = params$na.rm ) }, compute_group = function(data, scales, min, max, bandwidth = 1) { d <- density(data$x, bw = bandwidth, from = min, to = max) data.frame(x = d$x, density = d$y) } ) ggplot(mpg, aes(displ, fill = drv)) + stat_density_common(bandwidth = 1, geom = \"area\", position = \"stack\") ggplot(mpg, aes(displ, drv, fill = after_stat(density))) + stat_density_common(bandwidth = 1, geom = \"raster\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises","dir":"Articles","previous_headings":"Creating a new stat","what":"Exercises","title":"Extending ggplot2","text":"Extend stat_chull compute alpha hull, alphahull package. new stat take alpha argument. Modify final version StatDensityCommon allow user specify min max parameters. ’ll need modify layer function compute_group() method. Note: careful adding parameters layer function. following names col, color, pch, cex, lty, lwd, srt, adj, bg, fg, min, max intentionally renamed accommodate base graphical parameter names. example, value passed min layer appears ymin setup_params list params. recommended avoid using names layer parameters. Compare contrast StatLm ggplot2::StatSmooth. key differences make StatSmooth complex StatLm?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-a-new-geom","dir":"Articles","previous_headings":"","what":"Creating a new geom","title":"Extending ggplot2","text":"’s harder create new geom new stat also need know grid. ggplot2 built top grid, ’ll need know basics drawing grid. ’re serious adding new geom, ’d recommend buying R graphics Paul Murrell. tells everything need know drawing grid.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"a-simple-geom","dir":"Articles","previous_headings":"Creating a new geom","what":"A simple geom","title":"Extending ggplot2","text":"’s easiest start simple example. code simplified version geom_point(): similar defining new stat. always need provide fields/methods four pieces shown : required_aes character vector lists aesthetics user must provide. default_aes lists aesthetics default values. draw_key provides function used draw key legend. can see list build key functions ?draw_key draw_panel() magic happens. function takes three arguments returns grid grob. called panel. ’s complicated part described detail . draw_panel() three arguments: data: data frame one column aesthetic. panel_params: list per-panel parameters generated coord. consider opaque data structure: don’t look inside , just pass along coord methods. coord: object describing coordinate system. need use panel_params coord together transform data coords <- coord$transform(data, panel_params). creates data frame position variables scaled range 0–1. take data call grid grob function. (Transforming non-Cartesian coordinate systems quite complex - ’re best transforming data form accepted existing ggplot2 geom passing .)","code":"GeomSimplePoint <- ggproto(\"GeomSimplePoint\", Geom, required_aes = c(\"x\", \"y\"), default_aes = aes(shape = 19, colour = \"black\"), draw_key = draw_key_point, draw_panel = function(data, panel_params, coord) { coords <- coord$transform(data, panel_params) grid::pointsGrob( coords$x, coords$y, pch = coords$shape, gp = grid::gpar(col = coords$colour) ) } ) geom_simple_point <- function(mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( geom = GeomSimplePoint, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_simple_point()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"collective-geoms","dir":"Articles","previous_headings":"Creating a new geom","what":"Collective geoms","title":"Extending ggplot2","text":"Overriding draw_panel() appropriate one graphic element per row. cases, want graphic element per group. example, take polygons: row gives one vertex polygon. case, instead override draw_group(). following code makes simplified version GeomPolygon: things note : override draw_group() instead draw_panel() want one polygon per group, one polygon per row. data contains two fewer points, ’s point trying draw polygon, return nullGrob(). graphical equivalent NULL: ’s grob doesn’t draw anything doesn’t take space. Note units: x y always drawn “native” units. (default units pointGrob() native, didn’t need change ). lwd measured points, ggplot2 uses mm, need multiply adjustment factor .pt. might want compare real GeomPolygon. ’ll see overrides draw_panel() uses tricks make polygonGrob() produce multiple polygons one call. considerably complicated, gives better performance.","code":"GeomSimplePolygon <- ggproto(\"GeomPolygon\", Geom, required_aes = c(\"x\", \"y\"), default_aes = aes( colour = NA, fill = \"grey20\", linewidth = 0.5, linetype = 1, alpha = 1 ), draw_key = draw_key_polygon, draw_group = function(data, panel_params, coord) { n <- nrow(data) if (n <= 2) return(grid::nullGrob()) coords <- coord$transform(data, panel_params) # A polygon can only have a single colour, fill, etc, so take from first row first_row <- coords[1, , drop = FALSE] grid::polygonGrob( coords$x, coords$y, default.units = \"native\", gp = grid::gpar( col = first_row$colour, fill = scales::alpha(first_row$fill, first_row$alpha), lwd = first_row$linewidth * .pt, lty = first_row$linetype ) ) } ) geom_simple_polygon <- function(mapping = NULL, data = NULL, stat = \"chull\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( geom = GeomSimplePolygon, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_simple_polygon(aes(colour = class), fill = NA)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"inheriting-from-an-existing-geom","dir":"Articles","previous_headings":"Creating a new geom","what":"Inheriting from an existing Geom","title":"Extending ggplot2","text":"Sometimes just want make small modification existing geom. case, rather inheriting Geom can inherit existing subclass. example, might want change defaults GeomPolygon work better StatChull: doesn’t allow use different geoms stat, seems appropriate since convex hull primarily polygonal feature.","code":"GeomPolygonHollow <- ggproto(\"GeomPolygonHollow\", GeomPolygon, default_aes = aes(colour = \"black\", fill = NA, linewidth = 0.5, linetype = 1, alpha = NA) ) geom_chull <- function(mapping = NULL, data = NULL, position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatChull, geom = GeomPolygonHollow, data = data, mapping = mapping, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_chull()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises-1","dir":"Articles","previous_headings":"Creating a new geom","what":"Exercises","title":"Extending ggplot2","text":"Compare contrast GeomPoint GeomSimplePoint. Compare contrast GeomPolygon GeomSimplePolygon.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"geoms-and-stats-with-multiple-orientation","dir":"Articles","previous_headings":"","what":"Geoms and Stats with multiple orientation","title":"Extending ggplot2","text":"layers specific orientation. geom_bar() e.g. bars along one axis, geom_line() sort input one axis, etc. original approach using geoms orientation add coord_flip() plot switch position x y axes. Following ggplot2 v3.3 geoms natively work orientations without coord_flip(). mechanism layer try guess orientation mapped data, take direction user using orientation parameter. replicate functionality new stats geoms ’s steps take. look boxplot layer example instead creating new one scratch.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"omnidirectional-stats","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Omnidirectional stats","title":"Extending ggplot2","text":"actual guessing orientation happen setup_params() using has_flipped_aes() helper: Following call flip_data() make sure data horizontal orientation. rest code can simply assume data specific orientation. thing happens setup_data(): data flipped (needed), manipulated, flipped back returned. computation, sandwiching flip_data() used well, right data returned also get flipped_aes column denoting data flipped . allows stat communicate geom orientation already determined.","code":"StatBoxplot$setup_params #> #> #> function (...) #> setup_params(..., self = self) #> #> #> function (self, data, params) #> { #> params$flipped_aes <- has_flipped_aes(data, params, main_is_orthogonal = TRUE, #> group_has_equal = TRUE, main_is_optional = TRUE) #> data <- flip_data(data, params$flipped_aes) #> has_x <- !(is.null(data$x) && is.null(params$x)) #> has_y <- !(is.null(data$y) && is.null(params$y)) #> if (!has_x && !has_y) { #> cli::cli_abort(\"{.fn {snake_class(self)}} requires an {.field x} or {.field y} aesthetic.\") #> } #> params$width <- params$width %||% (resolution(data$x %||% #> 0, discrete = TRUE) * 0.75) #> if (!is_mapped_discrete(data$x) && is.double(data$x) && !has_groups(data) && #> any(data$x != data$x[1L])) { #> cli::cli_warn(c(\"Continuous {.field {flipped_names(params$flipped_aes)$x}} aesthetic\", #> i = \"did you forget {.code aes(group = ...)}?\")) #> } #> params #> } StatBoxplot$setup_data #> #> #> function (...) #> setup_data(..., self = self) #> #> #> function (self, data, params) #> { #> data <- flip_data(data, params$flipped_aes) #> data$x <- data$x %||% 0 #> data <- remove_missing(data, na.rm = params$na.rm, vars = \"x\", #> name = \"stat_boxplot\") #> flip_data(data, params$flipped_aes) #> }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"omnidirecitonal-geoms","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Omnidirecitonal geoms","title":"Extending ggplot2","text":"setup geoms pretty much , twists. has_flipped_aes() also used setup_params(), usually picked flipped_aes column given stat. setup_data() often see flipped_aes reassigned, make sure exist prior position adjustment. needed geom used together stat doesn’t handle orientation (often stat_identity()): draw_*() method sandwich data manipulation flip_data() calls. important make sure data flipped back prior creating grob calling draw methods geoms.","code":"GeomBoxplot$setup_data #> #> #> function (...) #> setup_data(...) #> #> #> function (data, params) #> { #> data$flipped_aes <- params$flipped_aes #> data <- flip_data(data, params$flipped_aes) #> data$width <- data$width %||% params$width %||% (resolution(data$x, #> FALSE, TRUE) * 0.9) #> if (isFALSE(params$outliers)) { #> data$outliers <- NULL #> } #> if (!is.null(data$outliers)) { #> suppressWarnings({ #> out_min <- vapply(data$outliers, min, numeric(1)) #> out_max <- vapply(data$outliers, max, numeric(1)) #> }) #> data$ymin_final <- pmin(out_min, data$ymin) #> data$ymax_final <- pmax(out_max, data$ymax) #> } #> if (is.null(params) || is.null(params$varwidth) || !params$varwidth || #> is.null(data$relvarwidth)) { #> data$xmin <- data$x - data$width/2 #> data$xmax <- data$x + data$width/2 #> } #> else { #> data$relvarwidth <- data$relvarwidth/max(data$relvarwidth) #> data$xmin <- data$x - data$relvarwidth * data$width/2 #> data$xmax <- data$x + data$relvarwidth * data$width/2 #> } #> data$width <- NULL #> if (!is.null(data$relvarwidth)) #> data$relvarwidth <- NULL #> flip_data(data, params$flipped_aes) #> }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"dealing-with-required-aesthetics","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Dealing with required aesthetics","title":"Extending ggplot2","text":"Omnidirectional layers usually two different sets required aesthetics. set used often knows orientation. handle gracefully required_aes field Stat Geom classes understands | () operator. Looking GeomBoxplot can see used: tells ggplot2 either aesthetics | required aesthetics required.","code":"GeomBoxplot$required_aes #> [1] \"x|y\" \"lower|xlower\" \"upper|xupper\" \"middle|xmiddle\" #> [5] \"ymin|xmin\" \"ymax|xmax\""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"ambiguous-layers","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Ambiguous layers","title":"Extending ggplot2","text":"layers clear interpretation data terms orientation. classic example geom_line() just convention runs along x-axis. nothing data indicates . geoms user must indicate flipped orientation setting orientation = \"y\". stat geom call has_flipped_aes() ambiguous = TRUE cancel guessing based data format. example can see setup_params() method GeomLine:","code":"GeomLine$setup_params #> #> #> function (...) #> setup_params(...) #> #> #> function (data, params) #> { #> params$flipped_aes <- has_flipped_aes(data, params, ambiguous = TRUE) #> params #> }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-your-own-theme","dir":"Articles","previous_headings":"","what":"Creating your own theme","title":"Extending ggplot2","text":"’re going create complete theme, things need know: Overriding existing elements, rather modifying four global elements affect (almost) every theme element Complete vs. incomplete elements","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"overriding-elements","dir":"Articles","previous_headings":"Creating your own theme","what":"Overriding elements","title":"Extending ggplot2","text":"default, add new theme element, inherits values existing theme. example, following code sets key colour red, inherits existing fill colour: override completely, use %+replace% instead +:","code":"theme_grey()$legend.key #> NULL new_theme <- theme_grey() + theme(legend.key = element_rect(colour = \"red\")) new_theme$legend.key #> List of 5 #> $ fill : NULL #> $ colour : chr \"red\" #> $ linewidth : NULL #> $ linetype : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\" new_theme <- theme_grey() %+replace% theme(legend.key = element_rect(colour = \"red\")) new_theme$legend.key #> List of 5 #> $ fill : NULL #> $ colour : chr \"red\" #> $ linewidth : NULL #> $ linetype : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"global-elements","dir":"Articles","previous_headings":"Creating your own theme","what":"Global elements","title":"Extending ggplot2","text":"four elements affect global appearance plot: set default properties inherited specific settings. useful setting overall “background” colour overall font settings (e.g. family size). generally start creating theme modifying values.","code":"df <- data.frame(x = 1:3, y = 1:3) base <- ggplot(df, aes(x, y)) + geom_point() + theme_minimal() base base + theme(text = element_text(colour = \"red\"))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"complete-vs-incomplete","dir":"Articles","previous_headings":"Creating your own theme","what":"Complete vs incomplete","title":"Extending ggplot2","text":"useful understand difference complete incomplete theme objects. complete theme object one produced calling theme function attribute complete = TRUE. Theme functions theme_grey() theme_bw() examples complete theme functions. Calls theme() produce incomplete theme objects, since represent (local) modifications theme object rather returning complete theme object per se. adding incomplete theme complete one, result complete theme. Complete incomplete themes behave somewhat differently added ggplot object: Adding incomplete theme augments current theme object, replacing properties elements defined call theme(). Adding complete theme wipes away existing theme applies new theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-a-new-faceting","dir":"Articles","previous_headings":"","what":"Creating a new faceting","title":"Extending ggplot2","text":"One daunting exercises ggplot2 extensions create new faceting system. reason creating new facetings take responsibility (almost) everything drawn screen, many experience directly using gtable grid upon ggplot2 rendering built. decide venture faceting extensions, highly recommended gain proficiency -mentioned packages. Facet class ggplot2 powerful takes responsibility wide range tasks. main tasks Facet object : Define layout; , partitioning data different plot areas (panels) well panels share position scales. Map plot data correct panels, potentially duplicating data exist multiple panels (e.g. margins facet_grid()). Assemble panels final gtable, adding axes, strips decorations process. Apart three tasks, functionality must implemented, couple additional extension points sensible defaults provided. can generally ignored, adventurous developers can override even control: Initialization training positional scales panel. Decoration front behind panel. Drawing axis labels show new faceting class created start simple go required methods turn build facet_duplicate() simply duplicate plot two panels. tinker bit show powerful possibilities.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-a-layout-specification","dir":"Articles","previous_headings":"Creating a new faceting","what":"Creating a layout specification","title":"Extending ggplot2","text":"layout context facets data.frame defines mapping data panels reside well positional scales used. output least contain columns PANEL, SCALE_X, SCALE_Y, often contain help assign data correct panel (facet_grid() e.g. also return faceting variables associated panel). Let’s make function defines duplicate layout: quite simple faceting just define two panels irrespectively input data parameters.","code":"layout <- function(data, params) { data.frame(PANEL = c(1L, 2L), SCALE_X = 1L, SCALE_Y = 1L) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"mapping-data-into-panels","dir":"Articles","previous_headings":"Creating a new faceting","what":"Mapping data into panels","title":"Extending ggplot2","text":"order ggplot2 know data go needs data assigned panel. purpose mapping step assign PANEL column layer data identifying panel belongs . first investigate whether gotten empty data.frame duplicate data assign original data first panel new data second panel.","code":"mapping <- function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } rbind( cbind(data, PANEL = 1L), cbind(data, PANEL = 2L) ) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"laying-out-the-panels","dir":"Articles","previous_headings":"Creating a new faceting","what":"Laying out the panels","title":"Extending ggplot2","text":"two functions deceivingly simple, last one going take work. goal draw two panels beside () axes etc.","code":"render <- function(panels, layout, x_scales, y_scales, ranges, coord, data, theme, params) { # Place panels according to settings if (params$horizontal) { # Put panels in matrix and convert to a gtable panels <- matrix(panels, ncol = 2) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(c(1, 1), \"null\"), heights = unit(1, \"null\"), clip = \"on\") # Add spacing according to theme panel_spacing <- calc_element(\"panel.spacing.x\", theme) panel_table <- gtable::gtable_add_col_space(panel_table, panel_spacing) } else { panels <- matrix(panels, ncol = 1) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(1, \"null\"), heights = unit(c(1, 1), \"null\"), clip = \"on\") panel_spacing <- if (is.null(theme$panel.spacing.y)) { theme$panel.spacing } else { theme$panel.spacing.y } panel_table <- gtable::gtable_add_row_space(panel_table, panel_spacing) } # Name panel grobs so they can be found later panel_table$layout$name <- paste0(\"panel-\", c(1, 2)) # Construct the axes axes <- render_axes(ranges[1], ranges[1], coord, theme, transpose = TRUE) # Add axes around each panel panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_width_l <- unit(grid::convertWidth( grid::grobWidth(axes$y$left[[1]]), \"cm\", TRUE), \"cm\") axis_width_r <- unit(grid::convertWidth( grid::grobWidth(axes$y$right[[1]]), \"cm\", TRUE), \"cm\") ## We do it reverse so we don't change the position of panels when we add axes for (i in rev(panel_pos_h)) { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r, i) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$y$right, length(panel_pos_v)), t = panel_pos_v, l = i + 1, clip = \"off\") panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l, i - 1) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$y$left, length(panel_pos_v)), t = panel_pos_v, l = i, clip = \"off\") } ## Recalculate as gtable has changed panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_height_t <- unit(grid::convertHeight( grid::grobHeight(axes$x$top[[1]]), \"cm\", TRUE), \"cm\") axis_height_b <- unit(grid::convertHeight( grid::grobHeight(axes$x$bottom[[1]]), \"cm\", TRUE), \"cm\") for (i in rev(panel_pos_v)) { panel_table <- gtable::gtable_add_rows(panel_table, axis_height_b, i) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$bottom, length(panel_pos_h)), t = i + 1, l = panel_pos_h, clip = \"off\") panel_table <- gtable::gtable_add_rows(panel_table, axis_height_t, i - 1) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$top, length(panel_pos_h)), t = i, l = panel_pos_h, clip = \"off\") } panel_table }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"assembling-the-facet-class","dir":"Articles","previous_headings":"Creating a new faceting","what":"Assembling the Facet class","title":"Extending ggplot2","text":"Usually methods defined within class definition way done Geom Stat. split go turn. remains assign functions correct methods well making constructor Now everything assembled, lets test :","code":"# Constructor: shrink is required to govern whether scales are trained on # Stat-transformed data or not. facet_duplicate <- function(horizontal = TRUE, shrink = TRUE) { ggproto(NULL, FacetDuplicate, shrink = shrink, params = list( horizontal = horizontal ) ) } FacetDuplicate <- ggproto(\"FacetDuplicate\", Facet, compute_layout = layout, map_data = mapping, draw_panels = render ) p <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() p p + facet_duplicate()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"doing-more-with-facets","dir":"Articles","previous_headings":"Creating a new faceting","what":"Doing more with facets","title":"Extending ggplot2","text":"example pretty useless ’ll now try expand add actual usability. going make faceting adds panels y-transformed axes: apparent, draw_panel method can become unwieldy begins take multiple possibilities account. fact want support horizontal vertical layout leads lot /else blocks code. general, big challenge writing facet extensions prepared meticulous writing methods. Enough talk - lets see new powerful faceting extension works:","code":"library(scales) facet_trans <- function(trans, horizontal = TRUE, shrink = TRUE) { ggproto(NULL, FacetTrans, shrink = shrink, params = list( trans = scales::as.transform(trans), horizontal = horizontal ) ) } FacetTrans <- ggproto(\"FacetTrans\", Facet, # Almost as before but we want different y-scales for each panel compute_layout = function(data, params) { data.frame(PANEL = c(1L, 2L), SCALE_X = 1L, SCALE_Y = c(1L, 2L)) }, # Same as before map_data = function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } rbind( cbind(data, PANEL = 1L), cbind(data, PANEL = 2L) ) }, # This is new. We create a new scale with the defined transformation init_scales = function(layout, x_scale = NULL, y_scale = NULL, params) { scales <- list() if (!is.null(x_scale)) { scales$x <- lapply(seq_len(max(layout$SCALE_X)), function(i) x_scale$clone()) } if (!is.null(y_scale)) { y_scale_orig <- y_scale$clone() y_scale_new <- y_scale$clone() y_scale_new$trans <- params$trans # Make sure that oob values are kept y_scale_new$oob <- function(x, ...) x scales$y <- list(y_scale_orig, y_scale_new) } scales }, # We must make sure that the second scale is trained on transformed data train_scales = function(x_scales, y_scales, layout, data, params) { # Transform data for second panel prior to scale training if (!is.null(y_scales)) { data <- lapply(data, function(layer_data) { match_id <- match(layer_data$PANEL, layout$PANEL) y_vars <- intersect(y_scales[[1]]$aesthetics, names(layer_data)) trans_scale <- layer_data$PANEL == 2L for (i in y_vars) { layer_data[trans_scale, i] <- y_scales[[2]]$transform(layer_data[trans_scale, i]) } layer_data }) } Facet$train_scales(x_scales, y_scales, layout, data, params) }, # this is where we actually modify the data. It cannot be done in $map_data as that function # doesn't have access to the scales finish_data = function(data, layout, x_scales, y_scales, params) { match_id <- match(data$PANEL, layout$PANEL) y_vars <- intersect(y_scales[[1]]$aesthetics, names(data)) trans_scale <- data$PANEL == 2L for (i in y_vars) { data[trans_scale, i] <- y_scales[[2]]$transform(data[trans_scale, i]) } data }, # A few changes from before to accommodate that axes are now not duplicate of each other # We also add a panel strip to annotate the different panels draw_panels = function(panels, layout, x_scales, y_scales, ranges, coord, data, theme, params) { # Place panels according to settings if (params$horizontal) { # Put panels in matrix and convert to a gtable panels <- matrix(panels, ncol = 2) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(c(1, 1), \"null\"), heights = unit(1, \"null\"), clip = \"on\") # Add spacing according to theme panel_spacing <- calc_element(\"panel.spacing.x\", theme) panel_table <- gtable::gtable_add_col_space(panel_table, panel_spacing) } else { panels <- matrix(panels, ncol = 1) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(1, \"null\"), heights = unit(c(1, 1), \"null\"), clip = \"on\") panel_spacing <- calc_element(\"panel.spacing.y\", theme) panel_table <- gtable::gtable_add_row_space(panel_table, panel_spacing) } # Name panel grobs so they can be found later panel_table$layout$name <- paste0(\"panel-\", c(1, 2)) # Construct the axes axes <- render_axes(ranges[1], ranges, coord, theme, transpose = TRUE) # Add axes around each panel grobWidths <- function(x) { unit(vapply(x, function(x) { grid::convertWidth( grid::grobWidth(x), \"cm\", TRUE) }, numeric(1)), \"cm\") } panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_width_l <- grobWidths(axes$y$left) axis_width_r <- grobWidths(axes$y$right) ## We do it reverse so we don't change the position of panels when we add axes if (params$horizontal) { for (i in rev(seq_along(panel_pos_h))) { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[i], panel_pos_h[i]) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$right[i], t = panel_pos_v, l = panel_pos_h[i] + 1, clip = \"off\") panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[i], panel_pos_h[i] - 1) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$left[i], t = panel_pos_v, l = panel_pos_h[i], clip = \"off\") } } else { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[1], panel_pos_h) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$right, t = panel_pos_v, l = panel_pos_h + 1, clip = \"off\") panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[1], panel_pos_h - 1) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$left, t = panel_pos_v, l = panel_pos_h, clip = \"off\") } ## Recalculate as gtable has changed panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_height_t <- unit(grid::convertHeight( grid::grobHeight(axes$x$top[[1]]), \"cm\", TRUE), \"cm\") axis_height_b <- unit(grid::convertHeight( grid::grobHeight(axes$x$bottom[[1]]), \"cm\", TRUE), \"cm\") for (i in rev(panel_pos_v)) { panel_table <- gtable::gtable_add_rows(panel_table, axis_height_b, i) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$bottom, length(panel_pos_h)), t = i + 1, l = panel_pos_h, clip = \"off\") panel_table <- gtable::gtable_add_rows(panel_table, axis_height_t, i - 1) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$top, length(panel_pos_h)), t = i, l = panel_pos_h, clip = \"off\") } # Add strips strips <- render_strips( x = data.frame(name = c(\"Original\", paste0(\"Transformed (\", params$trans$name, \")\"))), labeller = label_value, theme = theme) panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t strip_height <- unit(grid::convertHeight( grid::grobHeight(strips$x$top[[1]]), \"cm\", TRUE), \"cm\") for (i in rev(seq_along(panel_pos_v))) { panel_table <- gtable::gtable_add_rows(panel_table, strip_height, panel_pos_v[i] - 1) if (params$horizontal) { panel_table <- gtable::gtable_add_grob(panel_table, strips$x$top, t = panel_pos_v[i], l = panel_pos_h, clip = \"off\") } else { panel_table <- gtable::gtable_add_grob(panel_table, strips$x$top[i], t = panel_pos_v[i], l = panel_pos_h, clip = \"off\") } } panel_table } ) ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_trans('sqrt')"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"extending-existing-facet-function","dir":"Articles","previous_headings":"","what":"Extending existing facet function","title":"Extending ggplot2","text":"rendering part facet class often difficult development step, possible piggyback existing faceting classes achieve range new facetings. subclass facet_wrap() make facet_bootstrap() class splits input data number panels random. intercept compute_layout map_data methods instead dividing data variable randomly assigns rows panel based sampling parameters (n determines number panels, prop determines proportion data panel). important layout returned compute_layout valid layout FacetWrap counting draw_panel method FacetWrap work us. Thus want subclass FacetWrap FacetGrid, make sure understand nature layout specification.","code":"facet_bootstrap <- function(n = 9, prop = 0.2, nrow = NULL, ncol = NULL, scales = \"fixed\", shrink = TRUE, strip.position = \"top\") { facet <- facet_wrap(~.bootstrap, nrow = nrow, ncol = ncol, scales = scales, shrink = shrink, strip.position = strip.position) facet$params$n <- n facet$params$prop <- prop ggproto(NULL, FacetBootstrap, shrink = shrink, params = facet$params ) } FacetBootstrap <- ggproto(\"FacetBootstrap\", FacetWrap, compute_layout = function(data, params) { id <- seq_len(params$n) dims <- wrap_dims(params$n, params$nrow, params$ncol) layout <- data.frame(PANEL = factor(id)) layout$ROW <- as.integer((id - 1L) %/% dims[2] + 1L) layout$COL <- as.integer((id - 1L) %% dims[2] + 1L) layout <- layout[order(layout$PANEL), , drop = FALSE] rownames(layout) <- NULL # Add scale identification layout$SCALE_X <- if (params$free$x) id else 1L layout$SCALE_Y <- if (params$free$y) id else 1L cbind(layout, .bootstrap = id) }, map_data = function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } n_samples <- round(nrow(data) * params$prop) new_data <- lapply(seq_len(params$n), function(i) { cbind(data[sample(nrow(data), n_samples), , drop = FALSE], PANEL = i) }) do.call(rbind, new_data) } ) ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 0.1) + facet_bootstrap(n = 9, prop = 0.05)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises-2","dir":"Articles","previous_headings":"Extending existing facet function","what":"Exercises","title":"Extending ggplot2","text":"Rewrite FacetTrans take vector transformations create additional panel transformation. Based FacetWrap implementation rewrite FacetTrans take strip.placement theme setting account. Think caveats FacetBootstrap specifically related adding multiple layers data.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-new-guides","dir":"Articles","previous_headings":"","what":"Creating new guides","title":"Extending ggplot2","text":"Guides closely related scales aesthetics, important part guides taking information scale translating graphic. information passed around inside guides key dataframe. existing guides, can glance key contains using get_guide_data() function. Typical variables may see guides aesthetic mapped scale, hexadecimal colours example , aesthetic represent .value column labelled .label column. Sometimes, aesthetic used computations. avoid interpreting values labels aesthetics, customary prefix ..","code":"p <- ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + scale_colour_discrete( labels = c(\"4-wheel drive\", \"front wheel drive\", \"rear wheel drive\") ) get_guide_data(p, \"colour\") #> colour .value .label #> 1 #F8766D 4 4-wheel drive #> 2 #00BA38 f front wheel drive #> 3 #619CFF r rear wheel drive"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"overriding-scale-extraction","dir":"Articles","previous_headings":"Creating new guides","what":"Overriding scale extraction","title":"Extending ggplot2","text":"Let’s now make first guide extension adjusting guide’s key. Axes straightforward extend, least complicated. ’ll build axis accepts custom values guide’s key. can begin making custom ggproto class inherits axis guide. important extension point extract_key() method, determines break information transferred scale guide. class, reject scale’s reality substitute .","code":"GuideKey <- ggproto( \"Guide\", GuideAxis, # Some parameters are required, so it is easiest to copy the base Guide's # parameters into our new parameters. # We add a new 'key' parameter for our own guide. params = c(GuideAxis$params, list(key = NULL)), # It is important for guides to have a mapped aesthetic with the correct name extract_key = function(scale, aesthetic, key, ...) { key$aesthetic <- scale$map(key$aesthetic) names(key)[names(key) == \"aesthetic\"] <- aesthetic key } )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"guide-constructors","dir":"Articles","previous_headings":"Creating new guides","what":"Guide constructors","title":"Extending ggplot2","text":"Now can make guide constructor creates custom key pass along . new_guide() function instantiates new guide given parameters. function automatically rejects parameters class’ params field, important declare . new guide can now used inside guides() function guide argument position scale.","code":"guide_key <- function( aesthetic, value = aesthetic, label = as.character(aesthetic), ..., # Standard guide arguments theme = NULL, title = waiver(), order = 0, position = waiver() ) { key <- data.frame(aesthetic, .value = value, .label = label, ...) new_guide( # Arguments passed on to the GuideKey$params field key = key, theme = theme, title = title, order = order, position = position, # Declare which aesthetics are supported available_aes = c(\"x\", \"y\"), # Set the guide class super = GuideKey ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + scale_x_continuous( guide = guide_key(aesthetic = 2:6 + 0.5) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"custom-drawings","dir":"Articles","previous_headings":"Creating new guides","what":"Custom drawings","title":"Extending ggplot2","text":"feeling adventurous, can also alter way guides drawn. majority drawing code Guide$build_*() methods, orchestrated Guide$draw() method. derived guides, custom key guide ’re extending , overriding Guide$build_*() method sufficient. writing completely novel guide resemble structure existing guide, overriding Guide$draw() method might wise. example, changing way labels drawn, edit Guide$build_labels() method. ’ll edit method labels drawn colour set key. addition key params variable ’ve seen , now also elements variable, list precomputed theme elements. can use elements$text element draw graphical object (grob) style axis text. Perhaps finicky thing drawing guides lot settings depend guide’s position parameter. incorporating ... argument guide_key() key, adding colour column key straightforward. can check guide looks correct different positions around panel.","code":"# Same as before GuideKey <- ggproto( \"Guide\", GuideAxis, params = c(GuideAxis$params, list(key = NULL)), extract_key = function(scale, aesthetic, key, ...) { key$aesthetic <- scale$map(key$aesthetic) names(key)[names(key) == \"aesthetic\"] <- aesthetic key }, # New method to draw labels build_labels = function(key, elements, params) { position <- params$position # Downstream code expects a list of labels list(element_grob( elements$text, label = key$.label, x = switch(position, left = 1, right = 0, key$x), y = switch(position, top = 0, bottom = 1, key$y), margin_x = position %in% c(\"left\", \"right\"), margin_y = position %in% c(\"top\", \"bottom\"), colour = key$colour )) } ) ggplot(mpg, aes(displ, hwy)) + geom_point() + guides( x = guide_key( aesthetic = 2:6 + 0.5, colour = c(\"red\", \"grey\", \"red\", \"grey\", \"red\") ), x.sec = guide_key( aesthetic = c(2, 4, 6), colour = c(\"tomato\", \"limegreen\", \"dodgerblue\") ) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises-3","dir":"Articles","previous_headings":"Creating new guides","what":"Exercises","title":"Extending ggplot2","text":"Extend guide_key() also pass family, face size aesthetics key labels. Override GuideKey$build_ticks() method also pass colour linewidth settings tick marks. Looking Guide$build_ticks() good starting point. Compare GuideKey$extract_key() Guide$extract_key(). steps skimmed example?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"why-is-annotation-created-with-geom_text-pixellated-how-can-i-make-it-more-crisp","dir":"Articles","previous_headings":"","what":"Why is annotation created with geom_text() pixellated? How can I make it more crisp?","title":"FAQ: Annotation","text":"use annotate(geom = \"text\") instead geom_text() annotation. following visualisation annotated histogram red line red text mark mean. Note line text appears pixellated/fuzzy. geom_text() draws geom per row data frame, plotting top . annotation (opposed plotting data using text geometric objects represent observation) use annotate() instead.","code":"mean_hwy <- round(mean(mpg$hwy), 2) ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 2) + geom_segment( x = mean_hwy, xend = mean_hwy, y = 0, yend = 35, color = \"red\" ) + geom_text( x = mean_hwy, y = 40, label = paste(\"mean\\n\", mean_hwy), color = \"red\" ) ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 2) + annotate(\"segment\", x = mean_hwy, xend = mean_hwy, y = 0, yend = 35, color = \"red\" ) + annotate(\"text\", x = mean_hwy, y = 40, label = paste(\"mean =\", mean_hwy), color = \"red\" )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-make-sure-all-annotation-created-with-geom_text-fits-in-the-bounds-of-the-plot","dir":"Articles","previous_headings":"","what":"How can I make sure all annotation created with geom_text() fits in the bounds of the plot?","title":"FAQ: Annotation","text":"Set vjust = \"inward\" hjust = \"inward\" geom_text(). Suppose following data frame visualization. labels edges plot cut slightly. manually extend axis limits avoid , straightforward approach set vjust = \"inward\" hjust = \"inward\" geom_text().","code":"df <- tibble::tribble( ~x, ~y, ~name, 2, 2, \"two\", 3, 3, \"three\", 4, 4, \"four\" ) ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 10) ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 10, vjust = \"inward\", hjust = \"inward\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-annotate-my-bar-plot-to-display-counts-for-each-bar","dir":"Articles","previous_headings":"","what":"How can I annotate my bar plot to display counts for each bar?","title":"FAQ: Annotation","text":"Either calculate counts ahead time place bars using geom_text() let ggplot() calculate add plot using stat_count() geom = \"text\". Suppose following bar plot want add number cars fall drv level respective bars. One option calculate counts dplyr::count() pass label mapping geom_text(). Note expanded y axis limit get numbers fit plot. Another option let ggplot() counting , access counts after_stat(count) mapped labels placed plot stat_count().","code":"ggplot(mpg, aes(x = drv)) + geom_bar() mpg %>% dplyr::count(drv) %>% ggplot(aes(x = drv, y = n)) + geom_col() + geom_text(aes(label = n), vjust = -0.5) + coord_cartesian(ylim = c(0, 110)) ggplot(mpg, aes(x = drv)) + geom_bar() + stat_count(geom = \"text\", aes(label = ..count..), vjust = -0.5) + coord_cartesian(ylim = c(0, 110)) #> Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0. #> ℹ Please use `after_stat(count)` instead. #> This warning is displayed once every 8 hours. #> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was #> generated."},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-annotate-my-stacked-bar-plot-to-display-counts-for-each-segment","dir":"Articles","previous_headings":"","what":"How can I annotate my stacked bar plot to display counts for each segment?","title":"FAQ: Annotation","text":"First calculate counts segment (e.g. dplyr::count()) place bars geom_text() using position_stack(vjust = 0.5) position argument place values middle segments. Suppose following stacked bar plot. can first calculate counts segment dplyr::count(), place values column called n. can pass result directly ggplot(), draw segments appropriate heights y = n aesthetic mapping geom_col() draw bars, finally place counts plot geom_text().","code":"ggplot(mpg, aes(x = class, fill = drv)) + geom_bar() mpg %>% count(class, drv) #> # A tibble: 12 × 3 #> class drv n #> #> 1 2seater r 5 #> 2 compact 4 12 #> 3 compact f 35 #> 4 midsize 4 3 #> 5 midsize f 38 #> 6 minivan f 11 #> 7 pickup 4 33 #> 8 subcompact 4 4 #> 9 subcompact f 22 #> 10 subcompact r 9 #> 11 suv 4 51 #> 12 suv r 11 mpg %>% count(class, drv) %>% ggplot(aes(x = class, fill = drv, y = n)) + geom_col() + geom_text(aes(label = n), size = 3, position = position_stack(vjust = 0.5))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-display-proportions-relative-frequencies-instead-of-counts-on-a-bar-plot","dir":"Articles","previous_headings":"","what":"How can I display proportions (relative frequencies) instead of counts on a bar plot?","title":"FAQ: Annotation","text":"Either calculate proportions ahead time place bars using geom_text() let ggplot() calculate add plot using stat_coun() geom = \"text\". Suppose following bar plot want display proportion cars fall drv level, instead count. One option calculate proportions dplyr::count() use geom_col() draw bars Another option let ggplot() calculation proportions , access counts ..prop... Note also need group = 1 mapping option.","code":"ggplot(mpg, aes(x = drv)) + geom_bar() mpg %>% dplyr::count(drv) %>% mutate(prop = n / sum(n)) %>% ggplot(aes(x = drv, y = prop)) + geom_col() ggplot(mpg, aes(x = drv, y = ..prop.., group = 1)) + geom_bar()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-rotate-the-axis-tick-labels-in-ggplot2-so-that-tick-labels-that-are-long-character-strings-dont-overlap","dir":"Articles","previous_headings":"Label placement","what":"How can I rotate the axis tick labels in ggplot2 so that tick labels that are long character strings don’t overlap?","title":"FAQ: Axes","text":"Set angle text axis.text.x axis.text.y components theme(), e.g. theme(axis.text.x = element_text(angle = 90)). following plot labels x-axis overlapping. Rotate axis labels: can components theme(), specifically axis.text.x component. Applying vertical horizontal justification labels centers axis ticks. angle can set desired within 0 360 degree range, set 90 degrees. Flip axes: Use y-axis long labels. Dodge axis labels: Add scale_*() layer, e.g. scale_x_continuous(), scale_y_discrete(), etc., customise guide argument guide_axis() function. case want customise x-axis, variable x-axis discrete, ’ll use scale_x_continuous(). guide argument use guide_axis() specify many rows dodge labels n.dodge. likely trial--error exercise, depending lengths labels width plot. case ’ve settled 3 rows render labels. Omit overlapping labels: Alternatively, can set guide_axis(check.overlap = TRUE) omit axis labels overlap. ggplot2 prioritize first, last, middle labels. Note option might preferable axes representing variables inherent ordering obvious audience plot, ’s trivial guess missing labels . (case following plot.)","code":"ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) ggplot(msleep, aes(y = order, x = sleep_total)) + geom_boxplot() ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + scale_x_discrete(guide = guide_axis(n.dodge = 3)) ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + scale_x_discrete(guide = guide_axis(check.overlap = TRUE))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-remove-axis-labels-in-ggplot2","dir":"Articles","previous_headings":"Label placement","what":"How can I remove axis labels in ggplot2?","title":"FAQ: Axes","text":"Add theme() layer set relevant arguments, e.g. axis.title.x, axis.text.x, etc. element_blank(). Suppose want remove axis labels entirely. Remove x y axis labels: want modify just one axes, can modifying components theme(), setting elements want remove element_blank(). replace x y applying update y-axis. Note distinction axis.title axis.ticks – axis.title name variable axis.text text accompanying ticks. Remove axis labels: can use theme_void() remove theming elements. Note might remove features like. finer control theme, see .","code":"ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + theme( axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank() ) ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + theme_void()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-add-multi-row-axis-labels-with-a-grouping-variable","dir":"Articles","previous_headings":"Label placement","what":"How can I add multi-row axis labels with a grouping variable?","title":"FAQ: Axes","text":"can either using interaction() map interaction variable ’re plotting grouping variable x y aesthetic. Suppose following data sales quarter across two years. can create line plot data facet year group quarters year together. However might preferable plot points single plot indicate x-axis first Q1 Q4 2020 second 2021. achieve , map interaction() quarter year x aesthetic. achieves desired result line, however labeling x-axis busy difficult read. clean (1) clip plotting area coord_cartesian(), (2) remove axis labels add wider margin bottom plot theme(), (3) place axis labels indicating quarters underneath plot, (4) underneath labels, place annotation indicating years. Note x-coordinates year labels manually assigned , many years, might write logic calculate placement. approach works geoms well. example, might can create bar plot representing data using following. ’s undesirable bars flush edges plot, similar result can achieved leveraging faceting removing space facets create appearance single plot. However note space bars 2020 Q4 2021 Q1 greater space bars.","code":"library(tibble) sales <- tribble( ~value, ~quarter, ~year, 10, \"Q1\", 2020, 15, \"Q2\", 2020, 15, \"Q3\", 2020, 20, \"Q4\", 2020, 10, \"Q1\", 2021, 25, \"Q2\", 2021, 30, \"Q3\", 2021, 30, \"Q4\", 2021 ) ggplot(sales, aes(x = quarter, y = value, group = 1)) + geom_line() + facet_wrap(~year) ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + geom_line() ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + geom_line() + coord_cartesian(ylim = c(9, 32), expand = FALSE, clip = \"off\") + theme( plot.margin = margin(1, 1, 3, 1, \"lines\"), axis.title.x = element_blank(), axis.text.x = element_blank() ) + annotate(geom = \"text\", x = seq_len(nrow(sales)), y = 8, label = sales$quarter, size = 3) + annotate(geom = \"text\", x = c(2.5, 6.5), y = 6, label = unique(sales$year), size = 4) ggplot(sales, aes(x = interaction(quarter, year), y = value)) + geom_col() + coord_cartesian(ylim = c(0, 32), expand = FALSE, clip = \"off\") + annotate(geom = \"text\", x = seq_len(nrow(sales)), y = -1, label = sales$quarter, size = 3) + annotate(geom = \"text\", x = c(2.5, 6.5), y = -3, label = unique(sales$year), size = 4) + theme( plot.margin = margin(1, 1, 3, 1, \"lines\"), axis.title.x = element_blank(), axis.text.x = element_blank() ) ggplot(sales, aes(x = quarter, y = value)) + geom_col() + facet_wrap(~year, strip.position = \"bottom\") + theme( panel.spacing = unit(0, \"lines\"), strip.background = element_blank(), strip.placement = \"outside\" ) + labs(x = NULL)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-customize-the-text-shown-on-the-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I customize the text shown on the axis labels?","title":"FAQ: Axes","text":"Add scale_*() layer, e.g. scale_x_continuous(), scale_y_discrete(), etc., add custom labels labels argument. Suppose want give informative labels type drive train. Use labels argument appropriate scale_*() function. can find list functions . Type drive train (drv) discrete variable y-axis, ’ll adjust labels scale_y_discrete(). One option list labels order levels. Note start bottom go , just like variable numeric/continuous. Another approach use named list. approach makes relabelling explicit, also means don’t need worry order levels.","code":"ggplot(mpg, aes(y = drv)) + geom_bar() ggplot(mpg, aes(y = drv)) + geom_bar() + scale_y_discrete( labels = c(\"Four wheel drive\", \"Front wheel drive\", \"Rear wheel drive\") ) ggplot(mpg, aes(y = drv)) + geom_bar() + scale_y_discrete( labels = c( \"f\" = \"Front wheel drive\", \"r\" = \"Rear wheel drive\", \"4\" = \"Four wheel drive\" ) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-stop-r-from-using-scientific-notation-on-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I stop R from using scientific notation on axis labels?","title":"FAQ: Axes","text":"Use scales::label_number() force decimal display numbers. first need add scale_*() layer (e.g. scale_x_continuous(), scale_y_discrete(), etc.) customise labels argument within layer function. default, large numbers axis labels following plot shown scientific notation. scales package offers large number functions control formatting axis labels legend keys. Use scales::label_number() force decimal display numbers rather using scientific notation use scales::label_comma() insert comma every three digits.","code":"ggplot(txhousing, aes(x = median, y = volume)) + geom_point() #> Warning: Removed 617 rows containing missing values or values outside the scale #> range (`geom_point()`). library(scales) ggplot(txhousing, aes(x = median, y = volume)) + geom_point() + scale_x_continuous(labels = label_number()) + scale_y_continuous(labels = label_comma()) #> Warning: Removed 617 rows containing missing values or values outside the scale #> range (`geom_point()`)."},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-change-the-number-of-decimal-places-on-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I change the number of decimal places on axis labels?","title":"FAQ: Axes","text":"Set accuracy scales::label_number() desired level decimal places, e.g. 0.1 show 1 decimal place, 0.0001 show 4 decimal places, etc. first need add scale_*() layer (e.g. scale_x_continuous(), scale_y_discrete(), etc.) customise labels argument within layer function. Suppose want increase/decrease number decimal spaces shown axis text following plot. scales package offers large number functions control formatting axis labels legend keys. Use scales::label_number() accuracy argument indicates number round , e.g. 0.1 show 1 decimal place, 0.0001 show 4 decimal places, etc.","code":"ggplot(seals, aes(x = delta_long, y = delta_lat)) + geom_point() library(scales) ggplot(seals, aes(x = delta_long, y = delta_lat)) + geom_point() + scale_x_continuous(labels = label_number(accuracy = 0.1)) + scale_y_continuous(labels = label_number(accuracy = 0.0001))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-add-percentage-symbols-to-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I add percentage symbols (%) to axis labels?","title":"FAQ: Axes","text":"Use scales::label_percent(), place % number, default. can customise % placed using prefix suffix arguments, also scale numbers needed. first need add scale_*() layer (e.g. scale_x_continuous(), scale_y_discrete(), etc.) customise labels argument within layer function. variable y-axis following line plot (psavert) indicates personal savings rate, percentages. scales::label_percent() can add %s numbers shown axis make units clear. accuracy argument indicates number round , e.g. 0.1 show 1 decimal place, 0.0001 show 4 decimal places, etc.","code":"ggplot(economics, aes(x = date, y = psavert, group = 1)) + geom_line() ggplot(economics, aes(x = date, y = psavert, group = 1)) + geom_line() + scale_y_continuous(labels = scales::label_percent(scale = 1, accuracy = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-add-superscripts-and-subscripts-to-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I add superscripts and subscripts to axis labels?","title":"FAQ: Axes","text":"can either use bquote() parse mathematical expressions use ggtext package write expression using Markdown HTML syntax. following plot cty squared hwy log transformed. Use bquote() function parse mathematical expressions. ’re already familiar Markdown HTML, might prefer using ggtext package instead. Markdown can write axis labels cty2<\/sup> log10<\/sub>(hwy) x y axes, respectively. , tell ggplot2 interpret axis labels Markdown plain text setting axis.title.x axis.title.y ggtext::element_markdown().","code":"ggplot(mpg, aes(x = cty^2, y = log(hwy))) + geom_point() ggplot(mpg, aes(x = cty^2, y = log(hwy, base = 10))) + geom_point() + labs( x = bquote(cty^2), y = bquote(paste(log[10], \"(hwy)\")) ) ggplot(mpg, aes(x = cty^2, y = log(hwy, base = 10))) + geom_point() + labs( x = \"cty2<\/sup>\", y = \"log10<\/sub>(hwy)\" ) + theme( axis.title.x = ggtext::element_markdown(), axis.title.y = ggtext::element_markdown() )"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-increase-decrease-the-number-of-axis-ticks","dir":"Articles","previous_headings":"Custom breaks","what":"How can I increase / decrease the number of axis ticks?","title":"FAQ: Axes","text":"Customise breaks minor_breaks scale_x_continuous(), scale_y_continuous(), etc. Suppose want customise major minor grid lines x y axes following plot. can set breaks minor_breaks scale_x_continuous() scale_y_continuous() desired. example, x-axis major minor grid breaks defined sequence y-axis explicitly stated major breaks appear vector (value stated randomly selected illustrative purposes , don’t follow best practice) completely turned minor grid lines setting minor_breaks NULL.","code":"ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + scale_x_continuous( breaks = seq(9, 35, 3), minor_breaks = seq(8.5, 35.5, 1) ) + scale_y_continuous( breaks = c(12, 23, 36, 41), minor_breaks = NULL )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-control-the-number-of-major-and-minor-grid-lines-shown-on-the-plot","dir":"Articles","previous_headings":"Custom breaks","what":"How can I control the number of major and minor grid lines shown on the plot?","title":"FAQ: Axes","text":"Customise breaks minor_breaks scale_x_continuous(), scale_y_continuous()`, etc. See can increase / decrease number axis ticks? detail. Note question grid lines answered using breaks. ggplot2 place major grid lines break supplied breaks minor grid lines break supplied minor_breaks.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-remove-the-space-between-the-plot-and-the-axis","dir":"Articles","previous_headings":"Custom breaks","what":"How can I remove the space between the plot and the axis?","title":"FAQ: Axes","text":"Remove padding around data entirely using setting expand = c(0, 0) within scale_x_continuous(), scale_y_discrete(), etc. layers. Remove padding: Suppose want remove padding around heat map ’s flush axes. Since x y variables continuous, set expand = c(0, 0) scale_x_continuous() scale_y_continuous(). Remove padding: Suppose want remove padding bars x-axis . make adjustment scale_y_continuous() since padding vertical direction. However note removes padding bottom bars well top. default, ggplot2 expands scale 5% side continuous variables 0.6 units side discrete variables. keep default expansion top removing bottom, can use following. mult argument expansion() takes multiplicative range expansion factors. Given vector length 2, lower limit expanded mult[1] (case 0) upper limit expanded mult[2] (case 0.05).","code":"ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) ggplot(mpg, aes(drv)) + geom_bar() ggplot(mpg, aes(drv)) + geom_bar() + scale_y_continuous(expand = c(0, 0)) ggplot(mpg, aes(drv)) + geom_bar() + scale_y_continuous(expand = expansion(mult = c(0, 0.05)))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-change-the-color-of-the-bars-in-my-bar-plot","dir":"Articles","previous_headings":"Colors","what":"How can I change the color of the bars in my bar plot?","title":"FAQ: Barplots","text":"using color bars, define fill argument geom_bar() (geom_col()). assigning color based another variable, map variable fill aesthetic, needed, use one scale_fill_*() functions set colors. can set bars given color fill argument geom_bar(). Alternatively, colors based variable, happen aes() mapping. want customize colors, one option scale_fill_manual(), allows manually assign colors bar. See scale_fill_*() functions options color choices.","code":"ggplot(mpg, aes(x = drv)) + geom_bar(fill = \"blue\") ggplot(mpg, aes(x = drv, fill = drv)) + geom_bar() ggplot(mpg, aes(x = drv, fill = drv)) + geom_bar() + scale_fill_manual(values = c(\"purple\", \"orange\", \"darkblue\"))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-increase-the-space-between-the-bars-in-my-bar-plot","dir":"Articles","previous_headings":"Spacing and widths","what":"How can I increase the space between the bars in my bar plot?","title":"FAQ: Barplots","text":"Set width geom_bar() small value obtain narrower bars space . default, width bars 0.9 (90% resolution data). can set argument lower value get bars narrower space .","code":"ggplot(mpg, aes(x = drv)) + geom_bar(width = 0.5) ggplot(mpg, aes(x = drv)) + geom_bar(width = 0.1)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-remove-the-space-between-the-bars-and-the-x-axis","dir":"Articles","previous_headings":"Spacing and widths","what":"How can I remove the space between the bars and the x-axis?","title":"FAQ: Barplots","text":"Adjust expand argument scale_y_continuous(), e.g. add scale_y_continuous(expand = expansion(mult = c(0, 0.05))) remove expansion lower end y-axis keep expansion upper end y-axis 0.05 (default expansion continuous scales). default ggplot2 expands axes geoms aren’t flush edges plot. remove spacing bars x-axis, keep spacing bars top plot, use following. achieve opposite, switch values mult. Note tallest bar now flush top plot. adjust spacing around x-axis, adjust expand argument scale_x_discrete(). Note places bars flush left side leaves space right side. default look bar plot can achieved following.","code":"ggplot(mpg, aes(x = drv)) + geom_bar() ggplot(mpg, aes(x = drv)) + geom_bar() + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) ggplot(mpg, aes(x = drv)) + geom_bar() + scale_y_continuous(expand = expansion(mult = c(0.05, 0))) ggplot(mpg, aes(x = drv)) + geom_bar() + scale_x_discrete(expand = expansion(add = c(0, 0.6))) ggplot(mpg, aes(x = drv)) + geom_bar() + scale_x_discrete(expand = expansion(add = 0.6)) + scale_y_continuous(expand = expansion(mult = 0.05))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-do-i-ensure-that-bars-on-a-dodged-bar-plot-have-the-same-width","dir":"Articles","previous_headings":"Spacing and widths","what":"How do I ensure that bars on a dodged bar plot have the same width?","title":"FAQ: Barplots","text":"Set position = position_dodge2(preserve = \"single\") geom_bar(). following plot bars differing widths within level drv differing levels class represented. can use position_dodge2() preserve = \"single\" address .","code":"ggplot(mpg, aes(x = drv, fill = class)) + geom_bar(position = \"dodge\") ggplot(mpg, aes(x = drv, fill = class)) + geom_bar(position = position_dodge2(preserve = \"single\"))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-create-a-stacked-bar-plot-displaying-a-conditional-distribution-where-each-stack-is-scaled-to-sum-to-100","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I create a stacked bar plot displaying a conditional distribution where each stack is scaled to sum to 100%?","title":"FAQ: Barplots","text":"Use position = \"fill\" geom_bar() geom_col(). also want show percentages axis, use scales::label_percent(). following plot useful comparing counts useful comparing proportions, need want able make statements like “sample, ’s likely two-seater car rear-wheel drive SUV rear-wheel drive”. position = \"fill\" generate bar plot bars equal length stacks bar show proportion drv particular class. want show percentages instead proportions x-axis, can define scale_x_continuous() scales::label_percent().","code":"ggplot(mpg, aes(y = class, fill = drv)) + geom_bar() ggplot(mpg, aes(y = class, fill = drv)) + geom_bar(position = \"fill\") ggplot(mpg, aes(y = class, fill = drv)) + geom_bar(position = \"fill\") + scale_x_continuous(name = \"percentage\", labels = scales::label_percent(accuracy = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-create-a-stacked-bar-plot-based-on-data-from-a-contingency-table-of-to-categorical-variables","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I create a stacked bar plot based on data from a contingency table of to categorical variables?","title":"FAQ: Barplots","text":"First reshape data (e.g. tidyr::pivot_longer()) one row per combination levels categorical variables, use geom_col() draw bars. Suppose following data opinion poll, numbers cells represent number responses party/opinion combination. can first pivot data longer obtain data frame one row per party/opinion combination new column, n, number responses fall category. , can pass result ggplot() create bar party y (x, prefer vertical bars) axis fill bars number responses opinion. plot proportions (relative frequencies) instead counts, use position = \"fill\" geom_col().","code":"poll <- tribble( ~party, ~agree, ~disagree, ~no_opinion, \"Democrat\", 20, 30, 20, \"Republican\", 15, 20, 10, \"Independent\", 10, 5, 0 ) poll_longer <- poll %>% pivot_longer( cols = -party, names_to = \"opinion\", values_to = \"n\" ) poll_longer #> # A tibble: 9 × 3 #> party opinion n #> #> 1 Democrat agree 20 #> 2 Democrat disagree 30 #> 3 Democrat no_opinion 20 #> 4 Republican agree 15 #> 5 Republican disagree 20 #> 6 Republican no_opinion 10 #> 7 Independent agree 10 #> 8 Independent disagree 5 #> 9 Independent no_opinion 0 ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + geom_col() ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + geom_col(position = \"fill\") + xlab(\"proportion\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-make-a-grouped-bar-plot","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I make a grouped bar plot?","title":"FAQ: Barplots","text":"Map variable want group x y aesthetic, map variable want color vars fill aesthetic, set position = \"dodge\" geom_bar(). Suppose data survey three questions, respondents select “Agree” “Disagree” question. ’ll first want reshape data row represents respondent / question pair. can tidyr::pivot_longer(). , pass resulting longer data frame ggplot() group responses question together.","code":"survey <- tibble::tribble( ~respondent, ~q1, ~q2, ~q3, 1, \"Agree\", \"Agree\", \"Disagree\", 2, \"Disagree\", \"Agree\", \"Disagree\", 3, \"Agree\", \"Agree\", \"Disagree\", 4, \"Disagree\", \"Disagree\", \"Agree\" ) survey %>% tidyr::pivot_longer( cols = -respondent, names_to = \"question\", values_to = \"response\" ) %>% ggplot(aes(x = question, fill = response)) + geom_bar(position = \"dodge\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-make-a-bar-plot-of-group-means","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I make a bar plot of group means?","title":"FAQ: Barplots","text":"Either calculate group means first use geom_col() draw bars let ggplot2 calculate means stat_summary() fun = \"mean\" geom = \"bar\". One option calculating group means using dplyr::group_by() followed dplyr::summarise(). , can pass resulting data frame ggplot() plot bars using geom_col(). Alternatively, can use stat_summary() let ggplot2 calculate plot means.","code":"mpg %>% group_by(drv) %>% summarise(mean_hwy = mean(hwy)) %>% ggplot(aes(x = drv, y = mean_hwy)) + geom_col() ggplot(mpg, aes(x = drv, y = hwy)) + stat_summary(fun = \"mean\", geom = \"bar\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"why-do-the-bars-on-my-plot-disappear-when-i-specify-an-axis-range-with-ylim-how-can-i-get-the-bars-to-show-up-within-a-given-axis-range","dir":"Articles","previous_headings":"Axes and axis limits","what":"Why do the bars on my plot disappear when I specify an axis range with ylim()? How can I get the bars to show up within a given axis range?","title":"FAQ: Barplots","text":"ylim() shortcut supplying limits argument individual scales. either set, values outside limits specified replaced NA. Since bars naturally start y = 0, replacing part bars NAs results bars entirely disappearing plot. changing axis limits without dropping data observations, set limits coord_cartesian() instead. Also note result deceiving bar plot, avoided general. following plot y-axis limited 20 120, hence bars showing . order obtain bar plot limited y-axis, need instead set limits coord_cartesian(). , indeed, deceiving plot. ’re using bar plot display values take value 0, might choose different geom instead. example, following data plot. Also suppose want cut bars y = 1000 since know variable ’re plotting take value less 1000, might use geom_point() instead.","code":"ggplot(mpg, aes(x = drv)) + geom_bar() + ylim(c(20, 120)) #> Warning: Removed 3 rows containing missing values or values outside the scale #> range (`geom_bar()`). ggplot(mpg, aes(x = drv)) + geom_bar() + coord_cartesian(ylim = c(20,110)) df <- tibble::tribble( ~x, ~y, \"A\", 1050, \"B\", 1100, \"C\", 1150 ) ggplot(df, aes(x = x, y = y)) + geom_col() # don't do this ggplot(df, aes(x = x, y = y)) + geom_col() + coord_cartesian(ylim = c(1000, 1150)) # do this ggplot(df, aes(x = x, y = y)) + geom_point(size = 3)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-legend-title","dir":"Articles","previous_headings":"Legends","what":"How can I change the legend title?","title":"FAQ: Customising","text":"Change label aesthetic legend drawn labs(). default legend label name variable mapped aesthetic legend drawn . can change title legend using labs(). legend drawn multiple aesthetics, ’ll want update title .","code":"ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + labs(color = \"Drive train\") # not this ggplot(mpg, aes(x = hwy, y = cty, color = drv, shape = drv)) + geom_point() + labs(color = \"Drive train\") # but this ggplot(mpg, aes(x = hwy, y = cty, color = drv, shape = drv)) + geom_point() + labs(color = \"Drive train\", shape = \"Drive train\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-increase-the-spacing-between-legend-keys","dir":"Articles","previous_headings":"Legends","what":"How can I increase the spacing between legend keys?","title":"FAQ: Customising","text":"Increase horizontal space legend keys legend.spacing.x theme(). argument takes unit object created grid::unit(). horizontal legend, generally placed top bottom plot legend.position = \"top\" \"bottom\", can change spacing legend keys legend.spacing.x. can supply unit object argument, e.g. unit(1.0, \"cm\") 1 cm space legend keys. See documentation grid::unit() options units. vertical legends changing legend.spacing.y changes space legend title keys, keys, e.g. see large space legend title keys. order change space legend keys, can first make key size bigger legend.key.size remove grey background color legend.key. Note legend title longer aligned keys approach. can also shift hjust setting legend.title.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme( legend.position = \"bottom\", legend.spacing.x = unit(1.0, \"cm\") ) ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme(legend.spacing.y = unit(3.0, \"cm\")) ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme( legend.key.size = unit(1.5, \"cm\"), legend.key = element_rect(color = NA, fill = NA) ) ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme( legend.key.size = unit(1.5, \"cm\"), legend.key = element_rect(color = NA, fill = NA), legend.title = element_text(hjust = 0.5) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-key-labels-in-the-legend","dir":"Articles","previous_headings":"Legends","what":"How can I change the key labels in the legend?","title":"FAQ: Customising","text":"don’t want change levels variable legend drawn , can change key labels time drawing plot using labels argument appropriate scale_*() function, e.g. scale_colour_discrete() legend discrete variable mapped fill aesthetic. labels argument scale_* functions takes named vectors, recommend using relabeling keys legend. Using named lists allows declare explicitly label assigned level, without keep track level order.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + scale_color_discrete( labels = c(\"4\" = \"4-wheel drive\", \"f\" = \"Front-wheel drive\", \"r\" = \"Rear-wheel drive\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-font-sizes-in-the-legend","dir":"Articles","previous_headings":"Legends","what":"How can I change the font sizes in the legend?","title":"FAQ: Customising","text":"Set preference legend.text key labels legend.title theme(). cases, set font size size argument element_text(), e.g. legend.text = element_text(size = 14). Font characteristics legend can controlled legend.text legend.title elements theme(). can use following 14 pts text legend key labels 10 pts text legend title. (Note doesn’t result visually pleasing legend, default ggplot2 uses larger font size legend title legend text.) customization legend text, see documentation element_text(), e.g. can change font colors font face well.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = class)) + geom_point() + theme( legend.text = element_text(size = 14), legend.title = element_text(size = 10) ) ggplot(mpg, aes(x = hwy, y = cty, color = class)) + geom_point() + theme( legend.text = element_text(size = 14, color = \"red\"), legend.title = element_text(size = 10, face = \"bold.italic\") )"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-background-colour-of-plot","dir":"Articles","previous_headings":"Colours","what":"How can I change the background colour of plot?","title":"FAQ: Customising","text":"Set color panel.background element theme() element_rect(), takes arguments like fill (background fill color) colour (background border color. can set background colour plot panel.background theme(). following example border made thicker linewidth = 3 want change colour plotting area panel panel, can thing plot.background. Note ggplot2 variety complete themes might already ’re hoping accomplish. example, prefer minimal look plots, without grey background, might try theme_minimal(). can continue customization based one themes. might also find thematic package useful simplified theming plots.","code":"ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme(panel.background = element_rect(fill = \"lightblue\", colour = \"red\", linewidth = 3)) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme(plot.background = element_rect(fill = \"lightblue\", colour = \"red\", linewidth = 3)) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme_minimal() ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme_minimal() + theme(plot.background = element_rect(colour = \"red\", linewidth = 3))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-colour-nas-are-represented-with-in-a-plot","dir":"Articles","previous_headings":"Colours","what":"How can I change the colour NAs are represented with in a plot?","title":"FAQ: Customising","text":"can set color NA na.value argument appropriate scale_*() function, e.g. scale_fill_discrete(na.value = \"purple\") make NAs purple. Suppose following data frame two discrete variables, one NA. default, ggplot2 uses grey represent NAs. can change color NA scale_fill_discrete() case, e.g. make purple. can also set color \"transparent\". plot shown theme_minimal() demonstrate looks plot transparent background. Note possible, setting colour transparent wouldn’t recommended particular case gives appearance floating bar.","code":"df <- tibble::tribble( ~group, ~outcome, 1, \"yes\", 1, \"no\", 2, \"yes\", 2, \"no\", 2, \"no\", 2, NA ) ggplot(df, aes(x = group, fill = outcome)) + geom_bar() ggplot(df, aes(x = group, fill = outcome)) + geom_bar() + scale_fill_discrete(na.value = \"purple\") ggplot(df, aes(x = group, fill = outcome)) + geom_bar() + scale_fill_discrete(na.value = \"transparent\") + theme_minimal()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-default-font-size-in-ggplot2","dir":"Articles","previous_headings":"Fonts","what":"How can I change the default font size in ggplot2?","title":"FAQ: Customising","text":"Set base_size theme ’re using, theme_gray() default. base font size 11 pts default. can change base_size argument theme ’re using. See complete theme documentation high level options can set. like plots within session/document use particular base size, can set set_theme(). Run following beginning session include top R Markdown document.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = class)) + geom_point() + theme_gray(base_size = 18) set_theme(theme_gray(base_size = 18))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-font-size-of-the-plot-title-and-subtitle","dir":"Articles","previous_headings":"Fonts","what":"How can I change the font size of the plot title and subtitle?","title":"FAQ: Customising","text":"Set preference plot.title plot.subtitle theme(). cases, set font size size argument element_text(), e.g. plot.title = element_text(size = 20). Font characteristics plot titles subtitles can controlled plot.title plot.subtitle elements theme(). can use following 20 pts text plot title 15 pts text plot subtitle. customization plot title subtitle, see documentation element_text(), e.g. can change font colors font face well.","code":"ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( title = \"This is the plot title\", subtitle = \"And this is the subtitle\" ) + theme( plot.title = element_text(size = 20), plot.subtitle = element_text(size = 15) ) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( title = \"This is the plot title\", subtitle = \"And this is the subtitle\" ) + theme( plot.title = element_text(size = 20, color = \"red\"), plot.subtitle = element_text(size = 15, face = \"bold.italic\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-font-size-of-axis-labels","dir":"Articles","previous_headings":"Fonts","what":"How can I change the font size of axis labels?","title":"FAQ: Customising","text":"Set preference axis.title. axis.title.x, axis.title.y theme(). cases, set font size size argument element_text(), e.g. axis.text = element_text(size = 14). Font characteristics axis labels can controlled axis.title.x axis.title.y (axis.title settings axes). customization plot title subtitle, see documentation element_text(), e.g. can change font colors font face well. can also change size axis text (e.g. numbers axis ticks) using axis.text (axis.text.x axis.text.y want set different sizes).","code":"ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( x = \"This is HUGE\", y = \"This is small\" ) + theme( axis.title.x = element_text(size = 20), axis.title.y = element_text(size = 10) ) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( x = \"This is HUGE\", y = \"This is tiny\" ) + theme( axis.title.x = element_text(size = 20, color = \"red\"), axis.title.y = element_text(size = 10, face = \"bold.italic\") ) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( x = \"The axis labels are the same size\", y = \"The axis labels are the same size\" ) + theme( axis.title = element_text(size = 16), axis.text = element_text(size = 20, color = \"blue\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"what-is-the-default-size-of-geom_text-and-how-can-i-change-the-font-size-of-geom_text","dir":"Articles","previous_headings":"Fonts","what":"What is the default size of geom_text() and how can I change the font size of geom_text()?","title":"FAQ: Customising","text":"default font size geom_text() 3.88. can change size using size argument geom_text() single plot. want use updated size, can set update_geom_defaults(), e.g. update_geom_defaults(\"text\", list(size = 6)). One tricky thing size mm size element_text() pt. want match geom_text()’s font size theme’s size, specify size.unit = \"pt\" geom_text() single plot, divide number .pt constant variable update_geom_defaults(). Please refer “Font size” section aesthetic specifications details. Suppose following data frame visualization. can set size text following. can map size aesthetic. following size determined x value scale_size_identity(). want use updated size geom_text() series plots session/R Markdown document, can set use update_geom_defaults() update default size, e.g. want size geom_text() 6, use update_geom_defaults(\"text\", list(size = 6)).","code":"GeomLabel$default_aes$size #> #> expr: ^from_theme(fontsize) #> env: namespace:ggplot2 df <- tibble::tribble( ~x, ~y, ~name, 2, 2, \"two\", 3, 3, \"three\", 4, 4, \"four\" ) ggplot(df, aes(x = x, y = y, label = name)) + geom_text() ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 6) ggplot(df, aes(x = x, y = y, label = name)) + geom_text(aes(size = x)) + scale_size_identity()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"what-is-the-difference-between-facet_wrap-and-facet_grid","dir":"Articles","previous_headings":"Panes","what":"What is the difference between facet_wrap() and facet_grid()?","title":"FAQ: Faceting","text":"simplest answer use facet_wrap() faceting single variable facet_grid() faceting two variables want create grid panes. facet_wrap() commonly used facet plot single categorical variable. facet_grid() commonly used facet plot two categorical variables. Notice results empty panes (e.g. 4-wheel drive 5 cylinders) cars mpg dataset fall categories. can also use facet_wrap() facet two categorical variables. create facets combinations levels variables data exists. facet_wrap() can control number rows /columns resulting plot layout using nrow ncol arguments, respectively. facet_grid() values determined number levels variables ’re faceting . Similarly, can also use facet_grid() facet single categorical variable well. formula notation, use . indicate faceting done along axis, .e. cyl ~ . facets across y-axis (within column) . ~ cyl facets across x-axis (within row).","code":"ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_wrap(~ drv) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(cyl ~ drv) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_wrap(cyl ~ drv) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(cyl ~ .) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(. ~ cyl) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`."},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-place-a-vertical-lines-geom_vline-in-each-pane-of-a-faceted-plot","dir":"Articles","previous_headings":"Panes","what":"How can I place a vertical lines (geom_vline()) in each pane of a faceted plot?","title":"FAQ: Faceting","text":"First, calculate lines placed save information separate data frame. , add geom_vline() layer plot uses summarized data. Suppose following plot, want add vertical line mean value hwy (highway mileage) pane. First, calculate means save new data frame. , add geom_vline() layer plot uses summary data.","code":"ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 5) + facet_wrap(~ drv) library(dplyr) #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union mpg_summary <- mpg %>% group_by(drv) %>% summarise(hwy_mean = mean(hwy)) mpg_summary #> # A tibble: 3 × 2 #> drv hwy_mean #> #> 1 4 19.2 #> 2 f 28.2 #> 3 r 21 ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 5) + facet_wrap(~ drv) + geom_vline(data = mpg_summary, aes(xintercept = hwy_mean))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-set-individual-axis-limits-for-facets","dir":"Articles","previous_headings":"Axes","what":"How can I set individual axis limits for facets?","title":"FAQ: Faceting","text":"Either let ggplot2 determine custom axis limits facets based range data ’re plotting using scales argument facet_wrap() facet_grid() , sufficient, use expand_limits() ensure limits include single value range values. Suppose following faceted plot. default, x y scales shared across facets. can control behaviour scales argument faceting functions: varying scales across rows (\"free_x\"), columns (\"free_y\"), rows columns (\"free\"), e.g. also want make sure particular value range included facets, can set expand_limits(), e.g. ensure 10 included x-axis values 20 25 included y-axis:","code":"ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv) ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv, scales = \"free\") ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv, scales = \"free\") + expand_limits(x = 10, y = c(20, 25))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-remove-the-facet-labels-entirely","dir":"Articles","previous_headings":"Facet labels","what":"How can I remove the facet labels entirely?","title":"FAQ: Faceting","text":"Set strip.text element theme() element_blank(). Setting strip.text element_blank() remove facet labels. can also remove labels across rows strip.x.text across columns strip.y.text.","code":"ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv) + theme(strip.text = element_blank()) ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv) + theme(strip.text.x = element_blank())"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"the-facet-labels-in-my-plot-are-too-long-so-they-get-cut-off--how-can-i-wrap-facet-label-text-so-that-long-labels-are-spread-across-two-rows","dir":"Articles","previous_headings":"Facet labels","what":"The facet labels in my plot are too long so they get cut off. How can I wrap facet label text so that long labels are spread across two rows?","title":"FAQ: Faceting","text":"Use label_wrap_gen() labeller argument faceting function set width (number characters) maximum number characters wrapping strip. data frame 100 observations, 50 come one group 50 another. groups long names, facet ploy group, facet labels (strips) get cut . can control maximum width facet label setting width label_wrap_gen() function, passed labeller argument faceting function.","code":"df <- data.frame( x = rnorm(100), group = c(rep(\"A long group name for the first group\", 50), rep(\"A muuuuuuuuuuuuuch longer group name for the second group\", 50)) ) ggplot(df, aes(x = x)) + geom_histogram(binwidth = 0.5) + facet_wrap(~ group) ggplot(df, aes(x = x)) + geom_histogram(binwidth = 0.5) + facet_wrap(~ group, labeller = labeller(group = label_wrap_gen(width = 25)))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-set-different-axis-labels-for-facets","dir":"Articles","previous_headings":"Facet labels","what":"How can I set different axis labels for facets?","title":"FAQ: Faceting","text":"Use as_labeller() labeller argument faceting function set strip.background strip.placement elements theme() place facet labels axis labels go. particularly useful solution plotting data different scales without use double y-axes. Suppose data price data given item years two countries different currency scales. can plot price versus time facet country, resulting plot can bit difficult read due shared y-axis label. following can customize facet labels first as_labeller(), turn default y-axis label, place facet labels y-axis label goes (\"outside\" \"left\").","code":"df <- data.frame( year = rep(2016:2021, 2), price = c(10, 10, 13, 12, 14, 15, 1000, 1010, 1200, 1050, 1105, 1300), country = c(rep(\"US\", 6), rep(\"Japan\", 6)) ) df #> year price country #> 1 2016 10 US #> 2 2017 10 US #> 3 2018 13 US #> 4 2019 12 US #> 5 2020 14 US #> 6 2021 15 US #> 7 2016 1000 Japan #> 8 2017 1010 Japan #> 9 2018 1200 Japan #> 10 2019 1050 Japan #> 11 2020 1105 Japan #> 12 2021 1300 Japan ggplot(df, aes(x = year, y = price)) + geom_smooth() + facet_wrap(~ country, ncol = 1, scales = \"free_y\") + scale_x_continuous(breaks = 2011:2020) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(df, aes(x = year, y = price)) + geom_smooth() + facet_wrap(~ country, ncol = 1, scales = \"free_y\", labeller = as_labeller( c(US = \"US Dollars (USD)\", Japan = \"Japanese Yens (JPY)\")), strip.position = \"left\" ) + scale_x_continuous(breaks = 2011:2020) + labs(y = NULL) + theme(strip.background = element_blank(), strip.placement = \"outside\") #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' #> Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; #> returning -Inf #> Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; #> returning -Inf"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-reorder-the-bars-in-a-bar-plot-by-their-value","dir":"Articles","previous_headings":"Bar plots","what":"How can I reorder the bars in a bar plot by their value?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re creating bar plot aesthetic mapping. forcats package offers variety options , forcats::fct_infreq() ordering number observations within level. following bar plot shows number cars fall class category. Classes ordered alphabetically. might prefer ordered number cars class. , can use forcats::fct_infreq(). ’d like plot highest value first, can also reverse order forcats::fct_rev(). might also want simplify axis label.","code":"ggplot(mpg, aes(y = class)) + geom_bar() ggplot(mpg, aes(y = forcats::fct_infreq(class))) + geom_bar() ggplot(mpg, aes(y = forcats::fct_rev(forcats::fct_infreq(class)))) + geom_bar() + labs(y = \"class\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-reorder-the-stacks-in-a-stacked-bar-plot","dir":"Articles","previous_headings":"Bar plots","what":"How can I reorder the stacks in a stacked bar plot?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re creating stacks aesthetic mapping. forcats package offers variety options , forcats::fct_reorder() reorder levels forcats::fct_rev() reverse order. Suppose following stacked bar plot clarity diamonds cut. can reverse order clarity levels displayed bars forcats::fct_rev(). also change order ’re presented legend two orders match.","code":"ggplot(diamonds, aes(x = cut, fill = clarity)) + geom_bar() ggplot(diamonds, aes(x = cut, fill = forcats::fct_rev(clarity))) + geom_bar() + labs(fill = \"clarity\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-control-the-order-of-boxes-in-a-side-by-side-box-plot","dir":"Articles","previous_headings":"Box plots","what":"How can I control the order of boxes in a side-by-side box plot?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re faceting . forcats package offers variety options , forcats::fct_relevel() manual reordering forcats::fct_reorder() ordering particular value, e.g. group median. order boxes determined order levels variable ’re grouping . faceting variable character, order alphabetical default. Suppose ’d like boxes ordered ascending order medians. can data transformation step prior plotting (e.g. dplyr::mutate()) can directly plotting code shown . might want customize x-axis label well.","code":"ggplot(mpg, aes(x = class, y = hwy)) + geom_boxplot() ggplot(mpg, aes(x = forcats::fct_reorder(class, hwy, .fun = median), y = hwy)) + geom_boxplot() + labs(x = \"class\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-control-the-order-of-panes-created-with-facet_wrap-or-facet_grid","dir":"Articles","previous_headings":"Facets","what":"How can I control the order of panes created with facet_wrap() or facet_grid()?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re faceting . forcats package offers variety options , forcats::fct_relevel(). order panes determined order levels variable ’re faceting . faceting variable character, order alphabetical default. Suppose ’d like panes order \"r\", \"f\" , \"4\". can use forcats::fct_relevel() reorder levels drv. can data transformation step prior plotting (e.g. dplyr::mutate()) can directly plotting code shown .","code":"ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_wrap(~drv) ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_wrap(~forcats::fct_relevel(drv, \"r\", \"f\", \"4\"))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-control-the-order-of-the-points-plotted","dir":"Articles","previous_headings":"Overplotting","what":"How can I control the order of the points plotted?","title":"FAQ: Reordering","text":"specific point (group points) want make sure plotted top others, subset data observations add new layer plot. Suppose following data frame. default, scatterplot looks. Note blue circle partially covered yellow triangle since observation comes later dataset. Similarly black asterisk appears top red square. Suppose arranged data ascending order x-coordinates plotted . Now blue circle yellow triangle since 0.01 comes 0 similarly red square black asterisk since 1 comes 0.99. wanted make sure observation identified asterisk always plotted top, regardless data arranged data frame, can create additional layer observation.","code":"df <- tibble::tribble( ~id, ~x, ~y, ~shape, ~fill, 1, 0.01, 0, \"circle filled\", \"blue\", 2, 1, 0, \"square filled\", \"red\", 3, 0.99, 0, \"asterisk\", \"black\", 4, 0, 0, \"triangle filled\", \"yellow\" ) ggplot(df, aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(size = 8) + scale_shape_identity() + scale_fill_identity() df_arranged <- df %>% dplyr::arrange(x) df_arranged %>% ggplot(aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(size = 8) + scale_shape_identity() + scale_fill_identity() ggplot(mapping = aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(data = df %>% filter(shape != \"asterisk\"), size = 8) + geom_point(data = df %>% filter(shape == \"asterisk\"), size = 8) + scale_shape_identity() + scale_fill_identity() ggplot(mapping = aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(data = df_arranged %>% filter(shape != \"asterisk\"), size = 8) + geom_point(data = df_arranged %>% filter(shape == \"asterisk\"), size = 8) + scale_shape_identity() + scale_fill_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"referring-to-ggplot2-functions","dir":"Articles","previous_headings":"","what":"Referring to ggplot2 functions","title":"Using ggplot2 in packages","text":"function another package, list ggplot2 DESCRIPTION Imports refer functions using :: (e.g., ggplot2::function_name): use ggplot2 functions frequently, may wish import one functions ggplot2 NAMESPACE. use roxygen2, can include #' @importFrom ggplot2 roxygen comment block (work datasets like mpg). Even use many ggplot2 functions package, unwise use ggplot2 Depends import entire package NAMESPACE (e.g. #' @import ggplot2). Using ggplot2 Depends attach ggplot2 package attached, includes package tested. makes difficult ensure others can use functions package without attaching (.e., using ::). Similarly, importing 450 ggplot2’s exported objects namespace makes difficult separate responsibility package responsibility ggplot2, addition making difficult readers code figure functions coming !","code":"mpg_drv_summary <- function() { ggplot2::ggplot(ggplot2::mpg) + ggplot2::geom_bar(ggplot2::aes(x = .data$drv)) + ggplot2::coord_flip() } #' @importFrom ggplot2 ggplot aes geom_bar coord_flip mpg_drv_summary <- function() { ggplot(ggplot2::mpg) + geom_bar(aes(x = drv)) + coord_flip() }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"using-aes-and-vars-in-a-package-function","dir":"Articles","previous_headings":"","what":"Using aes() and vars() in a package function","title":"Using ggplot2 in packages","text":"create graphic using ggplot2 probably need use aes() least . graphic uses facets, might using vars() refer columns plot/layer data. functions use non-standard evaluation, try use function within package result CMD check note: three situations encounter problem: already know column name expression advance. column name character vector. user specifies column name expression, want function use kind non-standard evaluation used aes() vars(). already know mapping advance (like example) use .data pronoun rlang make explicit referring drv layer data variable named drv (may may exist elsewhere). avoid similar note CMD check .data, use #' @importFrom rlang .data roxygen code block (typically package documentation generated usethis::use_package_doc()). column name character vector (e.g., col = \"drv\"), use .data[[col]]: column name expression supplied user, can also pass aes() vars() using {{ col }}. tidy eval operator captures expression supplied user forwards another tidy eval-enabled function aes() vars(). summarise: know mapping facet specification col advance, use aes(.data$col) vars(.data$col). col variable contains column name character vector, use aes(.data[[col]] vars(.data[[col]]). like behaviour col look feel like within aes() vars(), use aes({{ col }}) vars({{ col }}). see lot ways wild, syntax use one can guarantee work future! particular, don’t use aes_() aes_string(), deprecated may removed future version. Finally, don’t skip step creating data frame mapping pass ggplot() layers! see ways , may rely undocumented behaviour can fail unexpected ways.","code":"mpg_drv_summary <- function() { ggplot(ggplot2::mpg) + geom_bar(aes(y = drv)) + facet_wrap(vars(year)) } N checking R code for possible problems (2.7s) mpg_drv_summary: no visible binding for global variable ‘drv’ Undefined global functions or variables: drv mpg_drv_summary <- function() { ggplot(ggplot2::mpg) + geom_bar(aes(y = .data$drv)) + facet_wrap(vars(.data$year)) } col_summary <- function(df, col, by) { ggplot(df) + geom_bar(aes(y = .data[[col]])) + facet_wrap(vars(.data[[by]])) } col_summary(mpg, \"drv\", \"year\") col_summary <- function(df, col, by) { ggplot(df) + geom_bar(aes(y = {{ col }})) + facet_wrap(vars({{ by }})) } col_summary(mpg, drv, year)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"using-ggplot2-to-visualize-an-object","dir":"Articles","previous_headings":"Best practices for common tasks","what":"Using ggplot2 to visualize an object","title":"Using ggplot2 in packages","text":"ggplot2 commonly used packages visualize objects (e.g., plot()-style function). example, package might define S3 class represents probability various discrete values: Many S3 classes R plot() method, unrealistic expect single plot() method can provide visualization every one users looking . useful, however, provide plot() method visual summary users can call understand essence object. satisfy users, suggest writing function transforms object data frame (list() data frames object complicated). good example approach ggdendro, creates dendrograms using ggplot2 also computes data necessary users make . example, function might look like : general, users plot() call side-effects: results graphic displayed. different behaviour ggplot(), displayed unless explicitly print()ed. , ggplot2 defines generic autoplot(), call expected return ggplot() (side effects). autoplot() method defined, plot() method can consist print()ing result autoplot(): considered bad practice implement S3 generic like plot(), autoplot() don’t S3 class, makes hard package developer control S3 implement method . shouldn’t stop creating functions visualize objects!","code":"mpg_drv_dist <- structure( c( \"4\" = 103 / 234, \"f\" = 106 / 234, \"r\" = 25 / 234 ), class = \"discrete_distr\" ) discrete_distr_data <- function(x) { tibble::tibble( value = names(x), probability = as.numeric(x) ) } discrete_distr_data(mpg_drv_dist) #> # A tibble: 3 × 2 #> value probability #> #> 1 4 0.440 #> 2 f 0.453 #> 3 r 0.107 #' @importFrom ggplot2 autoplot autoplot.discrete_distr <- function(object, ...) { plot_data <- discrete_distr_data(object) ggplot(plot_data, aes(.data$value, .data$probability)) + geom_col() + coord_flip() + labs(x = \"Value\", y = \"Probability\") } #' @importFrom graphics plot plot.discrete_distr <- function(x, ...) { print(autoplot(x, ...)) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"creating-a-new-theme","dir":"Articles","previous_headings":"Best practices for common tasks","what":"Creating a new theme","title":"Using ggplot2 in packages","text":"creating new theme, ’s always good practice start existing theme (e.g. theme_grey()) %+replace% elements changed. right strategy even seemingly elements replaced, makes difficult us improve themes adding new elements. many excellent examples themes ggthemes package. important theme calculated package loaded. , theme object stored compiled bytecode built package, may may align installed version ggplot2! package default theme visualizations, correct way load function returns default theme:","code":"#' @importFrom ggplot2 %+replace% theme_custom <- function(...) { theme_grey(...) %+replace% theme( panel.border = element_rect(linewidth = 1, fill = NA), panel.background = element_blank(), panel.grid = element_line(colour = \"grey80\") ) } mpg_drv_summary() + theme_custom() default_theme <- function() { theme_custom() } mpg_drv_summary2 <- function() { mpg_drv_summary() + default_theme() }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"testing-ggplot2-output","dir":"Articles","previous_headings":"Best practices for common tasks","what":"Testing ggplot2 output","title":"Using ggplot2 in packages","text":"suggest testing output ggplot2 using vdiffr package, tool manage visual test cases (one ways test ggplot2). changes ggplot2 code introduce change visual output ggplot, tests fail run locally part Continuous Integration setup. use vdiffr, make sure using testthat (can use usethis::use_testthat() get started) add vdiffr Suggests DESCRIPTION. , use vdiffr::expect_doppleganger(, ) make test fails visual changes . However, consider whether visual testing best strategy adds dependency ggplot2 performs rendering may change versions. extracting layer data using get_layer_data() testing values directly possible far better directly test behaviour code.","code":"test_that(\"output of ggplot() is stable\", { vdiffr::expect_doppelganger(\"A blank plot\", ggplot()) })"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"ggplot2-in-suggests","dir":"Articles","previous_headings":"Best practices for common tasks","what":"ggplot2 in Suggests","title":"Using ggplot2 in packages","text":"use ggplot2 package, likely want list Imports. like list ggplot2 Suggests instead, able #' @importFrom ggplot2 ... (.e., must refer ggplot2 objects using ::). use infix operators ggplot2 like %+replace% want keep ggplot2 Suggests, can assign operator within function used: Generally, add method ggplot2 generic like autoplot(), ggplot2 Imports. reason like keep ggplot2 Suggests, possible register generics ggplot2 installed using vctrs::s3_register(). , copy paste source vctrs::s3_register() package avoid adding vctrs dependency.","code":"theme_custom <- function(...) { `%+replace%` <- ggplot2::`%+replace%` ggplot2::theme_grey(...) %+replace% ggplot2::theme(panel.background = ggplot2::element_blank()) } .onLoad <- function(...) { if (requireNamespace(\"ggplot2\", quietly = TRUE)) { vctrs::s3_register(\"ggplot2::autoplot\", \"discrete_distr\") } }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"read-more","dir":"Articles","previous_headings":"","what":"Read more","title":"Using ggplot2 in packages","text":"things consider taking dependency. post goes detail many using ggplot2 example good read anyone developing package using ggplot2.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"colour-and-fill","dir":"Articles","previous_headings":"","what":"Colour and fill","title":"Aesthetic specifications","text":"Almost every geom either colour, fill, . Colours fills can specified following ways: name, e.g., \"red\". R 657 built-named colours, can listed colours(). rgb specification, string form \"#RRGGBB\" pairs RR, GG, BB consists two hexadecimal digits giving value range 00 FF can optionally make colour transparent using form \"#RRGGBBAA\". NA, completely transparent colour. munsell package, Charlotte Wickham, makes easy choose specific colours using system designed Albert H. Munsell. invest little learning system, provides convenient way specifying aesthetically pleasing colours.","code":"munsell::mnsl(\"5PB 5/10\") #> [1] \"#447DBF\""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"lines","dir":"Articles","previous_headings":"","what":"Lines","title":"Aesthetic specifications","text":"well colour, appearance line affected linewidth, linetype, linejoin lineend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"sec:line-type-spec","dir":"Articles","previous_headings":"Lines","what":"Line type","title":"Aesthetic specifications","text":"Line types can specified : integer name: 0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash, shown : lengths /stretches line. done string containing 2, 4, 6, 8 hexadecimal digits give lengths consecutive lengths. example, string \"33\" specifies three units followed three \"3313\" specifies three units followed three followed one finally three . five standard dash-dot line types described correspond 44, 13, 1343, 73, 2262.","code":"lty <- c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\") linetypes <- data.frame( y = seq_along(lty), lty = lty ) ggplot(linetypes, aes(0, y)) + geom_segment(aes(xend = 5, yend = y, linetype = lty)) + scale_linetype_identity() + geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) + scale_x_continuous(NULL, breaks = NULL) + scale_y_reverse(NULL, breaks = NULL) lty <- c(\"11\", \"18\", \"1f\", \"81\", \"88\", \"8f\", \"f1\", \"f8\", \"ff\") linetypes <- data.frame( y = seq_along(lty), lty = lty ) ggplot(linetypes, aes(0, y)) + geom_segment(aes(xend = 5, yend = y, linetype = lty)) + scale_linetype_identity() + geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) + scale_x_continuous(NULL, breaks = NULL) + scale_y_reverse(NULL, breaks = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"linewidth","dir":"Articles","previous_headings":"Lines","what":"Linewidth","title":"Aesthetic specifications","text":"Due historical error, unit linewidth roughly 0.75 mm. Making exactly 1 mm change large number existing plots, ’re stuck mistake.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"line-endjoin-paramters","dir":"Articles","previous_headings":"Lines","what":"Line end/join paramters","title":"Aesthetic specifications","text":"appearance line end controlled lineend paramter, can one “round”, “butt” (default), “square”. appearance line joins controlled linejoin can one “round” (default), “mitre”, “bevel”. Mitre joins automatically converted bevel joins whenever angle small (create long bevel). controlled linemitre parameter specifies maximum ratio line width length mitre.","code":"df <- data.frame(x = 1:3, y = c(4, 1, 9)) base <- ggplot(df, aes(x, y)) + xlim(0.5, 3.5) + ylim(0, 10) base + geom_path(linewidth = 10) + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, lineend = \"round\") + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, lineend = \"square\") + geom_path(linewidth = 1, colour = \"red\") df <- data.frame(x = 1:3, y = c(9, 1, 9)) base <- ggplot(df, aes(x, y)) + ylim(0, 10) base + geom_path(linewidth = 10) + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, linejoin = \"mitre\") + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, linejoin = \"bevel\") + geom_path(linewidth = 1, colour = \"red\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"polygons","dir":"Articles","previous_headings":"","what":"Polygons","title":"Aesthetic specifications","text":"border polygon controlled colour, linetype, linewidth aesthetics described . inside controlled fill.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"sec:shape-spec","dir":"Articles","previous_headings":"Point","what":"Shape","title":"Aesthetic specifications","text":"Shapes take five types values: integer [0,25][0, 25]: name shape: single character, use character plotting symbol. . draw smallest rectangle visible, usually 1 pixel. NA, draw nothing.","code":"shapes <- data.frame( shape = c(0:19, 22, 21, 24, 23, 20), x = 0:24 %/% 5, y = -(0:24 %% 5) ) ggplot(shapes, aes(x, y)) + geom_point(aes(shape = shape), size = 5, fill = \"red\") + geom_text(aes(label = shape), hjust = 0, nudge_x = 0.15) + scale_shape_identity() + expand_limits(x = 4.1) + theme_void() shape_names <- c( \"circle\", paste(\"circle\", c(\"open\", \"filled\", \"cross\", \"plus\", \"small\")), \"bullet\", \"square\", paste(\"square\", c(\"open\", \"filled\", \"cross\", \"plus\", \"triangle\")), \"diamond\", paste(\"diamond\", c(\"open\", \"filled\", \"plus\")), \"triangle\", paste(\"triangle\", c(\"open\", \"filled\", \"square\")), paste(\"triangle down\", c(\"open\", \"filled\")), \"plus\", \"cross\", \"asterisk\" ) shapes <- data.frame( shape_names = shape_names, x = c(1:7, 1:6, 1:3, 5, 1:3, 6, 2:3, 1:3), y = -rep(1:6, c(7, 6, 4, 4, 2, 3)) ) ggplot(shapes, aes(x, y)) + geom_point(aes(shape = shape_names), fill = \"red\", size = 5) + geom_text(aes(label = shape_names), nudge_y = -0.3, size = 3.5) + scale_shape_identity() + theme_void()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"colour-and-fill-1","dir":"Articles","previous_headings":"Point","what":"Colour and fill","title":"Aesthetic specifications","text":"colour applies shapes, fill applies shapes 21-25, can seen . size filled part controlled size, size stroke controlled stroke. measured mm, total size point sum two. Note size constant along diagonal following figure.","code":"sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2) ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) + geom_abline(slope = -1, intercept = 6, colour = \"white\", linewidth = 6) + geom_point(shape = 21, fill = \"red\") + scale_size_identity()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"font-family","dir":"Articles","previous_headings":"Text","what":"Font family","title":"Aesthetic specifications","text":"three fonts guaranteed work everywhere: “sans” (default), “serif”, “mono”: ’s trickier include system font plot text drawing done differently graphics device (GD). five GDs common use (png(), pdf(), screen devices Windows, Mac Linux), font work everywhere need configure five devices five different ways. Two packages simplify quandary bit: showtext makes GD-independent plots rendering text polygons. extrafont converts fonts standard format devices can use. approaches pros cons, need try see works best needs.","code":"df <- data.frame(x = 1, y = 3:1, family = c(\"sans\", \"serif\", \"mono\")) ggplot(df, aes(x, y)) + geom_text(aes(label = family, family = family))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"font-face","dir":"Articles","previous_headings":"Text","what":"Font face","title":"Aesthetic specifications","text":"","code":"df <- data.frame(x = 1:4, fontface = c(\"plain\", \"bold\", \"italic\", \"bold.italic\")) ggplot(df, aes(1, x)) + geom_text(aes(label = fontface, fontface = fontface))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"font-size","dir":"Articles","previous_headings":"Text","what":"Font size","title":"Aesthetic specifications","text":"size text measured mm default. unusual, makes size text consistent size lines points. Typically specify font size using points (pt short), 1 pt = 0.35mm. geom_text() geom_label(), can set size.unit = \"pt\" use points instead millimeters. addition, ggplot2 provides conversion factor variable .pt, want draw 12pt text, can also set size = 12 / .pt.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"justification","dir":"Articles","previous_headings":"Text","what":"Justification","title":"Aesthetic specifications","text":"Horizontal vertical justification parameterisation, either string (“top”, “middle”, “bottom”, “left”, “center”, “right”) number 0 1: top = 1, middle = 0.5, bottom = 0 left = 0, center = 0.5, right = 1 Note can use numbers outside range (0, 1), ’s recommended.","code":"just <- expand.grid(hjust = c(0, 0.5, 1), vjust = c(0, 0.5, 1)) just$label <- paste0(just$hjust, \", \", just$vjust) ggplot(just, aes(hjust, vjust)) + geom_point(colour = \"grey70\", size = 5) + geom_text(aes(label = label, hjust = hjust, vjust = vjust))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"data","dir":"Articles","previous_headings":"","what":"Data","title":"Introduction to ggplot2","text":"foundation every graphic, ggplot2 uses data construct plot. system works best data provided tidy format, briefly means rectangular data frame structure rows observations columns variables. first step many plots, pass data ggplot() function, stores data used later parts plotting system. example, intend make graphic mpg dataset, start follows:","code":"ggplot(data = mpg)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"mapping","dir":"Articles","previous_headings":"","what":"Mapping","title":"Introduction to ggplot2","text":"mapping plot set instructions parts data mapped onto aesthetic attributes geometric objects. ‘dictionary’ translate tidy data graphics system. mapping can made using aes() function make pairs graphical attributes parts data. want cty hwy columns map x- y-coordinates plot, can follows:","code":"ggplot(mpg, mapping = aes(x = cty, y = hwy))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"layers","dir":"Articles","previous_headings":"","what":"Layers","title":"Introduction to ggplot2","text":"heart graphic layers. take mapped data display something humans can understand representation data. Every layer consists three important parts: geometry determines data displayed, points, lines, rectangles. statistical transformation may compute new variables data affect data displayed. position adjustment primarily determines piece data displayed. layer can constructed using geom_*() stat_*() functions. functions often determine one three parts layer, two can still specified. can use two layers display cty hwy columns mpg dataset points stack trend line top.","code":"ggplot(mpg, aes(cty, hwy)) + # to create a scatterplot geom_point() + # to fit and overlay a loess trendline geom_smooth(formula = y ~ x, method = \"lm\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"scales","dir":"Articles","previous_headings":"","what":"Scales","title":"Introduction to ggplot2","text":"Scales important translating shown graph back understanding data. scales typically form pairs aesthetic attributes plots, represented plots guides, like axes legends. Scales responsible updating limits plot, setting breaks, formatting labels, possibly applying transformation. use scales, one can use one scale functions patterned scale_{aesthetic}_{type}() functions, {aesthetic} one pairings made mapping part plot. map class column mpg dataset viridis colour palette, can write following:","code":"ggplot(mpg, aes(cty, hwy, colour = class)) + geom_point() + scale_colour_viridis_d()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"facets","dir":"Articles","previous_headings":"","what":"Facets","title":"Introduction to ggplot2","text":"Facets can used separate small multiples, different subsets data. powerful tool quickly split data smaller panels, based one variables, display patterns trends (lack thereof) within subsets. facets mapping can given formula. plot subsets mpg dataset based levels drv year variables, can use facet_grid() follows:","code":"ggplot(mpg, aes(cty, hwy)) + geom_point() + facet_grid(year ~ drv)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"coordinates","dir":"Articles","previous_headings":"","what":"Coordinates","title":"Introduction to ggplot2","text":"can view coordinates part plot interpreter position aesthetics. typically Cartesian coordinates used, coordinate system powers display map projections polar plots. can also use coordinates display plot fixed aspect ratio one unit length x y directions. coord_fixed() function sets ratio automatically.","code":"ggplot(mpg, aes(cty, hwy)) + geom_point() + coord_fixed()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"theme","dir":"Articles","previous_headings":"","what":"Theme","title":"Introduction to ggplot2","text":"theme system controls almost visuals plot controlled data therefore important look feel plot. can use theme customizations ranging changing location legends setting background color plot. Many elements theme hierarchical setting look general axis line affects x y axes simultaneously. tweak look plot, one can use many built-theme_*() functions /detail specific aspects theme() function. element_*() functions control graphical attributes theme components.","code":"ggplot(mpg, aes(cty, hwy, colour = class)) + geom_point() + theme_minimal() + theme( legend.position = \"top\", axis.line = element_line(linewidth = 0.75), axis.line.x.bottom = element_line(colour = \"blue\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"combining","dir":"Articles","previous_headings":"","what":"Combining","title":"Introduction to ggplot2","text":"mentioned start, can layer pieces build customized plot data, like one shown beginning vignette: want learn , sure take look ggplot2 book.","code":"ggplot(mpg, aes(cty, hwy)) + geom_point(mapping = aes(colour = displ)) + geom_smooth(formula = y ~ x, method = \"lm\") + scale_colour_viridis_c() + facet_grid(year ~ drv) + coord_fixed() + theme_minimal() + theme(panel.grid.minor = element_blank())"},{"path":"https://ggplot2.tidyverse.org/dev/articles/profiling.html","id":"performance-focused-changes-across-versions","dir":"Articles","previous_headings":"","what":"Performance focused changes across versions","title":"Profiling Performance","text":"keep track changes focused improving performance gtable summarised :","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/profiling.html","id":"v3-5-1-9000","dir":"Articles","previous_headings":"Performance focused changes across versions","what":"v3.5.1.9000","title":"Profiling Performance","text":"Avoid costly factor construction scale_apply issue really appeared plotting huge datasets (>1e6 rows). order train map position aesthetics rows matched based panel. require splitting row indexes panel included factor() call. factor constructor slow large vectors can simplified considerably specific case. , split can avoided completely one panel","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/profiling.html","id":"v3-1-0","dir":"Articles","previous_headings":"Performance focused changes across versions","what":"v3.1.0","title":"Profiling Performance","text":"Caching calls grid::descentDetails() absolute biggest offender construction titles. recent versions included calls grid::descentDetails() ensure aligned across plots, quite heavy. calls now cached calculated per font setting. Use performant data.frame constructor throughout codebase data.frame() function carries lot overhead order sanitize check input. generally needed sure input just lead slower code. data.frame() call now used dealing output packages extra safety benefit. Use performant alternative utils::modifyList modifyList() nice convenience function carries lot overhead. mainly used plot element constructions slowed application theme settings. performant version added used throughout. Speed position transformation transform_position helper unreasonably slow due slowness getting assigning columns data.frame. input now treated list transformation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Hadley Wickham. Author. Winston Chang. Author. Lionel Henry. Author. Thomas Lin Pedersen. Author, maintainer. Kohske Takahashi. Author. Claus Wilke. Author. Kara Woo. Author. Hiroaki Yutani. Author. Dewey Dunnington. Author. Teun van den Brand. Author. . Copyright holder, funder.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"H. Wickham. ggplot2: Elegant Graphics Data Analysis. Springer-Verlag New York, 2016.","code":"@Book{, author = {Hadley Wickham}, title = {ggplot2: Elegant Graphics for Data Analysis}, publisher = {Springer-Verlag New York}, year = {2016}, isbn = {978-3-319-24277-4}, url = {https://ggplot2.tidyverse.org}, }"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"overview","dir":"","previous_headings":"","what":"Overview","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"ggplot2 system declaratively creating graphics, based Grammar Graphics. provide data, tell ggplot2 map variables aesthetics, graphical primitives use, takes care details.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"","code":"# The easiest way to get ggplot2 is to install the whole tidyverse: install.packages(\"tidyverse\") # Alternatively, install just ggplot2: install.packages(\"ggplot2\") # Or the development version from GitHub: # install.packages(\"pak\") pak::pak(\"tidyverse/ggplot2\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"usage","dir":"","previous_headings":"","what":"Usage","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"’s hard succinctly describe ggplot2 works embodies deep philosophy visualisation. However, cases start ggplot(), supply dataset aesthetic mapping (aes()). add layers (like geom_point() geom_histogram()), scales (like scale_colour_brewer()), faceting specifications (like facet_wrap()) coordinate systems (like coord_flip()).","code":"library(ggplot2) ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"lifecycle","dir":"","previous_headings":"","what":"Lifecycle","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"ggplot2 now 10 years old used hundreds thousands people make millions plots. means, --large, ggplot2 changes relatively little. make changes, generally add new functions arguments rather changing behaviour existing functions, make changes existing behaviour compelling reasons. looking innovation, look ggplot2’s rich ecosystem extensions. See community maintained list https://exts.ggplot2.tidyverse.org/gallery/.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"learning-ggplot2","dir":"","previous_headings":"","what":"Learning ggplot2","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"new ggplot2 better starting systematic introduction, rather trying learn reading individual documentation pages. Currently, three good places start: Data Visualization Communication chapters R Data Science. R Data Science designed give comprehensive introduction tidyverse, two chapters get speed essentials ggplot2 quickly possible. ’d like take online course, try Data Visualization R ggplot2 Kara Woo. ’d like follow webinar, try Plotting Anything ggplot2 Thomas Lin Pedersen. want dive making common graphics quickly possible, recommend R Graphics Cookbook Winston Chang. provides set recipes solve common graphics problems. ’ve mastered basics want learn , read ggplot2: Elegant Graphics Data Analysis. describes theoretical underpinnings ggplot2 shows pieces fit together. book helps understand theory underpins ggplot2, help create new types graphics specifically tailored needs.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"getting-help","dir":"","previous_headings":"","what":"Getting help","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"two main places get help ggplot2: RStudio community friendly place ask questions ggplot2. Stack Overflow great source answers common ggplot2 questions. also great place get help, created reproducible example illustrates problem.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/absoluteGrob.html","id":null,"dir":"Reference","previous_headings":"","what":"Absolute grob — absoluteGrob","title":"Absolute grob — absoluteGrob","text":"grob fixed dimensions position.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/absoluteGrob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Absolute grob — absoluteGrob","text":"","code":"absoluteGrob( grob, width = NULL, height = NULL, xmin = NULL, ymin = NULL, vp = NULL )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/absoluteGrob.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Absolute grob — absoluteGrob","text":"still experimental","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/add_theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify properties of an element in a theme object — add_theme","title":"Modify properties of an element in a theme object — add_theme","text":"Modify properties element theme object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/add_theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify properties of an element in a theme object — add_theme","text":"","code":"add_theme(t1, t2, t2name, call = caller_env())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/add_theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify properties of an element in a theme object — add_theme","text":"t1 theme object t2 theme object added t1 t2name name t2 object. used printing informative error messages.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":null,"dir":"Reference","previous_headings":"","what":"Construct aesthetic mappings — aes","title":"Construct aesthetic mappings — aes","text":"Aesthetic mappings describe variables data mapped visual properties (aesthetics) geoms. Aesthetic mappings can set ggplot() individual layers.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Construct aesthetic mappings — aes","text":"","code":"aes(x, y, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Construct aesthetic mappings — aes","text":"x, y, ... List name-value pairs form aesthetic = variable describing variables layer data mapped aesthetics used paired geom/stat. expression variable evaluated within layer data, need refer original dataset (.e., use ggplot(df, aes(variable)) instead ggplot(df, aes(df$variable))). names x y aesthetics typically omitted common; aesthetics must named.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Construct aesthetic mappings — aes","text":"list class uneval. Components list either quosures constants.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Construct aesthetic mappings — aes","text":"function also standardises aesthetic names converting color colour (also substrings, e.g., point_color point_colour) translating old style R names ggplot names (e.g., pch shape cex size).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"quasiquotation","dir":"Reference","previous_headings":"","what":"Quasiquotation","title":"Construct aesthetic mappings — aes","text":"aes() quoting function. means inputs quoted evaluated context data. makes easy work variables data frame can name directly. flip side use quasiquotation program aes(). See tidy evaluation tutorial dplyr programming vignette learn techniques.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Construct aesthetic mappings — aes","text":"","code":"aes(x = mpg, y = wt) #> Aesthetic mapping: #> * `x` -> `mpg` #> * `y` -> `wt` aes(mpg, wt) #> Aesthetic mapping: #> * `x` -> `mpg` #> * `y` -> `wt` # You can also map aesthetics to functions of variables aes(x = mpg ^ 2, y = wt / cyl) #> Aesthetic mapping: #> * `x` -> `mpg^2` #> * `y` -> `wt/cyl` # Or to constants aes(x = 1, colour = \"smooth\") #> Aesthetic mapping: #> * `x` -> 1 #> * `colour` -> \"smooth\" # Aesthetic names are automatically standardised aes(col = x) #> Aesthetic mapping: #> * `colour` -> `x` aes(fg = x) #> Aesthetic mapping: #> * `colour` -> `x` aes(color = x) #> Aesthetic mapping: #> * `colour` -> `x` aes(colour = x) #> Aesthetic mapping: #> * `colour` -> `x` # aes() is passed to either ggplot() or specific layer. Aesthetics supplied # to ggplot() are used as defaults for every layer. ggplot(mpg, aes(displ, hwy)) + geom_point() ggplot(mpg) + geom_point(aes(displ, hwy)) # Tidy evaluation ---------------------------------------------------- # aes() automatically quotes all its arguments, so you need to use tidy # evaluation to create wrappers around ggplot2 pipelines. The # simplest case occurs when your wrapper takes dots: scatter_by <- function(data, ...) { ggplot(data) + geom_point(aes(...)) } scatter_by(mtcars, disp, drat) # If your wrapper has a more specific interface with named arguments, # you need the \"embrace operator\": scatter_by <- function(data, x, y) { ggplot(data) + geom_point(aes({{ x }}, {{ y }})) } scatter_by(mtcars, disp, drat) # Note that users of your wrapper can use their own functions in the # quoted expressions and all will resolve as it should! cut3 <- function(x) cut_number(x, 3) scatter_by(mtcars, cut3(disp), drat)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":null,"dir":"Reference","previous_headings":"","what":"Define aesthetic mappings programmatically — aes_","title":"Define aesthetic mappings programmatically — aes_","text":"Aesthetic mappings describe variables data mapped visual properties (aesthetics) geoms. aes() uses non-standard evaluation capture variable names. aes_() aes_string() require explicitly quote inputs either \"\" aes_string(), quote ~ aes_(). (aes_q() alias aes_()). makes aes_() aes_string() easy program . aes_string() aes_() particularly useful writing functions create plots can use strings quoted names/calls define aesthetic mappings, rather use substitute() generate call aes(). recommend using aes_(), creating equivalents aes(colour = \"colour\") aes(x = `X$1`) aes_string() quite clunky.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Define aesthetic mappings programmatically — aes_","text":"","code":"aes_(x, y, ...) aes_string(x, y, ...) aes_q(x, y, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Define aesthetic mappings programmatically — aes_","text":"x, y, ... List name value pairs. Elements must either quoted calls, strings, one-sided formulas constants.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":"life-cycle","dir":"Reference","previous_headings":"","what":"Life cycle","title":"Define aesthetic mappings programmatically — aes_","text":"functions soft-deprecated. Please use tidy evaluation idioms instead. Regarding aes_string(), can replace .data pronoun. example, following code can achieve mapping aes_string(x_var, y_var). details, please see vignette(\"ggplot2--packages\").","code":"x_var <- \"foo\" y_var <- \"bar\" aes(.data[[x_var]], .data[[y_var]])"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":null,"dir":"Reference","previous_headings":"","what":"Given a character vector, create a set of identity mappings — aes_all","title":"Given a character vector, create a set of identity mappings — aes_all","text":"Given character vector, create set identity mappings","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Given a character vector, create a set of identity mappings — aes_all","text":"","code":"aes_all(vars)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Given a character vector, create a set of identity mappings — aes_all","text":"vars vector variable names","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Given a character vector, create a set of identity mappings — aes_all","text":"","code":"aes_all(names(mtcars)) #> Aesthetic mapping: #> * `mpg` -> `mpg` #> * `cyl` -> `cyl` #> * `disp` -> `disp` #> * `hp` -> `hp` #> * `drat` -> `drat` #> * `wt` -> `wt` #> * `qsec` -> `qsec` #> * `vs` -> `vs` #> * `am` -> `am` #> * `gear` -> `gear` #> * `carb` -> `carb` aes_all(c(\"x\", \"y\", \"col\", \"pch\")) #> Aesthetic mapping: #> * `x` -> `x` #> * `y` -> `y` #> * `colour` -> `col` #> * `shape` -> `pch`"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_auto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Automatic aesthetic mapping — aes_auto","text":"","code":"aes_auto(data = NULL, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_auto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Automatic aesthetic mapping — aes_auto","text":"data data.frame names variables ... aesthetics need explicitly mapped.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"aesthetics parameters change colour (colour fill) opacity (alpha) geom elements plot. Almost every geom either colour fill (), well can alpha modified. Modifying colour plot useful way enhance presentation data, often especially plot graphs two variables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":"colour-and-fill","dir":"Reference","previous_headings":"","what":"Colour and fill","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"colour aesthetic used draw lines strokes, geom_point() geom_line(), also line contours geom_rect() geom_polygon(). fill aesthetic used colour inside areas geoms, geom_rect() geom_polygon(), also insides shapes 21-25 geom_point(). Colours fills can specified following ways: name, e.g., \"red\". R 657 built-named colours, can listed grDevices::colors(). rgb specification, string form \"#RRGGBB\" pairs RR, GG, BB consists two hexadecimal digits giving value range 00 FF. can optionally make colour transparent using form \"#RRGGBBAA\". NA, completely transparent colour.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":"alpha","dir":"Reference","previous_headings":"","what":"Alpha","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"Alpha refers opacity geom. Values alpha range 0 1, lower values corresponding transparent colors. Alpha can additionally modified colour fill aesthetic either aesthetic provides color values using rgb specification (\"#RRGGBBAA\"), AA refers transparency values.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"","code":"# \\donttest{ # Bar chart example p <- ggplot(mtcars, aes(factor(cyl))) # Default plotting p + geom_bar() # To change the interior colouring use fill aesthetic p + geom_bar(fill = \"red\") # Compare with the colour aesthetic which changes just the bar outline p + geom_bar(colour = \"red\") # Combining both, you can see the changes more clearly p + geom_bar(fill = \"white\", colour = \"red\") # Both colour and fill can take an rgb specification. p + geom_bar(fill = \"#00abff\") # Use NA for a completely transparent colour. p + geom_bar(fill = NA, colour = \"#00abff\") # Colouring scales differ depending on whether a discrete or # continuous variable is being mapped. For example, when mapping # fill to a factor variable, a discrete colour scale is used. ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar() # When mapping fill to continuous variable a continuous colour # scale is used. ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) # Some geoms only use the colour aesthetic but not the fill # aesthetic (e.g. geom_point() or geom_line()). p <- ggplot(economics, aes(x = date, y = unemploy)) p + geom_line() p + geom_line(colour = \"green\") p + geom_point() p + geom_point(colour = \"red\") # For large datasets with overplotting the alpha # aesthetic will make the points more transparent. set.seed(1) df <- data.frame(x = rnorm(5000), y = rnorm(5000)) p <- ggplot(df, aes(x,y)) p + geom_point() p + geom_point(alpha = 0.5) p + geom_point(alpha = 1/10) # Alpha can also be used to add shading. p <- ggplot(economics, aes(x = date, y = unemploy)) + geom_line() p yrng <- range(economics$unemploy) p <- p + geom_rect( aes(NULL, NULL, xmin = start, xmax = end, fill = party), ymin = yrng[1], ymax = yrng[2], data = presidential ) p p + scale_fill_manual(values = alpha(c(\"blue\", \"red\"), .3)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":null,"dir":"Reference","previous_headings":"","what":"Control aesthetic evaluation — aes_eval","title":"Control aesthetic evaluation — aes_eval","text":"aesthetics mapped variables found data. Sometimes, however, want delay mapping later rendering process. ggplot2 three stages data can map aesthetics , three functions control stage aesthetics evaluated. after_stat() replaces old approaches using either stat(), e.g. stat(density), surrounding variable names .., e.g. ..density...","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Control aesthetic evaluation — aes_eval","text":"","code":"# These functions can be used inside the `aes()` function # used as the `mapping` argument in layers, for example: # geom_density(mapping = aes(y = after_stat(scaled))) after_stat(x) after_scale(x) from_theme(x) stage(start = NULL, after_stat = NULL, after_scale = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Control aesthetic evaluation — aes_eval","text":"x aesthetic expression using variables calculated stat (after_stat()) layer aesthetics (after_scale()). start aesthetic expression using variables layer data. after_stat aesthetic expression using variables calculated stat. after_scale aesthetic expression using layer aesthetics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"staging","dir":"Reference","previous_headings":"","what":"Staging","title":"Control aesthetic evaluation — aes_eval","text":"follows overview three stages evaluation aesthetic evaluation can controlled.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"stage-direct-input","dir":"Reference","previous_headings":"","what":"Stage 1: direct input","title":"Control aesthetic evaluation — aes_eval","text":"default map beginning, using layer data provided user. want map directly layer data anything special. stage original layer data can accessed.","code":"# 'x' and 'y' are mapped directly ggplot(mtcars) + geom_point(aes(x = mpg, y = disp))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"stage-after-stat-transformation","dir":"Reference","previous_headings":"","what":"Stage 2: after stat transformation","title":"Control aesthetic evaluation — aes_eval","text":"second stage data transformed layer stat. common example mapping stat transformed data height bars geom_histogram(): height come variable underlying data, instead mapped count computed stat_bin(). order map stat transformed data use after_stat() function flag evaluation aesthetic mapping postponed stat transformation. Evaluation stat transformation access variables calculated stat, original mapped values. 'computed variables' section stat lists variables available access.","code":"# The 'y' values for the histogram are computed by the stat ggplot(faithful, aes(x = waiting)) + geom_histogram() # Choosing a different computed variable to display, matching up the # histogram with the density plot ggplot(faithful, aes(x = waiting)) + geom_histogram(aes(y = after_stat(density))) + geom_density()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"stage-after-scale-transformation","dir":"Reference","previous_headings":"","what":"Stage 3: after scale transformation","title":"Control aesthetic evaluation — aes_eval","text":"third last stage data transformed mapped plot scales. example mapping scaled data use desaturated version stroke colour fill. use after_scale() flag evaluation mapping data scaled. Evaluation scaling access final aesthetics layer (including non-mapped, default aesthetics).","code":"# The exact colour is known after scale transformation ggplot(mpg, aes(cty, colour = factor(cyl))) + geom_density() # We re-use colour properties for the fill without a separate fill scale ggplot(mpg, aes(cty, colour = factor(cyl))) + geom_density(aes(fill = after_scale(alpha(colour, 0.3))))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"complex-staging","dir":"Reference","previous_headings":"","what":"Complex staging","title":"Control aesthetic evaluation — aes_eval","text":"want map aesthetic multiple times, e.g. map x data column stat, remap geom, can use stage() function collect multiple mappings.","code":"# Use stage to modify the scaled fill ggplot(mpg, aes(class, hwy)) + geom_boxplot(aes(fill = stage(class, after_scale = alpha(fill, 0.4)))) # Using data for computing summary, but placing label elsewhere. # Also, we're making our own computed variable to use for the label. ggplot(mpg, aes(class, displ)) + geom_violin() + stat_summary( aes( y = stage(displ, after_stat = 8), label = after_stat(paste(mean, \"±\", sd)) ), geom = \"text\", fun.data = ~ round(data.frame(mean = mean(.x), sd = sd(.x)), 2) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"theme-access","dir":"Reference","previous_headings":"","what":"Theme access","title":"Control aesthetic evaluation — aes_eval","text":"from_theme() function can used acces element_geom() fields theme(geom) argument. Using aes(colour = from_theme(ink)) aes(colour = from_theme(accent)) allows swapping foreground accent colours.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Control aesthetic evaluation — aes_eval","text":"","code":"# Default histogram display ggplot(mpg, aes(displ)) + geom_histogram(aes(y = after_stat(count))) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # Scale tallest bin to 1 ggplot(mpg, aes(displ)) + geom_histogram(aes(y = after_stat(count / max(count)))) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # Use a transparent version of colour for fill ggplot(mpg, aes(class, hwy)) + geom_boxplot(aes(colour = class, fill = after_scale(alpha(colour, 0.4)))) # Use stage to modify the scaled fill ggplot(mpg, aes(class, hwy)) + geom_boxplot(aes(fill = stage(class, after_scale = alpha(fill, 0.4)))) # Making a proportional stacked density plot ggplot(mpg, aes(cty)) + geom_density( aes( colour = factor(cyl), fill = after_scale(alpha(colour, 0.3)), y = after_stat(count / sum(n[!duplicated(group)])) ), position = \"stack\", bw = 1 ) + geom_density(bw = 1) # Imitating a ridgeline plot ggplot(mpg, aes(cty, colour = factor(cyl))) + geom_ribbon( stat = \"density\", outline.type = \"upper\", aes( fill = after_scale(alpha(colour, 0.3)), ymin = after_stat(group), ymax = after_stat(group + ndensity) ) ) # Labelling a bar plot ggplot(mpg, aes(class)) + geom_bar() + geom_text( aes( y = after_stat(count + 2), label = after_stat(count) ), stat = \"count\" ) # Labelling the upper hinge of a boxplot, # inspired by June Choe ggplot(mpg, aes(displ, class)) + geom_boxplot(outlier.shape = NA) + geom_text( aes( label = after_stat(xmax), x = stage(displ, after_stat = xmax) ), stat = \"boxplot\", hjust = -0.5 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_group_order.html","id":null,"dir":"Reference","previous_headings":"","what":"Aesthetics: grouping — aes_group_order","title":"Aesthetics: grouping — aes_group_order","text":"group aesthetic default set interaction discrete variables plot. choice often partitions data correctly, , discrete variable used plot, need explicitly define grouping structure mapping group variable different value group.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_group_order.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Aesthetics: grouping — aes_group_order","text":"applications grouping set implicitly mapping one discrete variables x, y, colour, fill, alpha, shape, size, /linetype. demonstrated examples . three common cases default display data correctly. geom_line() multiple individuals plot tries connect every observation, even across individuals, line. geom_line() discrete x-position implies groups, whereas observations span discrete x-positions. grouping needs different different layers, example computing statistic observations another layer shows individuals. examples use longitudinal dataset, Oxboys, nlme package demonstrate cases. Oxboys records heights (height) centered ages (age) 26 boys (Subject), measured nine occasions (Occasion).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_group_order.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Aesthetics: grouping — aes_group_order","text":"","code":"# \\donttest{ p <- ggplot(mtcars, aes(wt, mpg)) # A basic scatter plot p + geom_point(size = 4) # Using the colour aesthetic p + geom_point(aes(colour = factor(cyl)), size = 4) # Using the shape aesthetic p + geom_point(aes(shape = factor(cyl)), size = 4) # Using fill p <- ggplot(mtcars, aes(factor(cyl))) p + geom_bar() p + geom_bar(aes(fill = factor(cyl))) p + geom_bar(aes(fill = factor(vs))) # Using linetypes ggplot(economics_long, aes(date, value01)) + geom_line(aes(linetype = variable)) # Multiple groups with one aesthetic p <- ggplot(nlme::Oxboys, aes(age, height)) # The default is not sufficient here. A single line tries to connect all # the observations. p + geom_line() # To fix this, use the group aesthetic to map a different line for each # subject. p + geom_line(aes(group = Subject)) # Different groups on different layers p <- p + geom_line(aes(group = Subject)) # Using the group aesthetic with both geom_line() and geom_smooth() # groups the data the same way for both layers p + geom_smooth(aes(group = Subject), method = \"lm\", se = FALSE) #> `geom_smooth()` using formula = 'y ~ x' # Changing the group aesthetic for the smoother layer # fits a single line of best fit across all boys p + geom_smooth(aes(group = 1), size = 2, method = \"lm\", se = FALSE) #> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0. #> ℹ Please use `linewidth` instead. #> `geom_smooth()` using formula = 'y ~ x' # Overriding the default grouping # Sometimes the plot has a discrete scale but you want to draw lines # that connect across groups. This is the strategy used in interaction # plots, profile plots, and parallel coordinate plots, among others. # For example, we draw boxplots of height at each measurement occasion. p <- ggplot(nlme::Oxboys, aes(Occasion, height)) + geom_boxplot() p # There is no need to specify the group aesthetic here; the default grouping # works because occasion is a discrete variable. To overlay individual # trajectories, we again need to override the default grouping for that layer # with aes(group = Subject) p + geom_line(aes(group = Subject), colour = \"blue\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":null,"dir":"Reference","previous_headings":"","what":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"linetype, linewidth, size, shape aesthetics modify appearance lines /points. also apply outlines polygons (linetype linewidth) text (size).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"linetype","dir":"Reference","previous_headings":"","what":"Linetype","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"linetype aesthetic can specified either integer (0-6), name (0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash), mapping discrete variable, string even number (eight) hexadecimal digits give lengths consecutive positions string. See examples hex string demonstration.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"linewidth-and-stroke","dir":"Reference","previous_headings":"","what":"Linewidth and stroke","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"linewidth aesthetic sets widths lines, can specified numeric value (historical reasons, units 0.75 millimetres). Alternatively, can also set via mapping continuous variable. stroke aesthetic serves role points, distinct discriminating points lines geoms geom_pointrange().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"size","dir":"Reference","previous_headings":"","what":"Size","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"size aesthetic control size points text, can specified numerical value (millimetres) via mapping continuous variable.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"shape","dir":"Reference","previous_headings":"","what":"Shape","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"shape aesthetic controls symbols points, can specified integer (0 25), single character (uses character plotting symbol), . draw smallest rectangle visible (.e., one pixel), NA draw nothing, mapping discrete variable. Symbols filled shapes described examples .","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"","code":"df <- data.frame(x = 1:10 , y = 1:10) p <- ggplot(df, aes(x, y)) p + geom_line(linetype = 2) p + geom_line(linetype = \"dotdash\") # An example with hex strings; the string \"33\" specifies three units on followed # by three off and \"3313\" specifies three units on followed by three off followed # by one on and finally three off. p + geom_line(linetype = \"3313\") # Mapping line type from a grouping variable ggplot(economics_long, aes(date, value01)) + geom_line(aes(linetype = variable)) # Linewidth examples ggplot(economics, aes(date, unemploy)) + geom_line(linewidth = 2, lineend = \"round\") ggplot(economics, aes(date, unemploy)) + geom_line(aes(linewidth = uempmed), lineend = \"round\") # Size examples p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point(size = 4) p + geom_point(aes(size = qsec)) p + geom_point(size = 2.5) + geom_hline(yintercept = 25, size = 3.5) # Shape examples p + geom_point() p + geom_point(shape = 5) p + geom_point(shape = \"k\", size = 3) p + geom_point(shape = \".\") p + geom_point(shape = NA) #> Warning: Removed 32 rows containing missing values or values outside the scale #> range (`geom_point()`). p + geom_point(aes(shape = factor(cyl))) # A look at all 25 symbols df2 <- data.frame(x = 1:5 , y = 1:25, z = 1:25) p <- ggplot(df2, aes(x, y)) p + geom_point(aes(shape = z), size = 4) + scale_shape_identity() # While all symbols have a foreground colour, symbols 19-25 also take a # background colour (fill) p + geom_point(aes(shape = z), size = 4, colour = \"Red\") + scale_shape_identity() p + geom_point(aes(shape = z), size = 4, colour = \"Red\", fill = \"Black\") + scale_shape_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":null,"dir":"Reference","previous_headings":"","what":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"following aesthetics can used specify position elements: x, y, xmin, xmax, ymin, ymax, xend, yend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"x y define locations points positions along line path. x, y xend, yend define starting ending points segment curve geometries. xmin, xmax, ymin ymax can used specify position annotations represent rectangular areas. addition, position aesthetics contextual geometry used . xintercept, yintercept, xmin_final, ymin_final, xmax_final, ymax_final, xlower, lower, xmiddle, middle, xupper, upper, x0 y0. Many used automatically computed geom_boxplot().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":"relation-to-width-and-height","dir":"Reference","previous_headings":"","what":"Relation to width and height","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"position aesthetics mentioned like x y location based. width height aesthetics closely related length based aesthetics, position aesthetics. Consequently, x y aesthetics respond scale transformations, whereas length based width height aesthetics transformed scales. example, pair x = 10, width = 2, gets translated locations xmin = 9, xmax = 11 using default identity scales. However, pair becomes xmin = 1, xmax = 100 using log10 scales, width = 2 log10-space spans 100-fold change.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"","code":"# Generate data: means and standard errors of means for prices # for each type of cut dmod <- lm(price ~ cut, data = diamonds) cut <- unique(diamonds$cut) cuts_df <- data.frame( cut, predict(dmod, data.frame(cut), se = TRUE)[c(\"fit\", \"se.fit\")] ) ggplot(cuts_df) + aes( x = cut, y = fit, ymin = fit - se.fit, ymax = fit + se.fit, colour = cut ) + geom_pointrange() # Using annotate p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() p p + annotate( \"rect\", xmin = 2, xmax = 3.5, ymin = 2, ymax = 25, fill = \"dark grey\", alpha = .5 ) # Geom_segment examples p + geom_segment( aes(x = 2, y = 15, xend = 2, yend = 25), arrow = arrow(length = unit(0.5, \"cm\")) ) #> Warning: All aesthetics have length 1, but the data has 32 rows. #> ℹ Please consider using `annotate()` or provide this layer with data #> containing a single row. p + geom_segment( aes(x = 2, y = 15, xend = 3, yend = 15), arrow = arrow(length = unit(0.5, \"cm\")) ) #> Warning: All aesthetics have length 1, but the data has 32 rows. #> ℹ Please consider using `annotate()` or provide this layer with data #> containing a single row. p + geom_segment( aes(x = 5, y = 30, xend = 3.5, yend = 25), arrow = arrow(length = unit(0.5, \"cm\")) ) #> Warning: All aesthetics have length 1, but the data has 32 rows. #> ℹ Please consider using `annotate()` or provide this layer with data #> containing a single row. # You can also use geom_segment() to recreate plot(type = \"h\") # from base R: set.seed(1) counts <- as.data.frame(table(x = rpois(100, 5))) counts$x <- as.numeric(as.character(counts$x)) with(counts, plot(x, Freq, type = \"h\", lwd = 10)) ggplot(counts, aes(x = x, y = Freq)) + geom_segment(aes(yend = 0, xend = x), size = 10)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":null,"dir":"Reference","previous_headings":"","what":"Create an annotation layer — annotate","title":"Create an annotation layer — annotate","text":"function adds geoms plot, unlike typical geom function, properties geoms mapped variables data frame, instead passed vectors. useful adding small annotations (text labels) data vectors, reason want put data frame.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create an annotation layer — annotate","text":"","code":"annotate( geom, x = NULL, y = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, xend = NULL, yend = NULL, ..., na.rm = FALSE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create an annotation layer — annotate","text":"geom name geom use annotation x, y, xmin, ymin, xmax, ymax, xend, yend positioning aesthetics - must specify least one . ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create an annotation layer — annotate","text":"Note position aesthetics scaled (.e. expand limits plot visible), aesthetics set. means layers created function never affect legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"unsupported-geoms","dir":"Reference","previous_headings":"","what":"Unsupported geoms","title":"Create an annotation layer — annotate","text":"Due special nature, reference line geoms geom_abline(), geom_hline(), geom_vline() used annotate(). can use geoms directly annotations.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create an annotation layer — annotate","text":"","code":"p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() p + annotate(\"text\", x = 4, y = 25, label = \"Some text\") p + annotate(\"text\", x = 2:5, y = 25, label = \"Some text\") p + annotate(\"rect\", xmin = 3, xmax = 4.2, ymin = 12, ymax = 21, alpha = .2) p + annotate(\"segment\", x = 2.5, xend = 4, y = 15, yend = 25, colour = \"blue\") p + annotate(\"pointrange\", x = 3.5, y = 20, ymin = 12, ymax = 28, colour = \"red\", size = 2.5, linewidth = 1.5) p + annotate(\"text\", x = 2:3, y = 20:21, label = c(\"my label\", \"label 2\")) p + annotate(\"text\", x = 4, y = 25, label = \"italic(R) ^ 2 == 0.75\", parse = TRUE) p + annotate(\"text\", x = 4, y = 25, label = \"paste(italic(R) ^ 2, \\\" = .75\\\")\", parse = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: Custom grob — annotation_custom","title":"Annotation: Custom grob — annotation_custom","text":"special geom intended use static annotations every panel. annotations affect scales (.e. x y axes grow cover range grob, grob modified ggplot settings mappings).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: Custom grob — annotation_custom","text":"","code":"annotation_custom(grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: Custom grob — annotation_custom","text":"grob grob display xmin, xmax x location (data coordinates) giving horizontal location raster ymin, ymax y location (data coordinates) giving vertical location raster","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Annotation: Custom grob — annotation_custom","text":"useful adding tables, inset plots, grid-based decorations.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Annotation: Custom grob — annotation_custom","text":"annotation_custom() expects grob fill entire viewport defined xmin, xmax, ymin, ymax. Grobs different (absolute) size center-justified region. Inf values can used fill full plot panel (see examples).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: Custom grob — annotation_custom","text":"","code":"# Dummy plot df <- data.frame(x = 1:10, y = 1:10) base <- ggplot(df, aes(x, y)) + geom_blank() + theme_bw() # Full panel annotation base + annotation_custom( grob = grid::roundrectGrob(), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf ) # Inset plot df2 <- data.frame(x = 1 , y = 1) g <- ggplotGrob(ggplot(df2, aes(x, y)) + geom_point() + theme(plot.background = element_rect(colour = \"black\"))) base + annotation_custom(grob = g, xmin = 1, xmax = 10, ymin = 8, ymax = 10)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: log tick marks — annotation_logticks","title":"Annotation: log tick marks — annotation_logticks","text":"function superseded using guide_axis_logticks(). annotation adds log tick marks diminishing spacing. tick marks probably make sense base 10.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: log tick marks — annotation_logticks","text":"","code":"annotation_logticks( base = 10, sides = \"bl\", outside = FALSE, scaled = TRUE, short = unit(0.1, \"cm\"), mid = unit(0.2, \"cm\"), long = unit(0.3, \"cm\"), colour = \"black\", linewidth = 0.5, linetype = 1, alpha = 1, color = NULL, ..., size = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: log tick marks — annotation_logticks","text":"base base log (default 10) sides string controls sides plot log ticks appear . can set string containing \"trbl\", top, right, bottom, left. outside logical controls whether move log ticks outside plot area. Default (FALSE). also need use coord_cartesian(clip = \"\"). See examples. scaled data already log-scaled? TRUE (default) data already transformed log10() using scale_y_log10(). FALSE using coord_trans(y = \"log10\"). short grid::unit() object specifying length short tick marks mid grid::unit() object specifying length middle tick marks. base 10, \"5\" ticks. long grid::unit() object specifying length long tick marks. base 10, \"1\" (\"10\") ticks. colour Colour tick marks. linewidth Thickness tick marks, mm. linetype Linetype tick marks (solid, dashed, etc.) alpha transparency tick marks. color alias colour. ... parameters passed layer size","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: log tick marks — annotation_logticks","text":"","code":"# Make a log-log plot (without log ticks) a <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point(na.rm = TRUE) + scale_x_log10( breaks = scales::trans_breaks(\"log10\", function(x) 10^x), labels = scales::trans_format(\"log10\", scales::math_format(10^.x)) ) + scale_y_log10( breaks = scales::trans_breaks(\"log10\", function(x) 10^x), labels = scales::trans_format(\"log10\", scales::math_format(10^.x)) ) + theme_bw() a + annotation_logticks() # Default: log ticks on bottom and left a + annotation_logticks(sides = \"lr\") # Log ticks for y, on left and right a + annotation_logticks(sides = \"trbl\") # All four sides a + annotation_logticks(sides = \"lr\", outside = TRUE) + coord_cartesian(clip = \"off\") # Ticks outside plot # Hide the minor grid lines because they don't align with the ticks a + annotation_logticks(sides = \"trbl\") + theme(panel.grid.minor = element_blank()) # Another way to get the same results as 'a' above: log-transform the data before # plotting it. Also hide the minor grid lines. b <- ggplot(msleep, aes(log10(bodywt), log10(brainwt))) + geom_point(na.rm = TRUE) + scale_x_continuous(name = \"body\", labels = scales::label_math(10^.x)) + scale_y_continuous(name = \"brain\", labels = scales::label_math(10^.x)) + theme_bw() + theme(panel.grid.minor = element_blank()) b + annotation_logticks() # Using a coordinate transform requires scaled = FALSE t <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point() + coord_trans(x = \"log10\", y = \"log10\") + theme_bw() t + annotation_logticks(scaled = FALSE) #> Warning: Removed 27 rows containing missing values or values outside the scale #> range (`geom_point()`). # Change the length of the ticks a + annotation_logticks( short = unit(.5,\"mm\"), mid = unit(3,\"mm\"), long = unit(4,\"mm\") )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: a map — annotation_map","title":"Annotation: a map — annotation_map","text":"Display fixed map plot. function predates geom_sf() framework work sf geometry columns input. However, can used conjunction geom_sf() layers /coord_sf() (see examples).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: a map — annotation_map","text":"","code":"annotation_map(map, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: a map — annotation_map","text":"map Data frame representing map. See geom_map() details. ... arguments used modify visual parameters, colour fill.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: a map — annotation_map","text":"","code":"if (FALSE) { # \\dontrun{ if (requireNamespace(\"maps\", quietly = TRUE)) { # location of cities in North Carolina df <- data.frame( name = c(\"Charlotte\", \"Raleigh\", \"Greensboro\"), lat = c(35.227, 35.772, 36.073), long = c(-80.843, -78.639, -79.792) ) p <- ggplot(df, aes(x = long, y = lat)) + annotation_map( map_data(\"state\"), fill = \"antiquewhite\", colour = \"darkgrey\" ) + geom_point(color = \"blue\") + geom_text( aes(label = name), hjust = 1.105, vjust = 1.05, color = \"blue\" ) # use without coord_sf() is possible but not recommended p + xlim(-84, -76) + ylim(34, 37.2) if (requireNamespace(\"sf\", quietly = TRUE)) { # use with coord_sf() for appropriate projection p + coord_sf( crs = sf::st_crs(3347), default_crs = sf::st_crs(4326), # data is provided as long-lat xlim = c(-84, -76), ylim = c(34, 37.2) ) # you can mix annotation_map() and geom_sf() nc <- sf::st_read(system.file(\"shape/nc.shp\", package = \"sf\"), quiet = TRUE) p + geom_sf( data = nc, inherit.aes = FALSE, fill = NA, color = \"black\", linewidth = 0.1 ) + coord_sf(crs = sf::st_crs(3347), default_crs = sf::st_crs(4326)) }}} # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: high-performance rectangular tiling — annotation_raster","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"special version geom_raster() optimised static annotations every panel. annotations affect scales (.e. x y axes grow cover range raster, raster must already colours). useful adding bitmap images.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"","code":"annotation_raster(raster, xmin, xmax, ymin, ymax, interpolate = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"raster raster object display, may array nativeRaster xmin, xmax x location (data coordinates) giving horizontal location raster ymin, ymax y location (data coordinates) giving vertical location raster interpolate TRUE interpolate linearly, FALSE (default) interpolate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"","code":"# Generate data rainbow <- matrix(hcl(seq(0, 360, length.out = 50 * 50), 80, 70), nrow = 50) ggplot(mtcars, aes(mpg, wt)) + geom_point() + annotation_raster(rainbow, 15, 20, 3, 4) # To fill up whole plot ggplot(mtcars, aes(mpg, wt)) + annotation_raster(rainbow, -Inf, Inf, -Inf, Inf) + geom_point() rainbow2 <- matrix(hcl(seq(0, 360, length.out = 10), 80, 70), nrow = 1) ggplot(mtcars, aes(mpg, wt)) + annotation_raster(rainbow2, -Inf, Inf, -Inf, Inf) + geom_point() rainbow2 <- matrix(hcl(seq(0, 360, length.out = 10), 80, 70), nrow = 1) ggplot(mtcars, aes(mpg, wt)) + annotation_raster(rainbow2, -Inf, Inf, -Inf, Inf, interpolate = TRUE) + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/as.list.ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Convert a ggproto object to a list — as.list.ggproto","title":"Convert a ggproto object to a list — as.list.ggproto","text":"include object's super member.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/as.list.ggproto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Convert a ggproto object to a list — as.list.ggproto","text":"","code":"# S3 method for class 'ggproto' as.list(x, inherit = TRUE, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/as.list.ggproto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Convert a ggproto object to a list — as.list.ggproto","text":"x ggproto object convert list. inherit TRUE (default), flatten inherited items returned list. FALSE, include inherited items. ... Arguments passed base::.list.environment .names logical indicating whether copy values (default) whose names begin dot. sorted logical indicating whether names resulting list sorted (increasingly). Note somewhat costly, may useful comparison environments.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":null,"dir":"Reference","previous_headings":"","what":"Coerce to labeller function — as_labeller","title":"Coerce to labeller function — as_labeller","text":"transforms objects labeller functions. Used internally labeller().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Coerce to labeller function — as_labeller","text":"","code":"as_labeller(x, default = label_value, multi_line = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Coerce to labeller function — as_labeller","text":"x Object coerce labeller function. named character vector, used lookup table passed default. non-labeller function, assumed takes returns character vectors applied labels. labeller, simply applied labels. default Default labeller process labels produced lookup tables modified non-labeller functions. multi_line Whether display labels multiple factors separate lines. passed labeller function.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Coerce to labeller function — as_labeller","text":"","code":"p <- ggplot(mtcars, aes(disp, drat)) + geom_point() p + facet_wrap(~am) # Rename labels on the fly with a lookup character vector to_string <- as_labeller(c(`0` = \"Zero\", `1` = \"One\")) p + facet_wrap(~am, labeller = to_string) # Quickly transform a function operating on character vectors to a # labeller function: appender <- function(string, suffix = \"-foo\") paste0(string, suffix) p + facet_wrap(~am, labeller = as_labeller(appender)) # If you have more than one faceting variable, be sure to dispatch # your labeller to the right variable with labeller() p + facet_grid(cyl ~ am, labeller = labeller(am = to_string))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a ggplot layer appropriate to a particular data type — autolayer","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"autolayer() uses ggplot2 draw particular layer object particular class single command. defines S3 generic classes packages can extend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"","code":"autolayer(object, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"object object, whose class determine behaviour autolayer ... arguments passed specific methods","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"ggplot layer","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":null,"dir":"Reference","previous_headings":"","what":"Tailoring plots to particular data types — automatic_plotting","title":"Tailoring plots to particular data types — automatic_plotting","text":"three functions make plotting particular data types easier: autoplot(), autolayer() fortify(). S3 generics packages can write methods display classes data. three functions complementary allow different levels customisation. explore implementing series methods automate plotting class. suppose writing packages class called 'my_heatmap', wraps matrix like users easily plot heatmap.","code":"my_heatmap <- function(...) { m <- matrix(...) class(m) <- c(\"my_heatmap\", class(m)) m } my_data <- my_heatmap(volcano)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":"automatic-data-shaping","dir":"Reference","previous_headings":"","what":"Automatic data shaping","title":"Tailoring plots to particular data types — automatic_plotting","text":"One things ensure data shaped long format compatible ggplot2. job fortify() function. 'my_heatmap' wraps matrix, can let fortify method 'melt' matrix long format. data already based long-format , can skip implementing fortify() method. implemented fortify() method, easier construct plot data matrix.","code":"fortify.my_heatmap <- function(model, ...) { data.frame( row = as.vector(row(model)), col = as.vector(col(model)), value = as.vector(model) ) } fortify(my_data) ggplot(my_data, aes(x = col, y = row, fill = value)) + geom_raster()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":"automatic-layers","dir":"Reference","previous_headings":"","what":"Automatic layers","title":"Tailoring plots to particular data types — automatic_plotting","text":"next step automating plotting data type write autolayer() method. typically wrappers around geoms stats automatically set aesthetics parameters. implemented fortify() method data type, might reshape data autolayer(). require multiple layers display data type, can use autolayer() method constructs list layers, can added plot. quick tip: define mapping autolayer(), might want set inherit.aes = FALSE aesthetics set layers interfere layer.","code":"autolayer.my_heatmap <- function(object, ...) { geom_raster( mapping = aes(x = col, y = row, fill = value), data = object, ..., inherit.aes = FALSE ) } ggplot() + autolayer(my_data)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":"automatic-plots","dir":"Reference","previous_headings":"","what":"Automatic plots","title":"Tailoring plots to particular data types — automatic_plotting","text":"last step automating plotting write autoplot() method data type. expectation return complete plot. example , exploiting autolayer() method already written make complete plot. wish implement base R plotting method, can set plot method class autoplot method.","code":"autoplot.my_heatmap <- function(object, ..., option = \"magma\") { ggplot() + autolayer(my_data) + scale_fill_viridis_c(option = option) + theme_void() } autoplot(my_data) plot.my_heatmap <- autoplot.my_heatmap plot(my_data)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a complete ggplot appropriate to a particular data type — autoplot","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"autoplot() uses ggplot2 draw particular plot object particular class single command. defines S3 generic classes packages can extend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"","code":"autoplot(object, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"object object, whose class determine behaviour autoplot ... arguments passed specific methods","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"ggplot object","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"Benchmark plot creation time. Broken construct, build, render draw times.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"","code":"benchplot(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"x code create ggplot2 plot","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"","code":"benchplot(ggplot(mtcars, aes(mpg, wt)) + geom_point()) #> step user.self sys.self elapsed #> 1 construct 0.002 0 0.002 #> 2 build 0.020 0 0.020 #> 3 render 0.020 0 0.020 #> 4 draw 0.020 0 0.021 #> 5 TOTAL 0.062 0 0.063 benchplot(ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl)) #> step user.self sys.self elapsed #> 1 construct 0.002 0 0.002 #> 2 build 0.021 0 0.021 #> 3 render 0.046 0 0.046 #> 4 draw 0.037 0 0.036 #> 5 TOTAL 0.106 0 0.105 # With tidy eval: p <- expr(ggplot(mtcars, aes(mpg, wt)) + geom_point()) benchplot(!!p) #> step user.self sys.self elapsed #> 1 construct 0.002 0 0.002 #> 2 build 0.019 0 0.019 #> 3 render 0.019 0 0.019 #> 4 draw 0.020 0 0.020 #> 5 TOTAL 0.060 0 0.060"},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":null,"dir":"Reference","previous_headings":"","what":"Utilities for working with bidirectional layers — bidirection","title":"Utilities for working with bidirectional layers — bidirection","text":"functions underpins ability certain geoms work automatically directions. See Extending ggplot2 vignette used implementing Geom, Stat, Position classes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Utilities for working with bidirectional layers — bidirection","text":"","code":"has_flipped_aes( data, params = list(), main_is_orthogonal = NA, range_is_orthogonal = NA, group_has_equal = FALSE, ambiguous = FALSE, main_is_continuous = FALSE, main_is_optional = FALSE, default = FALSE ) flip_data(data, flip = NULL) flipped_names(flip = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Utilities for working with bidirectional layers — bidirection","text":"data layer data params parameters Stat/Geom. orientation parameter used. main_is_orthogonal x y present correspond main orientation reverse. E.g. TRUE y present flipped. NA check ignored. range_is_orthogonal xmin/xmax ymin/ymax present correspond main orientation reverse. NA check ignored. group_has_equal expected grouped data either single x y value correspond orientation. ambiguous layer ambiguous mapping nature. , flipped params$orientation == \"y\" main_is_continuous discrete continuous axis, continuous one correspond main orientation? main_is_optional main axis aesthetic optional , given, set 0 default logical value return orientation can discerned data. flip Logical. layer flipped.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Utilities for working with bidirectional layers — bidirection","text":"has_flipped_aes() returns TRUE detects layer orientation FALSE otherwise. flip_data() return input unchanged flip = FALSE data flipped aesthetic names flip = TRUE. flipped_names() returns named list strings. flip = FALSE name element correspond element, e.g. flipped_names(FALSE)$x == \"x\" flip = TRUE correspond flipped name, e.g. flipped_names(FALSE)$x == \"y\"","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Utilities for working with bidirectional layers — bidirection","text":"has_flipped_aes() used sniff orientation layer data. range arguments can used finetune sniffing based data look like. flip_data() switch column names data looks like x-oriented data. flipped_names() provides named list aesthetic names corresponds orientation layer.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"controlling-the-sniffing","dir":"Reference","previous_headings":"","what":"Controlling the sniffing","title":"Utilities for working with bidirectional layers — bidirection","text":"layer data interpreted depends specific features. has_flipped_aes() contains range flags defining certain features data correspond : main_is_orthogonal: argument controls existence x y aesthetic understood. TRUE existing aesthetic secondary axis. behaviour present stat_ydensity() stat_boxplot(). FALSE existing aesthetic main axis seen e.g. stat_bin(), geom_count(), stat_density(). range_is_orthogonal: argument controls whether existence range-like aesthetics (e.g. xmin xmax) represents main secondary axis. TRUE range given secondary axis seen e.g. geom_ribbon() geom_linerange(). group_has_equal: argument controls whether test equality x y values inside group set main axis one equal. test performed TRUE, less computationally heavy tests come empty handed. Examples stat_boxplot() stat_ydensity ambiguous: argument tells function layer, bidirectional, treat axis differently. circumvent data based guessing take hint orientation element params. present fall back FALSE. Examples geom_line() geom_area() main_is_continuous: argument controls test discreteness scales interpreted. TRUE main axis one discrete-like. Conversely, FALSE main axis discrete-like one. Examples TRUE stat_density() stat_bin(), examples FALSE stat_ydensity() stat_boxplot() main_is_optional: argument controls rare case layers main direction optional aesthetic. seen stat_boxplot() x set 0 given. TRUE check whether x y equal 0","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/binned_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Binning scale constructor — binned_scale","title":"Binning scale constructor — binned_scale","text":"Binning scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/binned_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Binning scale constructor — binned_scale","text":"","code":"binned_scale( aesthetics, scale_name = deprecated(), palette, name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, rescaler = rescale, oob = squish, expand = waiver(), na.value = NA_real_, n.breaks = NULL, nice.breaks = TRUE, right = TRUE, transform = \"identity\", trans = deprecated(), show.limits = FALSE, guide = \"bins\", position = \"left\", call = caller_call(), super = ScaleBinned )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/binned_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Binning scale constructor — binned_scale","text":"aesthetics names aesthetics scale works . scale_name name scale used error messages associated scale. palette palette function called numeric vector values 0 1 returns corresponding output values (e.g., scales::pal_area()). name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::squish()) squishes bounds values range. scales::censor replacing bounds values NA. scales::squish_infinite() squishing infinite values range. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. na.value Missing values replaced value. n.breaks number break points create breaks given directly. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. right intervals closed right (TRUE, default) intervals closed left (FALSE)? 'Closed right' means values break positions part lower bin (open left), whereas part upper bin intervals closed left (open right). transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. show.limits limits scale appear ticks guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. call call used construct scale reporting messages. super super class use constructed scale","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a layer of map borders — borders","title":"Create a layer of map borders — borders","text":"quick dirty way get map data (maps package) onto plot. good place start need crude reference lines, typically want something sophisticated communication graphics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a layer of map borders — borders","text":"","code":"borders( database = \"world\", regions = \".\", fill = NA, colour = \"grey50\", xlim = NULL, ylim = NULL, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a layer of map borders — borders","text":"database map data, see maps::map() details regions map region fill fill colour colour border colour xlim, ylim latitudinal longitudinal ranges extracting map polygons, see maps::map() details. ... Arguments passed geom_polygon rule Either \"evenodd\" \"winding\". polygons holes drawn (using subgroup aesthetic) argument defines hole coordinates interpreted. See examples grid::pathGrob() explanation. mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a layer of map borders — borders","text":"","code":"if (require(\"maps\")) { ia <- map_data(\"county\", \"iowa\") mid_range <- function(x) mean(range(x)) seats <- do.call(rbind, lapply(split(ia, ia$subregion), function(d) { data.frame(lat = mid_range(d$lat), long = mid_range(d$long), subregion = unique(d$subregion)) })) ggplot(ia, aes(long, lat)) + geom_polygon(aes(group = group), fill = NA, colour = \"grey60\") + geom_text(aes(label = subregion), data = seats, size = 2, angle = 45) } #> Loading required package: maps if (require(\"maps\")) { data(us.cities) capitals <- subset(us.cities, capital == 2) ggplot(capitals, aes(long, lat)) + borders(\"state\") + geom_point(aes(size = pop)) + scale_size_area() + coord_quickmap() } if (require(\"maps\")) { # Same map, with some world context ggplot(capitals, aes(long, lat)) + borders(\"world\", xlim = c(-130, -60), ylim = c(20, 50)) + geom_point(aes(size = pop)) + scale_size_area() + coord_quickmap() }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate the element properties, by inheriting properties from its parents — calc_element","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"Calculate element properties, inheriting properties parents","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"","code":"calc_element( element, theme, verbose = FALSE, skip_blank = FALSE, call = caller_env() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"element name theme element calculate theme theme object (like theme_grey()) verbose TRUE, print elements one inherits skip_blank TRUE, elements type element_blank inheritance hierarchy ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"","code":"t <- theme_grey() calc_element('text', t) #> List of 11 #> $ family : chr \"\" #> $ face : chr \"plain\" #> $ colour : chr \"black\" #> $ size : num 11 #> $ hjust : num 0.5 #> $ vjust : num 0.5 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 0points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" # Compare the \"raw\" element definition to the element with calculated inheritance t$axis.text.x #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : NULL #> $ size : NULL #> $ hjust : NULL #> $ vjust : num 1 #> $ angle : NULL #> $ lineheight : NULL #> $ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : NULL #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" calc_element('axis.text.x', t, verbose = TRUE) #> axis.text.x --> #> axis.text #> axis.text --> #> text #> text --> #> nothing (top level) #> List of 11 #> $ family : chr \"\" #> $ face : chr \"plain\" #> $ colour : chr \"grey30\" #> $ size : num 8.8 #> $ hjust : num 0.5 #> $ vjust : num 1 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" # This reports that axis.text.x inherits from axis.text, # which inherits from text. You can view each of them with: t$axis.text.x #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : NULL #> $ size : NULL #> $ hjust : NULL #> $ vjust : num 1 #> $ angle : NULL #> $ lineheight : NULL #> $ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : NULL #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" t$axis.text #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : chr \"grey30\" #> $ size : 'rel' num 0.8 #> $ hjust : NULL #> $ vjust : NULL #> $ angle : NULL #> $ lineheight : NULL #> $ margin : NULL #> $ debug : NULL #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" t$text #> List of 11 #> $ family : chr \"\" #> $ face : chr \"plain\" #> $ colour : chr \"black\" #> $ size : num 11 #> $ hjust : num 0.5 #> $ vjust : num 0.5 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 0points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":null,"dir":"Reference","previous_headings":"","what":"Check graphics device capabilities — check_device","title":"Check graphics device capabilities — check_device","text":"function makes attempt estimate whether graphics device able render newer graphics features.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Check graphics device capabilities — check_device","text":"","code":"check_device( feature, action = \"warn\", op = NULL, maybe = FALSE, call = caller_env() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Check graphics device capabilities — check_device","text":"feature string naming graphics device feature. One : \"clippingPaths\", \"alpha_masks\", \"lumi_masks\", \"compositing\", \"blending\", \"transformations\", \"gradients\", \"patterns\", \"paths\" \"glyphs\". See 'Features' section explanation terms. action string action take. One : \"test\" returns TRUE FALSE indicating support feature. \"warn\" also returns logical, throws informative warning FALSE. \"abort\" throws error device estimated support feature. op string specific operation test feature either \"blending\" \"compositing\". NULL (default), support known blending compositing operations queried. maybe logical length 1 determining return value case device capabilities assessed. current device 'null device', maybe returned. call execution environment currently running function, e.g. caller_env(). function mentioned warnings error messages source warning error. See call argument abort() information.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Check graphics device capabilities — check_device","text":"TRUE feature thought supported FALSE otherwise.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Check graphics device capabilities — check_device","text":"procedure testing follows: First, R version checked version wherein feature introduced. Next, dev.capabilities() function queried support feature. check ambiguous, svglite ragg devices checked known support. Lastly, answer yet, checked whether device one 'known' devices supports feature.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"features","dir":"Reference","previous_headings":"","what":"Features","title":"Check graphics device capabilities — check_device","text":"\"clippingPaths\" devices support rectangular clipping regions, feature support clipping arbitrary paths. can used display part drawing. \"alpha_masks\" Like clipping regions paths, alpha masks can also used display part drawing. particular semi-transparent mask can used display drawing opaque parts mask hide drawing transparent part mask. \"lumi_masks Similar alpha masks, using mask's luminance (greyscale value) determine drawn. Light values opaque dark values transparent. \"compositing\" Compositing allows one control drawings drawn relation one another. default, one drawing drawn '' previous one, operators possible, like 'clear', '' ''. \"blending\" placing one drawing atop another, blend mode determines colours drawings relate one another. \"transformations\" Performing affine transformation group can used translate, rotate, scale, shear flip drawing. \"gradients\" Gradients can used show transition two colours fill drawing. checks expects linear radial gradients supported. \"patterns\" Patterns can used display repeated, tiled drawing fill another drawing. \"paths\" Contrary 'paths' polyline polygon drawings, \"paths\" refers ability fill stroke collections drawings. \"glyphs\" Refers advanced typesetting feature controlling appearance individual glyphs.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"limitations","dir":"Reference","previous_headings":"","what":"Limitations","title":"Check graphics device capabilities — check_device","text":"Windows machines, bitmap devices png() jpeg() default type = \"windows\". time writing, support new features, contrast type = \"cairo\", . Prior R version 4.2.0, capabilities resolved value maybe argument returned. exception ragg svglite devices, device report capabilities via dev.capabilities(), R version 4.2.0, maybe value returned. Even though patterns gradients introduced R 4.1.0, considered unsupported providing vectorised patterns gradients introduced later R 4.2.0. using RStudio graphics device, back end assumed next device list. assumption typically met default, unless device list purposefully rearranged.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Check graphics device capabilities — check_device","text":"","code":"# Typically you'd run `check_device()` inside a function that might produce # advanced graphics. # The check is designed for use in control flow statements in the test mode if (check_device(\"patterns\", action = \"test\")) { print(\"Yay\") } else { print(\"Nay\") } #> [1] \"Yay\" # Automatically throw a warning when unavailable if (check_device(\"compositing\", action = \"warn\")) { print(\"Yay\") } else { print(\"Nay\") } #> Warning: The agg_png device does not support compositing. #> [1] \"Nay\" # Possibly throw an error try(check_device(\"glyphs\", action = \"abort\")) #> [1] TRUE"},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":null,"dir":"Reference","previous_headings":"","what":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"Take input data define mapping faceting variables ROW, COL PANEL keys","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"","code":"combine_vars(data, env = emptyenv(), vars = NULL, drop = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"data list data.frames, first plot data subsequent individual layer data env environment vars evaluated vars list quoted symbols matching columns data drop missing combinations/levels dropped","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"data.frame columns PANEL, ROW, COL, faceting vars","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Complete a theme — complete_theme","title":"Complete a theme — complete_theme","text":"function takes theme completes can used downstream render theme elements. Missing elements filled every item validated specifications element tree.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Complete a theme — complete_theme","text":"","code":"complete_theme(theme = NULL, default = theme_get())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Complete a theme — complete_theme","text":"theme incomplete theme object complete, NULL complete default theme. default complete theme fill missing pieces. Defaults global theme settings.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Complete a theme — complete_theme","text":"theme object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Complete a theme — complete_theme","text":"","code":"my_theme <- theme(line = element_line(colour = \"red\")) complete_theme(my_theme) #> List of 139 #> $ line :List of 7 #> ..$ colour : chr \"red\" #> ..$ linewidth : num 0.5 #> ..$ linetype : num 1 #> ..$ lineend : chr \"butt\" #> ..$ arrow : logi FALSE #> ..$ arrow.fill : chr \"red\" #> ..$ inherit.blank: logi FALSE #> ..- attr(*, \"class\")= chr [1:2] \"element_line\" \"element\" #> $ rect :List of 5 #> ..$ fill : chr \"white\" #> ..$ colour : chr \"black\" #> ..$ linewidth : num 0.5 #> ..$ linetype : num 1 #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\" #> $ text :List of 11 #> ..$ family : chr \"\" #> ..$ face : chr \"plain\" #> ..$ colour : chr \"black\" #> ..$ size : num 11 #> ..$ hjust : num 0.5 #> ..$ vjust : num 0.5 #> ..$ angle : num 0 #> ..$ lineheight : num 0.9 #> ..$ margin : 'margin' num [1:4] 0points 0points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : logi FALSE #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ title :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ geom :List of 12 #> ..$ ink : chr \"black\" #> ..$ paper : chr \"white\" #> ..$ accent : chr \"#3366FF\" #> ..$ linewidth : num 0.5 #> ..$ borderwidth : num 0.5 #> ..$ linetype : int 1 #> ..$ bordertype : int 1 #> ..$ family : chr \"\" #> ..$ fontsize : num 3.87 #> ..$ pointsize : num 1.5 #> ..$ pointshape : num 19 #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_geom\" \"element\" #> $ spacing : 'simpleUnit' num 5.5points #> ..- attr(*, \"unit\")= int 8 #> $ margins : 'margin' num [1:4] 5.5points 5.5points 5.5points 5.5points #> ..- attr(*, \"unit\")= int 8 #> $ aspect.ratio : NULL #> $ axis.title : NULL #> $ axis.title.x :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 2.75points 0points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.title.x.top :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 0 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 2.75points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.title.x.bottom : NULL #> $ axis.title.y :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : num 90 #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 2.75points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.title.y.left : NULL #> $ axis.title.y.right :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : num -90 #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 0points 2.75points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : chr \"grey30\" #> ..$ size : 'rel' num 0.8 #> ..$ hjust : NULL #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.x :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.x.top :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 0 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 2.2points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.x.bottom : NULL #> $ axis.text.y :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 1 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 2.2points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.y.left : NULL #> $ axis.text.y.right :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 0 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 0points 2.2points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.theta : NULL #> $ axis.text.r :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 0.5 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 2.2points 0points 2.2points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.ticks :List of 7 #> ..$ colour : chr \"grey20\" #> ..$ linewidth : NULL #> ..$ linetype : NULL #> ..$ lineend : NULL #> ..$ arrow : logi FALSE #> ..$ arrow.fill : chr \"grey20\" #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_line\" \"element\" #> $ axis.ticks.x : NULL #> $ axis.ticks.x.top : NULL #> $ axis.ticks.x.bottom : NULL #> $ axis.ticks.y : NULL #> $ axis.ticks.y.left : NULL #> $ axis.ticks.y.right : NULL #> $ axis.ticks.theta : NULL #> $ axis.ticks.r : NULL #> $ axis.minor.ticks.x.top : NULL #> $ axis.minor.ticks.x.bottom : NULL #> $ axis.minor.ticks.y.left : NULL #> $ axis.minor.ticks.y.right : NULL #> $ axis.minor.ticks.theta : NULL #> $ axis.minor.ticks.r : NULL #> $ axis.ticks.length : 'rel' num 0.5 #> $ axis.ticks.length.x : NULL #> $ axis.ticks.length.x.top : NULL #> $ axis.ticks.length.x.bottom : NULL #> $ axis.ticks.length.y : NULL #> $ axis.ticks.length.y.left : NULL #> $ axis.ticks.length.y.right : NULL #> $ axis.ticks.length.theta : NULL #> $ axis.ticks.length.r : NULL #> $ axis.minor.ticks.length : 'rel' num 0.75 #> $ axis.minor.ticks.length.x : NULL #> $ axis.minor.ticks.length.x.top : NULL #> $ axis.minor.ticks.length.x.bottom: NULL #> $ axis.minor.ticks.length.y : NULL #> $ axis.minor.ticks.length.y.left : NULL #> $ axis.minor.ticks.length.y.right : NULL #> $ axis.minor.ticks.length.theta : NULL #> $ axis.minor.ticks.length.r : NULL #> $ axis.line : list() #> ..- attr(*, \"class\")= chr [1:2] \"element_blank\" \"element\" #> $ axis.line.x : NULL #> $ axis.line.x.top : NULL #> $ axis.line.x.bottom : NULL #> $ axis.line.y : NULL #> $ axis.line.y.left : NULL #> $ axis.line.y.right : NULL #> $ axis.line.theta : NULL #> $ axis.line.r : NULL #> $ legend.background :List of 5 #> ..$ fill : NULL #> ..$ colour : logi NA #> ..$ linewidth : NULL #> ..$ linetype : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\" #> $ legend.margin : NULL #> $ legend.spacing : 'rel' num 2 #> $ legend.spacing.x : NULL #> $ legend.spacing.y : NULL #> $ legend.key : NULL #> $ legend.key.size : 'simpleUnit' num 1.2lines #> ..- attr(*, \"unit\")= int 3 #> $ legend.key.height : NULL #> $ legend.key.width : NULL #> $ legend.key.spacing : NULL #> $ legend.key.spacing.x : NULL #> $ legend.key.spacing.y : NULL #> $ legend.frame : NULL #> $ legend.ticks : NULL #> $ legend.ticks.length : 'rel' num 0.2 #> $ legend.axis.line : NULL #> $ legend.text :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : 'rel' num 0.8 #> ..$ hjust : NULL #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ legend.text.position : NULL #> $ legend.title :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 0 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ legend.title.position : NULL #> $ legend.position : chr \"right\" #> $ legend.position.inside : NULL #> $ legend.direction : NULL #> $ legend.byrow : NULL #> $ legend.justification : chr \"center\" #> $ legend.justification.top : NULL #> $ legend.justification.bottom : NULL #> $ legend.justification.left : NULL #> $ legend.justification.right : NULL #> $ legend.justification.inside : NULL #> $ legend.location : NULL #> $ legend.box : NULL #> $ legend.box.just : NULL #> [list output truncated] #> - attr(*, \"class\")= chr [1:2] \"theme\" \"gg\" #> - attr(*, \"complete\")= logi TRUE #> - attr(*, \"validate\")= logi FALSE"},{"path":"https://ggplot2.tidyverse.org/dev/reference/continuous_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Continuous scale constructor — continuous_scale","title":"Continuous scale constructor — continuous_scale","text":"Continuous scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/continuous_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Continuous scale constructor — continuous_scale","text":"","code":"continuous_scale( aesthetics, scale_name = deprecated(), palette, name = waiver(), breaks = waiver(), minor_breaks = waiver(), n.breaks = NULL, labels = waiver(), limits = NULL, rescaler = rescale, oob = censor, expand = waiver(), na.value = NA_real_, transform = \"identity\", trans = deprecated(), guide = \"legend\", position = \"left\", call = caller_call(), super = ScaleContinuous )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/continuous_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Continuous scale constructor — continuous_scale","text":"aesthetics names aesthetics scale works . scale_name name scale used error messages associated scale. palette palette function called numeric vector values 0 1 returns corresponding output values (e.g., scales::pal_area()). name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. na.value Missing values replaced value. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. call call used construct scale reporting messages. super super class use constructed scale","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":null,"dir":"Reference","previous_headings":"","what":"Cartesian coordinates — coord_cartesian","title":"Cartesian coordinates — coord_cartesian","text":"Cartesian coordinate system familiar, common, type coordinate system. Setting limits coordinate system zoom plot (like looking magnifying glass), change underlying data like setting limits scale .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cartesian coordinates — coord_cartesian","text":"","code":"coord_cartesian( xlim = NULL, ylim = NULL, expand = TRUE, default = FALSE, clip = \"on\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cartesian coordinates — coord_cartesian","text":"xlim, ylim Limits x y axes. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. default default coordinate system? FALSE (default), replacing coordinate system another one creates message alerting user coordinate system replaced. TRUE, warning suppressed. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cartesian coordinates — coord_cartesian","text":"","code":"# There are two ways of zooming the plot display: with scales or # with coordinate systems. They work in two rather different ways. p <- ggplot(mtcars, aes(disp, wt)) + geom_point() + geom_smooth() p #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Setting the limits on a scale converts all values outside the range to NA. p + scale_x_continuous(limits = c(325, 500)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' #> Warning: Removed 24 rows containing non-finite outside the scale range #> (`stat_smooth()`). #> Warning: Removed 24 rows containing missing values or values outside the scale #> range (`geom_point()`). # Setting the limits on the coordinate system performs a visual zoom. # The data is unchanged, and we just view a small portion of the original # plot. Note how smooth continues past the points visible on this plot. p + coord_cartesian(xlim = c(325, 500)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # By default, the same expansion factor is applied as when setting scale # limits. You can set the limits precisely by setting expand = FALSE p + coord_cartesian(xlim = c(325, 500), expand = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Similarly, we can use expand = FALSE to turn off expansion with the # default limits p + coord_cartesian(expand = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # You can see the same thing with this 2d histogram d <- ggplot(diamonds, aes(carat, price)) + stat_bin_2d(bins = 25, colour = \"white\") d # When zooming the scale, the we get 25 new bins that are the same # size on the plot, but represent smaller regions of the data space d + scale_x_continuous(limits = c(0, 1)) #> Warning: Removed 17502 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 17 rows containing missing values or values outside the scale #> range (`geom_tile()`). # When zooming the coordinate system, we see a subset of original 50 bins, # displayed bigger d + coord_cartesian(xlim = c(0, 1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":null,"dir":"Reference","previous_headings":"","what":"Cartesian coordinates with fixed ","title":"Cartesian coordinates with fixed ","text":"fixed scale coordinate system forces specified ratio physical representation data units axes. ratio represents number units y-axis equivalent one unit x-axis. default, ratio = 1, ensures one unit x-axis length one unit y-axis. Ratios higher one make units y axis longer units x-axis, vice versa. similar MASS::eqscplot(), works types graphics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cartesian coordinates with fixed ","text":"","code":"coord_fixed(ratio = 1, xlim = NULL, ylim = NULL, expand = TRUE, clip = \"on\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cartesian coordinates with fixed ","text":"ratio aspect ratio, expressed y / x xlim, ylim Limits x y axes. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cartesian coordinates with fixed ","text":"","code":"# ensures that the ranges of axes are equal to the specified ratio by # adjusting the plot aspect ratio p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p + coord_fixed(ratio = 1) p + coord_fixed(ratio = 5) p + coord_fixed(ratio = 1/5) p + coord_fixed(xlim = c(15, 30)) # Resize the plot to see that the specified aspect ratio is maintained"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":null,"dir":"Reference","previous_headings":"","what":"Cartesian coordinates with x and y flipped — coord_flip","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"function superseded many cases, coord_flip() can easily replaced swapping x y aesthetics, optionally setting orientation argument geom stat layers. coord_flip() useful geoms statistics support orientation setting, converting display y conditional x, x conditional y.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"","code":"coord_flip(xlim = NULL, ylim = NULL, expand = TRUE, clip = \"on\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"xlim, ylim Limits x y axes. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"Coordinate systems interact many parts plotting system. can expect following coord_flip(): change facet order facet_grid() facet_wrap(). scale_x_*() functions apply vertical direction, whereas scale_y_*() functions apply horizontal direction. holds xlim ylim arguments coord_flip() xlim() ylim() functions. x-axis theme settings, axis.line.x apply horizontal direction. y-axis theme settings, axis.text.y apply vertical direction.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"","code":"# The preferred method of creating horizontal instead of vertical boxplots ggplot(diamonds, aes(price, cut)) + geom_boxplot() # Using `coord_flip()` to make the same plot ggplot(diamonds, aes(cut, price)) + geom_boxplot() + coord_flip() # With swapped aesthetics, the y-scale controls the left axis ggplot(diamonds, aes(y = carat)) + geom_histogram() + scale_y_reverse() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # In `coord_flip()`, the x-scale controls the left axis ggplot(diamonds, aes(carat)) + geom_histogram() + coord_flip() + scale_x_reverse() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # In line and area plots, swapped aesthetics require an explicit orientation df <- data.frame(a = 1:5, b = (1:5) ^ 2) ggplot(df, aes(b, a)) + geom_area(orientation = \"y\") # The same plot with `coord_flip()` ggplot(df, aes(a, b)) + geom_area() + coord_flip()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":null,"dir":"Reference","previous_headings":"","what":"Map projections — coord_map","title":"Map projections — coord_map","text":"coord_map() projects portion earth, approximately spherical, onto flat 2D plane using projection defined mapproj package. Map projections , general, preserve straight lines, requires considerable computation. coord_quickmap() quick approximation preserve straight lines. works best smaller areas closer equator. coord_map() coord_quickmap() superseded coord_sf(), longer used new code. regular (non-sf) geoms can used coord_sf() setting default coordinate system via default_crs argument. See also examples annotation_map() geom_map().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Map projections — coord_map","text":"","code":"coord_map( projection = \"mercator\", ..., parameters = NULL, orientation = NULL, xlim = NULL, ylim = NULL, clip = \"on\" ) coord_quickmap(xlim = NULL, ylim = NULL, expand = TRUE, clip = \"on\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Map projections — coord_map","text":"projection projection use, see mapproj::mapproject() list ..., parameters arguments passed mapproj::mapproject(). Use ... named parameters projection, parameters unnamed parameters. ... ignored parameters argument present. orientation projection orientation, defaults c(90, 0, mean(range(x))). optimal many projections, supply . See mapproj::mapproject() information. xlim, ylim Manually specific x/y limits (degrees longitude/latitude) clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . details, please see coord_cartesian(). expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Map projections — coord_map","text":"Map projections must account fact actual length (km) one degree longitude varies equator pole. Near equator, ratio lengths one degree latitude one degree longitude approximately 1. Near pole, tends towards infinity length one degree longitude tends towards 0. regions span degrees close poles, setting aspect ratio plot appropriate lat/lon ratio approximates usual mercator projection. coord_quickmap() , much faster (particularly complex plots like geom_tile()) expense correctness.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Map projections — coord_map","text":"","code":"if (require(\"maps\")) { nz <- map_data(\"nz\") # Prepare a map of NZ nzmap <- ggplot(nz, aes(x = long, y = lat, group = group)) + geom_polygon(fill = \"white\", colour = \"black\") # Plot it in cartesian coordinates nzmap } if (require(\"maps\")) { # With correct mercator projection nzmap + coord_map() } if (require(\"maps\")) { # With the aspect ratio approximation nzmap + coord_quickmap() } if (require(\"maps\")) { # Other projections nzmap + coord_map(\"azequalarea\", orientation = c(-36.92, 174.6, 0)) } if (require(\"maps\")) { states <- map_data(\"state\") usamap <- ggplot(states, aes(long, lat, group = group)) + geom_polygon(fill = \"white\", colour = \"black\") # Use cartesian coordinates usamap } if (require(\"maps\")) { # With mercator projection usamap + coord_map() } if (require(\"maps\")) { # See ?mapproject for coordinate systems and their parameters usamap + coord_map(\"gilbert\") } if (require(\"maps\")) { # For most projections, you'll need to set the orientation yourself # as the automatic selection done by mapproject is not available to # ggplot usamap + coord_map(\"orthographic\") } if (require(\"maps\")) { usamap + coord_map(\"conic\", lat0 = 30) } if (require(\"maps\")) { usamap + coord_map(\"bonne\", lat0 = 50) } if (FALSE) { # \\dontrun{ if (require(\"maps\")) { # World map, using geom_path instead of geom_polygon world <- map_data(\"world\") worldmap <- ggplot(world, aes(x = long, y = lat, group = group)) + geom_path() + scale_y_continuous(breaks = (-2:2) * 30) + scale_x_continuous(breaks = (-4:4) * 45) # Orthographic projection with default orientation (looking down at North pole) worldmap + coord_map(\"ortho\") } if (require(\"maps\")) { # Looking up up at South Pole worldmap + coord_map(\"ortho\", orientation = c(-90, 0, 0)) } if (require(\"maps\")) { # Centered on New York (currently has issues with closing polygons) worldmap + coord_map(\"ortho\", orientation = c(41, -74, 0)) } } # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_munch.html","id":null,"dir":"Reference","previous_headings":"","what":"Munch coordinates data — coord_munch","title":"Munch coordinates data — coord_munch","text":"function \"munches\" lines, dividing line many small pieces can transformed independently. Used inside geom functions.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_munch.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Munch coordinates data — coord_munch","text":"","code":"coord_munch(coord, data, range, segment_length = 0.01, is_closed = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_munch.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Munch coordinates data — coord_munch","text":"coord Coordinate system definition. data Data set transform - variables x y chopped small pieces (defined group). variables duplicated needed. range Panel range specification. segment_length Target segment length is_closed Whether data considered closed polygon.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":null,"dir":"Reference","previous_headings":"","what":"Polar coordinates — coord_polar","title":"Polar coordinates — coord_polar","text":"polar coordinate system commonly used pie charts, stacked bar chart polar coordinates. coord_radial() extended options.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Polar coordinates — coord_polar","text":"","code":"coord_polar(theta = \"x\", start = 0, direction = 1, clip = \"on\") coord_radial( theta = \"x\", start = 0, end = NULL, expand = TRUE, direction = 1, clip = \"off\", r.axis.inside = NULL, rotate.angle = FALSE, inner.radius = 0, r_axis_inside = deprecated(), rotate_angle = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Polar coordinates — coord_polar","text":"theta variable map angle (x y) start Offset starting point 12 o'clock radians. Offset applied clockwise anticlockwise depending value direction. direction 1, clockwise; -1, anticlockwise clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . details, please see coord_cartesian(). end Position 12 o'clock radians plot ends, allow partial polar coordinates. default, NULL, set start + 2 * pi. expand TRUE, default, adds small expansion factor limits prevent overlap data axes. FALSE, limits taken directly scale. r.axis.inside One following: NULL (default) places axis next panel start end arguments form full circle inside panel otherwise. TRUE place radius axis inside panel. FALSE place radius axis next panel. numeric value, setting theta axis value axis placed inside panel. Can given length 2 vector control primary secondary axis placement separately. rotate.angle TRUE, transforms angle aesthetic data accordance computed theta position. FALSE (default), transformation performed. Can useful rotate text geoms alignment coordinates. inner.radius numeric 0 1 setting size inner.radius hole. r_axis_inside, rotate_angle","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Polar coordinates — coord_polar","text":"coord_radial(), position guides can defined using guides(r = ..., theta = ..., r.sec = ..., theta.sec = ...). Note guides require r theta available aesthetics. classic guide_axis() can used r positions guide_axis_theta() can used theta positions. Using theta.sec position sensible inner.radius > 0.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Polar coordinates — coord_polar","text":"","code":"# NOTE: Use these plots with caution - polar coordinates has # major perceptual problems. The main point of these examples is # to demonstrate how these common plots can be described in the # grammar. Use with EXTREME caution. #' # A pie chart = stacked bar chart + polar coordinates pie <- ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) + geom_bar(width = 1) pie + coord_polar(theta = \"y\") # \\donttest{ # A coxcomb plot = bar chart + polar coordinates cxc <- ggplot(mtcars, aes(x = factor(cyl))) + geom_bar(width = 1, colour = \"black\") cxc + coord_polar() # A new type of plot? cxc + coord_polar(theta = \"y\") # The bullseye chart pie + coord_polar() # Hadley's favourite pie chart df <- data.frame( variable = c(\"does not resemble\", \"resembles\"), value = c(20, 80) ) ggplot(df, aes(x = \"\", y = value, fill = variable)) + geom_col(width = 1) + scale_fill_manual(values = c(\"red\", \"yellow\")) + coord_polar(\"y\", start = pi / 3) + labs(title = \"Pac man\") # Windrose + doughnut plot if (require(\"ggplot2movies\")) { movies$rrating <- cut_interval(movies$rating, length = 1) movies$budgetq <- cut_number(movies$budget, 4) doh <- ggplot(movies, aes(x = rrating, fill = budgetq)) # Wind rose doh + geom_bar(width = 1) + coord_polar() # Race track plot doh + geom_bar(width = 0.9, position = \"fill\") + coord_polar(theta = \"y\") } #> Loading required package: ggplot2movies # } # A partial polar plot ggplot(mtcars, aes(disp, mpg)) + geom_point() + coord_radial(start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":null,"dir":"Reference","previous_headings":"","what":"Transformed Cartesian coordinate system — coord_trans","title":"Transformed Cartesian coordinate system — coord_trans","text":"coord_trans() different scale transformations occurs statistical transformation affect visual appearance geoms - guarantee straight lines continue straight.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Transformed Cartesian coordinate system — coord_trans","text":"","code":"coord_trans( x = \"identity\", y = \"identity\", xlim = NULL, ylim = NULL, limx = deprecated(), limy = deprecated(), clip = \"on\", expand = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Transformed Cartesian coordinate system — coord_trans","text":"x, y Transformers x y axes names. xlim, ylim Limits x y axes. limx, limy use xlim ylim instead. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Transformed Cartesian coordinate system — coord_trans","text":"Transformations work continuous values: see scales::new_transform() list transformations, instructions create .","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Transformed Cartesian coordinate system — coord_trans","text":"","code":"# \\donttest{ # See ?geom_boxplot for other examples # Three ways of doing transformation in ggplot: # * by transforming the data ggplot(diamonds, aes(log10(carat), log10(price))) + geom_point() # * by transforming the scales ggplot(diamonds, aes(carat, price)) + geom_point() + scale_x_log10() + scale_y_log10() # * by transforming the coordinate system: ggplot(diamonds, aes(carat, price)) + geom_point() + coord_trans(x = \"log10\", y = \"log10\") # The difference between transforming the scales and # transforming the coordinate system is that scale # transformation occurs BEFORE statistics, and coordinate # transformation afterwards. Coordinate transformation also # changes the shape of geoms: d <- subset(diamonds, carat > 0.5) ggplot(d, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") + scale_x_log10() + scale_y_log10() #> `geom_smooth()` using formula = 'y ~ x' ggplot(d, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") + coord_trans(x = \"log10\", y = \"log10\") #> `geom_smooth()` using formula = 'y ~ x' # Here I used a subset of diamonds so that the smoothed line didn't # drop below zero, which obviously causes problems on the log-transformed # scale # With a combination of scale and coordinate transformation, it's # possible to do back-transformations: ggplot(diamonds, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") + scale_x_log10() + scale_y_log10() + coord_trans(x = scales::transform_exp(10), y = scales::transform_exp(10)) #> `geom_smooth()` using formula = 'y ~ x' #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced # cf. ggplot(diamonds, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") #> `geom_smooth()` using formula = 'y ~ x' # Also works with discrete scales set.seed(1) df <- data.frame(a = abs(rnorm(26)),letters) plot <- ggplot(df,aes(a,letters)) + geom_point() plot + coord_trans(x = \"log10\") plot + coord_trans(x = \"sqrt\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":null,"dir":"Reference","previous_headings":"","what":"Discretise numeric data into categorical — cut_interval","title":"Discretise numeric data into categorical — cut_interval","text":"cut_interval() makes n groups equal range, cut_number() makes n groups (approximately) equal numbers observations; cut_width() makes groups width width.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discretise numeric data into categorical — cut_interval","text":"","code":"cut_interval(x, n = NULL, length = NULL, ...) cut_number(x, n = NULL, ...) cut_width(x, width, center = NULL, boundary = NULL, closed = \"right\", ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discretise numeric data into categorical — cut_interval","text":"x numeric vector n number intervals create, length length interval ... Arguments passed base::cut.default breaks either numeric vector two unique cut points single number (greater equal 2) giving number intervals x cut. labels labels levels resulting category. default, labels constructed using \"(,b]\" interval notation. labels = FALSE, simple integer codes returned instead factor. right logical, indicating intervals closed right (open left) vice versa. dig.lab integer used labels given. determines number digits used formatting break numbers. ordered_result logical: result ordered factor? width bin width. center, boundary Specify either position edge center bin. Since bins aligned, specifying position single bin (need range data) affects location bins. specified, uses \"tile layers algorithm\", sets boundary half binwidth. center integers, width = 1 center = 0. boundary = 0.5. closed One \"right\" \"left\" indicating whether right left edges bins included bin.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"Discretise numeric data into categorical — cut_interval","text":"Randall Prium contributed implementation cut_width().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Discretise numeric data into categorical — cut_interval","text":"","code":"table(cut_interval(1:100, 10)) #> #> [1,10.9] (10.9,20.8] (20.8,30.7] (30.7,40.6] (40.6,50.5] (50.5,60.4] #> 10 10 10 10 10 10 #> (60.4,70.3] (70.3,80.2] (80.2,90.1] (90.1,100] #> 10 10 10 10 table(cut_interval(1:100, 11)) #> #> [1,10] (10,19] (19,28] (28,37] (37,46] (46,55] (55,64] (64,73] #> 10 9 9 9 9 9 9 9 #> (73,82] (82,91] (91,100] #> 9 9 9 set.seed(1) table(cut_number(runif(1000), 10)) #> #> [0.00131,0.105] (0.105,0.201] (0.201,0.312] (0.312,0.398] #> 100 100 100 100 #> (0.398,0.483] (0.483,0.596] (0.596,0.706] (0.706,0.797] #> 100 100 100 100 #> (0.797,0.91] (0.91,1] #> 100 100 table(cut_width(runif(1000), 0.1)) #> #> [-0.05,0.05] (0.05,0.15] (0.15,0.25] (0.25,0.35] (0.35,0.45] #> 59 109 103 96 110 #> (0.45,0.55] (0.55,0.65] (0.65,0.75] (0.75,0.85] (0.85,0.95] #> 85 89 86 113 97 #> (0.95,1.05] #> 53 table(cut_width(runif(1000), 0.1, boundary = 0)) #> #> [0,0.1] (0.1,0.2] (0.2,0.3] (0.3,0.4] (0.4,0.5] (0.5,0.6] (0.6,0.7] #> 106 106 108 100 99 107 84 #> (0.7,0.8] (0.8,0.9] (0.9,1] #> 96 95 99 table(cut_width(runif(1000), 0.1, center = 0)) #> #> [-0.05,0.05] (0.05,0.15] (0.15,0.25] (0.25,0.35] (0.35,0.45] #> 72 104 80 104 100 #> (0.45,0.55] (0.55,0.65] (0.65,0.75] (0.75,0.85] (0.85,0.95] #> 91 94 75 115 110 #> (0.95,1.05] #> 55 table(cut_width(runif(1000), 0.1, labels = FALSE)) #> #> 1 2 3 4 5 6 7 8 9 10 11 #> 49 92 100 98 112 102 88 89 97 116 57"},{"path":"https://ggplot2.tidyverse.org/dev/reference/datetime_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Date/time scale constructor — datetime_scale","title":"Date/time scale constructor — datetime_scale","text":"Date/time scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/datetime_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Date/time scale constructor — datetime_scale","text":"","code":"datetime_scale( aesthetics, transform, trans = deprecated(), palette, breaks = pretty_breaks(), minor_breaks = waiver(), labels = waiver(), date_breaks = waiver(), date_labels = waiver(), date_minor_breaks = waiver(), timezone = NULL, guide = \"legend\", call = caller_call(), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/datetime_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Date/time scale constructor — datetime_scale","text":"aesthetics names aesthetics scale works . transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans date/time scales, name date/time transformation object . Built-transformations include \"hms\", \"date\" \"time\". palette palette function called numeric vector values 0 1 returns corresponding output values (e.g., scales::pal_area()). breaks One : NULL breaks waiver() breaks specified date_breaks Date/POSIXct vector giving positions breaks function takes limits input returns breaks output minor_breaks One : NULL breaks waiver() breaks specified date_minor_breaks Date/POSIXct vector giving positions minor breaks function takes limits input returns minor breaks output labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. date_breaks string giving distance breaks like \"2 weeks\", \"10 years\". breaks date_breaks specified, date_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. date_labels string giving formatting specification labels. Codes defined strftime(). labels date_labels specified, date_labels wins. date_minor_breaks string giving distance minor breaks like \"2 weeks\", \"10 years\". minor_breaks date_minor_breaks specified, date_minor_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. timezone timezone use display axes. default (NULL) uses timezone encoded data. guide function used create guide name. See guides() information. call call used construct scale reporting messages. ... Arguments passed continuous_scale scale_name name scale used error messages associated scale. name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. position position scales, position axis. left right y axes, top bottom x axes. super super class use constructed scale","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/diamonds.html","id":null,"dir":"Reference","previous_headings":"","what":"Prices of over 50,000 round cut diamonds — diamonds","title":"Prices of over 50,000 round cut diamonds — diamonds","text":"dataset containing prices attributes almost 54,000 diamonds. variables follows:","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/diamonds.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Prices of over 50,000 round cut diamonds — diamonds","text":"","code":"diamonds"},{"path":"https://ggplot2.tidyverse.org/dev/reference/diamonds.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Prices of over 50,000 round cut diamonds — diamonds","text":"data frame 53940 rows 10 variables: price price US dollars ($326–$18,823) carat weight diamond (0.2–5.01) cut quality cut (Fair, Good, Good, Premium, Ideal) color diamond colour, D (best) J (worst) clarity measurement clear diamond (I1 (worst), SI2, SI1, VS2, VS1, VVS2, VVS1, (best)) x length mm (0–10.74) y width mm (0–58.9) z depth mm (0–31.8) depth total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43–79) table width top diamond relative widest point (43–95)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/discrete_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Discrete scale constructor — discrete_scale","title":"Discrete scale constructor — discrete_scale","text":"Discrete scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/discrete_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discrete scale constructor — discrete_scale","text":"","code":"discrete_scale( aesthetics, scale_name = deprecated(), palette, name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), na.translate = TRUE, na.value = NA, drop = TRUE, guide = \"legend\", position = \"left\", call = caller_call(), super = ScaleDiscrete )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/discrete_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discrete scale constructor — discrete_scale","text":"aesthetics names aesthetics scale works . scale_name name scale used error messages associated scale. palette palette function called single integer argument (number levels scale) returns values take (e.g., scales::pal_hue()). name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. na.value na.translate = TRUE, aesthetic value missing values displayed ? apply position scales NA always placed far right. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. call call used construct scale reporting messages. super super class use constructed scale","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Key glyphs for legends — draw_key","title":"Key glyphs for legends — draw_key","text":"geom associated function draws key geom needs displayed legend. functions called draw_key_*(), * stands name respective key glyph. key glyphs can customized individual geoms providing geom key_glyph argument (see layer() examples .)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Key glyphs for legends — draw_key","text":"","code":"draw_key_point(data, params, size) draw_key_abline(data, params, size) draw_key_rect(data, params, size) draw_key_polygon(data, params, size) draw_key_blank(data, params, size) draw_key_boxplot(data, params, size) draw_key_crossbar(data, params, size) draw_key_path(data, params, size) draw_key_vpath(data, params, size) draw_key_dotplot(data, params, size) draw_key_linerange(data, params, size) draw_key_pointrange(data, params, size) draw_key_smooth(data, params, size) draw_key_text(data, params, size) draw_key_label(data, params, size) draw_key_vline(data, params, size) draw_key_timeseries(data, params, size)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Key glyphs for legends — draw_key","text":"data single row data frame containing scaled aesthetics display key params list additional parameters supplied geom. size Width height key mm.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Key glyphs for legends — draw_key","text":"grid grob.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Key glyphs for legends — draw_key","text":"","code":"p <- ggplot(economics, aes(date, psavert, color = \"savings rate\")) # key glyphs can be specified by their name p + geom_line(key_glyph = \"timeseries\") # key glyphs can be specified via their drawing function p + geom_line(key_glyph = draw_key_rect)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/economics.html","id":null,"dir":"Reference","previous_headings":"","what":"US economic time series — economics","title":"US economic time series — economics","text":"dataset produced US economic time series data available https://fred.stlouisfed.org/. economics \"wide\" format, economics_long \"long\" format.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/economics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"US economic time series — economics","text":"","code":"economics economics_long"},{"path":"https://ggplot2.tidyverse.org/dev/reference/economics.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"US economic time series — economics","text":"data frame 574 rows 6 variables: date Month data collection pce personal consumption expenditures, billions dollars, https://fred.stlouisfed.org/series/PCE pop total population, thousands, https://fred.stlouisfed.org/series/POP psavert personal savings rate, https://fred.stlouisfed.org/series/PSAVERT/ uempmed median duration unemployment, weeks, https://fred.stlouisfed.org/series/UEMPMED unemploy number unemployed thousands, https://fred.stlouisfed.org/series/UNEMPLOY object class tbl_df (inherits tbl, data.frame) 2870 rows 4 columns.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":null,"dir":"Reference","previous_headings":"","what":"Theme elements — element","title":"Theme elements — element","text":"conjunction theme system, element_ functions specify display non-data components plot drawn. element_blank(): draws nothing, assigns space. element_rect(): borders backgrounds. element_line(): lines. element_text(): text. element_geom(): defaults drawing layers. rel() used specify sizes relative parent, margin() used specify margins elements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Theme elements — element","text":"","code":"element_blank() element_rect( fill = NULL, colour = NULL, linewidth = NULL, linetype = NULL, color = NULL, inherit.blank = FALSE, size = deprecated() ) element_line( colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL, color = NULL, arrow = NULL, arrow.fill = NULL, inherit.blank = FALSE, size = deprecated() ) element_text( family = NULL, face = NULL, colour = NULL, size = NULL, hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL, color = NULL, margin = NULL, debug = NULL, inherit.blank = FALSE ) element_geom( ink = NULL, paper = NULL, accent = NULL, linewidth = NULL, borderwidth = NULL, linetype = NULL, bordertype = NULL, family = NULL, fontsize = NULL, pointsize = NULL, pointshape = NULL ) rel(x) margin(t = 0, r = 0, b = 0, l = 0, unit = \"pt\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Theme elements — element","text":"fill Fill colour. colour, color Line/border colour. Color alias colour. linewidth, borderwidth Line/border size mm. linetype, bordertype Line type lines borders respectively. integer (0:8), name (blank, solid, dashed, dotted, dotdash, longdash, twodash), string even number (eight) hexadecimal digits give lengths consecutive positions string. inherit.blank element inherit existence element_blank among parents? TRUE existence blank element among parents cause element blank well. FALSE blank parent element ignored calculating final element state. size, fontsize text size pts. lineend Line end Line end style (round, butt, square) arrow Arrow specification, created grid::arrow() arrow.fill Fill colour arrows. family Font family face Font face (\"plain\", \"italic\", \"bold\", \"bold.italic\") hjust Horizontal justification (\\([0, 1]\\)) vjust Vertical justification (\\([0, 1]\\)) angle Angle (\\([0, 360]\\)) lineheight Line height margin Margins around text. See margin() details. creating theme, margins placed side text facing towards center plot. debug TRUE, aids visual debugging drawing solid rectangle behind complete text area, point label anchored. ink Foreground colour. paper Background colour. accent Accent colour. pointsize Size points mm. pointshape Shape points (1-25). x single number specifying size relative parent element. t, r, b, l Dimensions margin. (remember order, think trouble). unit Default units dimensions. Defaults \"pt\" can easily scaled text.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Theme elements — element","text":"S3 object class element, rel, margin.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Theme elements — element","text":"","code":"plot <- ggplot(mpg, aes(displ, hwy)) + geom_point() plot + theme( panel.background = element_blank(), axis.text = element_blank() ) plot + theme( axis.text = element_text(colour = \"red\", size = rel(1.5)) ) plot + theme( axis.line = element_line(arrow = arrow()) ) plot + theme( panel.background = element_rect(fill = \"white\"), plot.margin = margin(2, 2, 2, 2, \"cm\"), plot.background = element_rect( fill = \"grey90\", colour = \"black\", linewidth = 1 ) ) ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(formula = y ~ x, method = \"lm\") + theme(geom = element_geom( ink = \"red\", accent = \"black\", pointsize = 1, linewidth = 2 ))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_grob.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate grid grob from theme element — element_grob","title":"Generate grid grob from theme element — element_grob","text":"Generate grid grob theme element","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_grob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate grid grob from theme element — element_grob","text":"","code":"element_grob(element, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_grob.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate grid grob from theme element — element_grob","text":"element Theme element, .e. element_rect similar. ... arguments control specific rendering. usually least position. See source code individual methods.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_render.html","id":null,"dir":"Reference","previous_headings":"","what":"Render a specified theme element into a grob — element_render","title":"Render a specified theme element into a grob — element_render","text":"Given theme object element name, returns grob element. Uses element_grob() generate grob.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_render.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Render a specified theme element into a grob — element_render","text":"","code":"element_render(theme, element, ..., name = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_render.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Render a specified theme element into a grob — element_render","text":"theme theme object element element name given character vector ... arguments provided element_grob() name Character vector added name grob","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":null,"dir":"Reference","previous_headings":"","what":"Expand the plot limits, using data — expand_limits","title":"Expand the plot limits, using data — expand_limits","text":"Sometimes may want ensure limits include single value, panels plots. function thin wrapper around geom_blank() makes easy add values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Expand the plot limits, using data — expand_limits","text":"","code":"expand_limits(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Expand the plot limits, using data — expand_limits","text":"... named list aesthetics specifying value (values) included scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Expand the plot limits, using data — expand_limits","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p + expand_limits(x = 0) p + expand_limits(y = c(1, 9)) p + expand_limits(x = 0, y = 0) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = cyl)) + expand_limits(colour = seq(2, 10, by = 2)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl))) + expand_limits(colour = factor(seq(2, 10, by = 2)))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate expansion vector for scales — expansion","title":"Generate expansion vector for scales — expansion","text":"convenience function generating scale expansion vectors expand argument scale_(x|y)_continuous scale_(x|y)_discrete. expansion vectors used add space data axes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate expansion vector for scales — expansion","text":"","code":"expansion(mult = 0, add = 0) expand_scale(mult = 0, add = 0)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate expansion vector for scales — expansion","text":"mult vector multiplicative range expansion factors. length 1, lower upper limits scale expanded outwards mult. length 2, lower limit expanded mult[1] upper limit mult[2]. add vector additive range expansion constants. length 1, lower upper limits scale expanded outwards add units. length 2, lower limit expanded add[1] upper limit add[2].","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate expansion vector for scales — expansion","text":"","code":"# No space below the bars but 10% above them ggplot(mtcars) + geom_bar(aes(x = factor(cyl))) + scale_y_continuous(expand = expansion(mult = c(0, .1))) # Add 2 units of space on the left and right of the data ggplot(subset(diamonds, carat > 2), aes(cut, clarity)) + geom_jitter() + scale_x_discrete(expand = expansion(add = 2)) # Reproduce the default range expansion used # when the 'expand' argument is not specified ggplot(subset(diamonds, carat > 2), aes(cut, price)) + geom_jitter() + scale_x_discrete(expand = expansion(add = .6)) + scale_y_continuous(expand = expansion(mult = .05))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":null,"dir":"Reference","previous_headings":"","what":"Lay out panels in a grid — facet_grid","title":"Lay out panels in a grid — facet_grid","text":"facet_grid() forms matrix panels defined row column faceting variables. useful two discrete variables, combinations variables exist data. one variable many levels, try facet_wrap().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Lay out panels in a grid — facet_grid","text":"","code":"facet_grid( rows = NULL, cols = NULL, scales = \"fixed\", space = \"fixed\", shrink = TRUE, labeller = \"label_value\", as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE, axes = \"margins\", axis.labels = \"all\", facets = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Lay out panels in a grid — facet_grid","text":"rows, cols set variables expressions quoted vars() defining faceting groups rows columns dimension. variables can named (names passed labeller). compatibility classic interface, rows can also formula rows (tabular display) LHS columns (tabular display) RHS; dot formula used indicate faceting dimension (either row column). scales scales shared across facets (default, \"fixed\"), vary across rows (\"free_x\"), columns (\"free_y\"), rows columns (\"free\")? space \"fixed\", default, panels size. \"free_y\" height proportional length y scale; \"free_x\" width proportional length x scale; \"free\" height width vary. setting effect unless appropriate scales also vary. shrink TRUE, shrink scales fit output statistics, raw data. FALSE, range raw data statistical summary. labeller function takes one data frame labels returns list data frame character vectors. input column corresponds one factor. Thus one vars(cyl, ). output column gets displayed one separate line strip label. function inherit \"labeller\" S3 class compatibility labeller(). can use different labeling functions different kind labels, example use label_parsed() formatting facet labels. label_value() used default, check details pointers options. .table TRUE, default, facets laid like table highest values bottom-right. FALSE, facets laid like plot highest value top-right. switch default, labels displayed top right plot. \"x\", top labels displayed bottom. \"y\", right-hand side labels displayed left. Can also set \"\". drop TRUE, default, factor levels used data automatically dropped. FALSE, factor levels shown, regardless whether appear data. margins Either logical value character vector. Margins additional facets contain data possible values faceting variables. FALSE, additional facets included (default). TRUE, margins included faceting variables. specified character vector, names variables margins created. axes Determines axes drawn. \"margins\" (default), axes drawn exterior margins. \"all_x\" \"all_y\" draw respective axes interior panels , whereas \"\" draw axes panels. axis.labels Determines whether draw labels interior axes axes argument \"margins\". \"\" (default), interior axes get labels. \"margins\", exterior axes get labels interior axes get none. \"all_x\" \"all_y\", draws labels interior axes x- y-direction respectively. facets Please use rows cols instead.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Lay out panels in a grid — facet_grid","text":"","code":"p <- ggplot(mpg, aes(displ, cty)) + geom_point() # Use vars() to supply variables from the dataset: p + facet_grid(rows = vars(drv)) p + facet_grid(cols = vars(cyl)) p + facet_grid(vars(drv), vars(cyl)) # To change plot order of facet grid, # change the order of variable levels with factor() # If you combine a facetted dataset with a dataset that lacks those # faceting variables, the data will be repeated across the missing # combinations: df <- data.frame(displ = mean(mpg$displ), cty = mean(mpg$cty)) p + facet_grid(cols = vars(cyl)) + geom_point(data = df, colour = \"red\", size = 2) # When scales are constant, duplicated axes can be shown with # or without labels ggplot(mpg, aes(cty, hwy)) + geom_point() + facet_grid(year ~ drv, axes = \"all\", axis.labels = \"all_x\") # Free scales ------------------------------------------------------- # You can also choose whether the scales should be constant # across all panels (the default), or whether they should be allowed # to vary mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() mt + facet_grid(vars(cyl), scales = \"free\") # If scales and space are free, then the mapping between position # and values in the data will be the same across all panels. This # is particularly useful for categorical axes ggplot(mpg, aes(drv, model)) + geom_point() + facet_grid(manufacturer ~ ., scales = \"free\", space = \"free\") + theme(strip.text.y = element_text(angle = 0)) # Margins ---------------------------------------------------------- # \\donttest{ # Margins can be specified logically (all yes or all no) or for specific # variables as (character) variable names mg <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point() mg + facet_grid(vs + am ~ gear, margins = TRUE) mg + facet_grid(vs + am ~ gear, margins = \"am\") # when margins are made over \"vs\", since the facets for \"am\" vary # within the values of \"vs\", the marginal facet for \"vs\" is also # a margin over \"am\". mg + facet_grid(vs + am ~ gear, margins = \"vs\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":null,"dir":"Reference","previous_headings":"","what":"Facet specification: a single panel. — facet_null","title":"Facet specification: a single panel. — facet_null","text":"Facet specification: single panel.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Facet specification: a single panel. — facet_null","text":"","code":"facet_null(shrink = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Facet specification: a single panel. — facet_null","text":"shrink TRUE, shrink scales fit output statistics, raw data. FALSE, range raw data statistical summary.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Facet specification: a single panel. — facet_null","text":"","code":"# facet_null is the default faceting specification if you # don't override it with facet_grid or facet_wrap ggplot(mtcars, aes(mpg, wt)) + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":null,"dir":"Reference","previous_headings":"","what":"Wrap a 1d ribbon of panels into 2d — facet_wrap","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"facet_wrap() wraps 1d sequence panels 2d. generally better use screen space facet_grid() displays roughly rectangular.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"","code":"facet_wrap( facets, nrow = NULL, ncol = NULL, scales = \"fixed\", space = \"fixed\", shrink = TRUE, labeller = \"label_value\", as.table = TRUE, switch = deprecated(), drop = TRUE, dir = \"h\", strip.position = \"top\", axes = \"margins\", axis.labels = \"all\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"facets set variables expressions quoted vars() defining faceting groups rows columns dimension. variables can named (names passed labeller). compatibility classic interface, can also formula character vector. Use either one sided formula, ~+ b, character vector, c(\"\", \"b\"). nrow, ncol Number rows columns. scales scales fixed (\"fixed\", default), free (\"free\"), free one dimension (\"free_x\", \"free_y\")? space \"fixed\" (default), panels size number rows columns layout can arbitrary. \"free_x\", panels widths proportional length x-scale, layout constrained one row. \"free_y\", panels heights proportional length y-scale, layout constrained one column. shrink TRUE, shrink scales fit output statistics, raw data. FALSE, range raw data statistical summary. labeller function takes one data frame labels returns list data frame character vectors. input column corresponds one factor. Thus one vars(cyl, ). output column gets displayed one separate line strip label. function inherit \"labeller\" S3 class compatibility labeller(). can use different labeling functions different kind labels, example use label_parsed() formatting facet labels. label_value() used default, check details pointers options. .table TRUE, default, facets laid like table highest values bottom-right. FALSE, facets laid like plot highest value top-right. switch default, labels displayed top right plot. \"x\", top labels displayed bottom. \"y\", right-hand side labels displayed left. Can also set \"\". drop TRUE, default, factor levels used data automatically dropped. FALSE, factor levels shown, regardless whether appear data. dir Direction: either \"h\" horizontal, default, \"v\", vertical. \"h\" \"v\" combined .table set final layout. Alternatively, combination \"t\" (top) \"b\" (bottom) \"l\" (left) \"r\" (right) set layout directly. two letters give starting position first letter gives growing direction. example \"rt\" place first panel top-right starts filling panels right--left. strip.position default, labels displayed top plot. Using strip.position possible place labels either four sides setting strip.position = c(\"top\", \"bottom\", \"left\", \"right\") axes Determines axes drawn case fixed scales. \"margins\" (default), axes drawn exterior margins. \"all_x\" \"all_y\" draw respective axes interior panels , whereas \"\" draw axes panels. axis.labels Determines whether draw labels interior axes scale fixed axis argument \"margins\". \"\" (default), interior axes get labels. \"margins\", exterior axes get labels, interior axes get none. \"all_x\" \"all_y\", draws labels interior axes x- y-direction respectively.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Use vars() to supply faceting variables: p + facet_wrap(vars(class)) # Control the number of rows and columns with nrow and ncol p + facet_wrap(vars(class), nrow = 4) # \\donttest{ # You can facet by multiple variables ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(cyl, drv)) # Use the `labeller` option to control how labels are printed: ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(cyl, drv), labeller = \"label_both\") # To change the order in which the panels appear, change the levels # of the underlying factor. mpg$class2 <- reorder(mpg$class, mpg$displ) ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class2)) # By default, the same scales are used for all panels. You can allow # scales to vary across the panels with the `scales` argument. # Free scales make it easier to see patterns within each panel, but # harder to compare across panels. ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class), scales = \"free\") # When scales are constant, duplicated axes can be shown with # or without labels ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class), axes = \"all\", axis.labels = \"all_y\") # To repeat the same data in every panel, simply construct a data frame # that does not contain the faceting variable. ggplot(mpg, aes(displ, hwy)) + geom_point(data = transform(mpg, class = NULL), colour = \"grey85\") + geom_point() + facet_wrap(vars(class)) # Use `strip.position` to display the facet labels at the side of your # choice. Setting it to `bottom` makes it act as a subtitle for the axis. # This is typically used with free scales and a theme without boxes around # strip labels. ggplot(economics_long, aes(date, value)) + geom_line() + facet_wrap(vars(variable), scales = \"free_y\", nrow = 2, strip.position = \"top\") + theme(strip.background = element_blank(), strip.placement = \"outside\") # } # The two letters determine the starting position, so 'tr' starts # in the top-right. # The first letter determines direction, so 'tr' fills top-to-bottom. # `dir = \"tr\"` is equivalent to `dir = \"v\", as.table = FALSE` ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class), dir = \"tr\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/faithfuld.html","id":null,"dir":"Reference","previous_headings":"","what":"2d density estimate of Old Faithful data — faithfuld","title":"2d density estimate of Old Faithful data — faithfuld","text":"2d density estimate waiting eruptions variables data faithful.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/faithfuld.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"2d density estimate of Old Faithful data — faithfuld","text":"","code":"faithfuld"},{"path":"https://ggplot2.tidyverse.org/dev/reference/faithfuld.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"2d density estimate of Old Faithful data — faithfuld","text":"data frame 5,625 observations 3 variables: eruptions Eruption time mins waiting Waiting time next eruption mins density 2d density estimate","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify fill transparency — fill_alpha","title":"Modify fill transparency — fill_alpha","text":"works much like alpha() modifies transparency fill colours. differs fill_alpha() also attempts set transparency objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify fill transparency — fill_alpha","text":"","code":"fill_alpha(fill, alpha)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify fill transparency — fill_alpha","text":"fill fill colour given character integer vector, (list ) object(s). alpha transparency value 0 (transparent) 1 (opaque), parallel fill.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Modify fill transparency — fill_alpha","text":"character vector colours, list objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify fill transparency — fill_alpha","text":"","code":"# Typical colour input fill_alpha(\"red\", 0.5) #> [1] \"#FF000080\" if (utils::packageVersion(\"grid\") > \"4.2\") { # Pattern input fill_alpha(list(grid::linearGradient()), 0.5) } #> [[1]] #> $x1 #> [1] 0npc #> #> $y1 #> [1] 0npc #> #> $x2 #> [1] 1npc #> #> $y2 #> [1] 1npc #> #> $stops #> [1] 0 1 #> #> $colours #> [1] \"#00000080\" \"#FFFFFF80\" #> #> $extend #> [1] \"pad\" #> #> $group #> [1] TRUE #> #> attr(,\"class\") #> [1] \"GridLinearGradient\" \"GridPattern\" #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":null,"dir":"Reference","previous_headings":"","what":"Find panels in a gtable — find_panel","title":"Find panels in a gtable — find_panel","text":"functions help detect placement panels gtable, named \"panel\" beginning. find_panel() returns extend panel area, panel_cols() panel_rows() returns columns rows contains panels respectively.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Find panels in a gtable — find_panel","text":"","code":"find_panel(table) panel_cols(table) panel_rows(table)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Find panels in a gtable — find_panel","text":"table gtable","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Find panels in a gtable — find_panel","text":"data.frame columns t(op), r(ight), b(ottom), l(eft)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify methods for objects produced by multcomp — fortify-multcomp","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"Fortify methods objects produced multcomp","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"","code":"# S3 method for class 'glht' fortify(model, data, ...) # S3 method for class 'confint.glht' fortify(model, data, ...) # S3 method for class 'summary.glht' fortify(model, data, ...) # S3 method for class 'cld' fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"model object class glht, confint.glht, summary.glht multcomp::cld() data, ... arguments generic ignored method.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"","code":"if (require(\"multcomp\")) { amod <- aov(breaks ~ wool + tension, data = warpbreaks) wht <- glht(amod, linfct = mcp(tension = \"Tukey\")) fortify(wht) ggplot(wht, aes(lhs, estimate)) + geom_point() CI <- confint(wht) fortify(CI) ggplot(CI, aes(lhs, estimate, ymin = lwr, ymax = upr)) + geom_pointrange() fortify(summary(wht)) ggplot(mapping = aes(lhs, estimate)) + geom_linerange(aes(ymin = lwr, ymax = upr), data = CI) + geom_point(aes(size = p), data = summary(wht)) + scale_size(transform = \"reverse\") cld <- cld(wht) fortify(cld) } #> Loading required package: multcomp #> Loading required package: mvtnorm #> Loading required package: survival #> Loading required package: TH.data #> Loading required package: MASS #> #> Attaching package: ‘TH.data’ #> The following object is masked from ‘package:MASS’: #> #> geyser #> lhs letters #> L L a #> M M b #> H H b"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify a model with data. — fortify","title":"Fortify a model with data. — fortify","text":"Rather using function, now recommend using broom package, implements much wider range methods. fortify() may deprecated future.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify a model with data. — fortify","text":"","code":"fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify a model with data. — fortify","text":"model model R object convert data frame data original dataset, needed ... Arguments passed methods.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":null,"dir":"Reference","previous_headings":"","what":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"missing values model data, may need refit model na.action = na.exclude.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"","code":"# S3 method for class 'lm' fortify(model, data = model$model, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"model linear model data data set, defaults data used fit model ... used method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"original data extra columns: .hat Diagonal hat matrix .sigma Estimate residual standard deviation corresponding observation dropped model .cooksd Cooks distance, cooks.distance() .fitted Fitted values model .resid Residuals .stdresid Standardised residuals","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"","code":"mod <- lm(mpg ~ wt, data = mtcars) head(fortify(mod)) #> mpg wt .hat .sigma .cooksd .fitted #> Mazda RX4 21.0 2.620 0.04326896 3.067494 1.327407e-02 23.28261 #> Mazda RX4 Wag 21.0 2.875 0.03519677 3.093068 1.723963e-03 21.91977 #> Datsun 710 22.8 2.320 0.05837573 3.072127 1.543937e-02 24.88595 #> Hornet 4 Drive 21.4 3.215 0.03125017 3.088268 3.020558e-03 20.10265 #> Hornet Sportabout 18.7 3.440 0.03292182 3.097722 7.599578e-05 18.90014 #> Valiant 18.1 3.460 0.03323551 3.095184 9.210650e-04 18.79325 #> .resid .stdresid #> Mazda RX4 -2.2826106 -0.76616765 #> Mazda RX4 Wag -0.9197704 -0.30743051 #> Datsun 710 -2.0859521 -0.70575249 #> Hornet 4 Drive 1.2973499 0.43275114 #> Hornet Sportabout -0.2001440 -0.06681879 #> Valiant -0.6932545 -0.23148309 head(fortify(mod, mtcars)) #> mpg cyl disp hp drat wt qsec vs am gear carb #> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 #> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 #> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 #> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 #> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 #> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 #> .hat .sigma .cooksd .fitted .resid #> Mazda RX4 0.04326896 3.067494 1.327407e-02 23.28261 -2.2826106 #> Mazda RX4 Wag 0.03519677 3.093068 1.723963e-03 21.91977 -0.9197704 #> Datsun 710 0.05837573 3.072127 1.543937e-02 24.88595 -2.0859521 #> Hornet 4 Drive 0.03125017 3.088268 3.020558e-03 20.10265 1.2973499 #> Hornet Sportabout 0.03292182 3.097722 7.599578e-05 18.90014 -0.2001440 #> Valiant 0.03323551 3.095184 9.210650e-04 18.79325 -0.6932545 #> .stdresid #> Mazda RX4 -0.76616765 #> Mazda RX4 Wag -0.30743051 #> Datsun 710 -0.70575249 #> Hornet 4 Drive 0.43275114 #> Hornet Sportabout -0.06681879 #> Valiant -0.23148309 plot(mod, which = 1) ggplot(mod, aes(.fitted, .resid)) + geom_point() + geom_hline(yintercept = 0) + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(mod, aes(.fitted, .stdresid)) + geom_point() + geom_hline(yintercept = 0) + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(fortify(mod, mtcars), aes(.fitted, .stdresid)) + geom_point(aes(colour = factor(cyl))) ggplot(fortify(mod, mtcars), aes(mpg, .stdresid)) + geom_point(aes(colour = factor(cyl))) plot(mod, which = 2) ggplot(mod) + stat_qq(aes(sample = .stdresid)) + geom_abline() plot(mod, which = 3) ggplot(mod, aes(.fitted, sqrt(abs(.stdresid)))) + geom_point() + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' plot(mod, which = 4) ggplot(mod, aes(seq_along(.cooksd), .cooksd)) + geom_col() plot(mod, which = 5) ggplot(mod, aes(.hat, .stdresid)) + geom_vline(linewidth = 2, colour = \"white\", xintercept = 0) + geom_hline(linewidth = 2, colour = \"white\", yintercept = 0) + geom_point() + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(mod, aes(.hat, .stdresid)) + geom_point(aes(size = .cooksd)) + geom_smooth(se = FALSE, linewidth = 0.5) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' plot(mod, which = 6) ggplot(mod, aes(.hat, .cooksd)) + geom_vline(xintercept = 0, colour = NA) + geom_abline(slope = seq(0, 3, by = 0.5), colour = \"white\") + geom_smooth(se = FALSE) + geom_point() #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(mod, aes(.hat, .cooksd)) + geom_point(aes(size = .cooksd / .hat)) + scale_size_area()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify method for map objects — fortify.map","title":"Fortify method for map objects — fortify.map","text":"function turns map data frame can easily plotted ggplot2.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify method for map objects — fortify.map","text":"","code":"# S3 method for class 'map' fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify method for map objects — fortify.map","text":"model map object data used method ... used method","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Fortify method for map objects — fortify.map","text":"","code":"if (require(\"maps\")) { ca <- map(\"county\", \"ca\", plot = FALSE, fill = TRUE) head(fortify(ca)) ggplot(ca, aes(long, lat)) + geom_polygon(aes(group = group)) } if (require(\"maps\")) { tx <- map(\"county\", \"texas\", plot = FALSE, fill = TRUE) head(fortify(tx)) ggplot(tx, aes(long, lat)) + geom_polygon(aes(group = group), colour = \"white\") }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.sp.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify method for classes from the sp package. — fortify.sp","title":"Fortify method for classes from the sp package. — fortify.sp","text":"figure correct variable name region, inspect .data.frame(model).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.sp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify method for classes from the sp package. — fortify.sp","text":"","code":"# S3 method for class 'SpatialPolygonsDataFrame' fortify(model, data, region = NULL, ...) # S3 method for class 'SpatialPolygons' fortify(model, data, ...) # S3 method for class 'Polygons' fortify(model, data, ...) # S3 method for class 'Polygon' fortify(model, data, ...) # S3 method for class 'SpatialLinesDataFrame' fortify(model, data, ...) # S3 method for class 'Lines' fortify(model, data, ...) # S3 method for class 'Line' fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.sp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify method for classes from the sp package. — fortify.sp","text":"model SpatialPolygonsDataFrame convert dataframe. data used method region name variable used split regions ... used method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":null,"dir":"Reference","previous_headings":"","what":"Reference lines: horizontal, vertical, and diagonal — geom_abline","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"geoms add reference lines (sometimes called rules) plot, either horizontal, vertical, diagonal (specified slope intercept). useful annotating plots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"","code":"geom_abline( mapping = NULL, data = NULL, ..., slope, intercept, na.rm = FALSE, show.legend = NA ) geom_hline( mapping = NULL, data = NULL, position = \"identity\", ..., yintercept, na.rm = FALSE, show.legend = NA ) geom_vline( mapping = NULL, data = NULL, position = \"identity\", ..., xintercept, na.rm = FALSE, show.legend = NA )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"mapping Set aesthetic mappings created aes(). data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. xintercept, yintercept, slope, intercept Parameters control position line. set, data, mapping show.legend overridden.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"geoms act slightly differently geoms. can supply parameters two ways: either arguments layer function, via aesthetics. use arguments, e.g. geom_abline(intercept = 0, slope = 1), behind scenes geom makes new data frame containing just data supplied. means lines facets; want vary across facets, construct data frame use aesthetics. Unlike geoms, geoms inherit aesthetics plot default, understand x y aesthetics commonly set plot. also affect x y scales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"geoms drawn using geom_line() support aesthetics: alpha, colour, linetype linewidth. also aesthetics control position line: geom_vline(): xintercept geom_hline(): yintercept geom_abline(): slope intercept","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() # Fixed values p + geom_vline(xintercept = 5) p + geom_vline(xintercept = 1:5) p + geom_hline(yintercept = 20) p + geom_abline() # Can't see it - outside the range of the data p + geom_abline(intercept = 20) # Calculate slope and intercept of line of best fit coef(lm(mpg ~ wt, data = mtcars)) #> (Intercept) wt #> 37.285126 -5.344472 p + geom_abline(intercept = 37, slope = -5) # But this is easier to do with geom_smooth: p + geom_smooth(method = \"lm\", se = FALSE) #> `geom_smooth()` using formula = 'y ~ x' # To show different lines in different facets, use aesthetics p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_wrap(~ cyl) mean_wt <- data.frame(cyl = c(4, 6, 8), wt = c(2.28, 3.11, 4.00)) p + geom_hline(aes(yintercept = wt), mean_wt) # You can also control other aesthetics ggplot(mtcars, aes(mpg, wt, colour = wt)) + geom_point() + geom_hline(aes(yintercept = wt, colour = wt), mean_wt) + facet_wrap(~ cyl)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":null,"dir":"Reference","previous_headings":"","what":"Bar charts — geom_bar","title":"Bar charts — geom_bar","text":"two types bar charts: geom_bar() geom_col(). geom_bar() makes height bar proportional number cases group (weight aesthetic supplied, sum weights). want heights bars represent values data, use geom_col() instead. geom_bar() uses stat_count() default: counts number cases x position. geom_col() uses stat_identity(): leaves data .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Bar charts — geom_bar","text":"","code":"geom_bar( mapping = NULL, data = NULL, stat = \"count\", position = \"stack\", ..., just = 0.5, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_col( mapping = NULL, data = NULL, position = \"stack\", ..., just = 0.5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_count( mapping = NULL, data = NULL, geom = \"bar\", position = \"stack\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Bar charts — geom_bar","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. just Adjustment column placement. Set 0.5 default, meaning columns centered axis breaks. Set 0 1 place columns left/right axis breaks. Note argument may unintended behaviour used alternative positions, e.g. position_dodge(). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Override default connection geom_bar() stat_count(). information overriding connections, see stat geom arguments work.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Bar charts — geom_bar","text":"bar chart uses height represent value, base bar must always shown produce valid visual comparison. Proceed caution using transformed scales bar chart. important always use meaningful reference point base bar. example, log transformations reference point 1. fact, using log scale, geom_bar() automatically places base bar 1. Furthermore, never use stacked bars transformed scale, scaling happens stacking. consequence, height bars wrong stacking occurs transformed scale. default, multiple bars occupying x position stacked atop one another position_stack(). want dodged side--side, use position_dodge() position_dodge2(). Finally, position_fill() shows relative proportions x stacking bars standardising bar height.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Bar charts — geom_bar","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Bar charts — geom_bar","text":"geom_bar() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth width Learn setting aesthetics vignette(\"ggplot2-specs\"). geom_col() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth width Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_count() understands following aesthetics (required aesthetics bold): x y group weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Bar charts — geom_bar","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(prop) groupwise proportion","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Bar charts — geom_bar","text":"","code":"# geom_bar is designed to make it easy to create bar charts that show # counts (or sums of weights) g <- ggplot(mpg, aes(class)) # Number of cars in each class: g + geom_bar() # Total engine displacement of each class g + geom_bar(aes(weight = displ)) # Map class to y instead to flip the orientation ggplot(mpg) + geom_bar(aes(y = class)) # Bar charts are automatically stacked when multiple bars are placed # at the same location. The order of the fill is designed to match # the legend g + geom_bar(aes(fill = drv)) # If you need to flip the order (because you've flipped the orientation) # call position_stack() explicitly: ggplot(mpg, aes(y = class)) + geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) + theme(legend.position = \"top\") # To show (e.g.) means, you need geom_col() df <- data.frame(trt = c(\"a\", \"b\", \"c\"), outcome = c(2.3, 1.9, 3.2)) ggplot(df, aes(trt, outcome)) + geom_col() # But geom_point() displays exactly the same information and doesn't # require the y-axis to touch zero. ggplot(df, aes(trt, outcome)) + geom_point() # You can also use geom_bar() with continuous data, in which case # it will show counts at unique locations df <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4))) ggplot(df, aes(x)) + geom_bar() # cf. a histogram of the same data ggplot(df, aes(x)) + geom_histogram(binwidth = 0.5) # Use `just` to control how columns are aligned with axis breaks: df <- data.frame(x = as.Date(c(\"2020-01-01\", \"2020-02-01\")), y = 1:2) # Columns centered on the first day of the month ggplot(df, aes(x, y)) + geom_col(just = 0.5) # Columns begin on the first day of the month ggplot(df, aes(x, y)) + geom_col(just = 1)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":null,"dir":"Reference","previous_headings":"","what":"Heatmap of 2d bin counts — geom_bin_2d","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"Divides plane rectangles, counts number cases rectangle, (default) maps number cases rectangle's fill. useful alternative geom_point() presence overplotting.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"","code":"geom_bin_2d( mapping = NULL, data = NULL, stat = \"bin2d\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_bin_2d( mapping = NULL, data = NULL, geom = \"tile\", position = \"identity\", ..., bins = 30, binwidth = NULL, drop = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_bin_2d() stat_bin_2d(). information overriding connections, see stat geom arguments work. bins numeric vector giving number bins vertical horizontal directions. Set 30 default. binwidth Numeric vector giving bin width vertical horizontal directions. Overrides bins set. drop TRUE removes cells 0 counts.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"stat_bin_2d() understands following aesthetics (required aesthetics bold): x y fill group weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(density) density points bin, scaled integrate 1. after_stat(ncount) count, scaled maximum 1. after_stat(ndensity) density, scaled maximum 1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"","code":"d <- ggplot(diamonds, aes(x, y)) + xlim(4, 10) + ylim(4, 10) d + geom_bin_2d() #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 5 rows containing missing values or values outside the scale #> range (`geom_tile()`). # You can control the size of the bins by specifying the number of # bins in each direction: d + geom_bin_2d(bins = 10) #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 6 rows containing missing values or values outside the scale #> range (`geom_tile()`). d + geom_bin_2d(bins = 30) #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 5 rows containing missing values or values outside the scale #> range (`geom_tile()`). # Or by specifying the width of the bins d + geom_bin_2d(binwidth = c(0.1, 0.1)) #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 5 rows containing missing values or values outside the scale #> range (`geom_tile()`)."},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":null,"dir":"Reference","previous_headings":"","what":"Draw nothing — geom_blank","title":"Draw nothing — geom_blank","text":"blank geom draws nothing, can useful way ensuring common scales different plots. See expand_limits() details.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Draw nothing — geom_blank","text":"","code":"geom_blank( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Draw nothing — geom_blank","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Draw nothing — geom_blank","text":"","code":"ggplot(mtcars, aes(wt, mpg)) # Nothing to see here!"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":null,"dir":"Reference","previous_headings":"","what":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"boxplot compactly displays distribution continuous variable. visualises five summary statistics (median, two hinges two whiskers), \"outlying\" points individually.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"","code":"geom_boxplot( mapping = NULL, data = NULL, stat = \"boxplot\", position = \"dodge2\", ..., outliers = TRUE, outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, outlier.shape = NULL, outlier.size = NULL, outlier.stroke = 0.5, outlier.alpha = NULL, notch = FALSE, notchwidth = 0.5, staplewidth = 0, varwidth = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_boxplot( mapping = NULL, data = NULL, geom = \"boxplot\", position = \"dodge2\", ..., coef = 1.5, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. outliers Whether display (TRUE) discard (FALSE) outliers plot. Hiding discarding outliers can useful , example, raw data points need displayed top boxplot. discarding outliers, axis limits adapt box whiskers , full data range. outliers need hidden axes needs show full data range, please use outlier.shape = NA instead. outlier.colour, outlier.color, outlier.fill, outlier.shape, outlier.size, outlier.stroke, outlier.alpha Default aesthetics outliers. Set NULL inherit aesthetics used box. unlikely event specify US UK spellings colour, US spelling take precedence. notch FALSE (default) make standard box plot. TRUE, make notched box plot. Notches used compare groups; notches two boxes overlap, suggests medians significantly different. notchwidth notched box plot, width notch relative body (defaults notchwidth = 0.5). staplewidth relative width staples width box. Staples mark ends whiskers line. varwidth FALSE (default) make standard box plot. TRUE, boxes drawn widths proportional square-roots number observations groups (possibly weighted, using weight aesthetic). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_boxplot() stat_boxplot(). information overriding connections, see stat geom arguments work. coef Length whiskers multiple IQR. Defaults 1.5.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"summary-statistics","dir":"Reference","previous_headings":"","what":"Summary statistics","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"lower upper hinges correspond first third quartiles (25th 75th percentiles). differs slightly method used boxplot() function, may apparent small samples. See boxplot.stats() information hinge positions calculated boxplot(). upper whisker extends hinge largest value 1.5 * IQR hinge (IQR inter-quartile range, distance first third quartiles). lower whisker extends hinge smallest value 1.5 * IQR hinge. Data beyond end whiskers called \"outlying\" points plotted individually. notched box plot, notches extend 1.58 * IQR / sqrt(n). gives roughly 95% confidence interval comparing medians. See McGill et al. (1978) details.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"geom_boxplot() understands following aesthetics (required aesthetics bold): x y lower xlower upper xupper middle xmiddle ymin xmin ymax xmax alpha colour fill group linetype linewidth shape size weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"calculated 'stat' part layers can accessed delayed evaluation. stat_boxplot() provides following variables, depend orientation: after_stat(width) width boxplot. after_stat(ymin) after_stat(xmin) lower whisker = smallest observation greater equal lower hinger - 1.5 * IQR. after_stat(lower) after_stat(xlower) lower hinge, 25% quantile. after_stat(notchlower) lower edge notch = median - 1.58 * IQR / sqrt(n). after_stat(middle) after_stat(xmiddle) median, 50% quantile. after_stat(notchupper) upper edge notch = median + 1.58 * IQR / sqrt(n). after_stat(upper) after_stat(xupper) upper hinge, 75% quantile. after_stat(ymax) after_stat(xmax) upper whisker = largest observation less equal upper hinger + 1.5 * IQR.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"McGill, R., Tukey, J. W. Larsen, W. . (1978) Variations box plots. American Statistician 32, 12-16.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"","code":"p <- ggplot(mpg, aes(class, hwy)) p + geom_boxplot() # Orientation follows the discrete axis ggplot(mpg, aes(hwy, class)) + geom_boxplot() p + geom_boxplot(notch = TRUE) #> Notch went outside hinges #> ℹ Do you want `notch = FALSE`? #> Notch went outside hinges #> ℹ Do you want `notch = FALSE`? p + geom_boxplot(varwidth = TRUE) p + geom_boxplot(fill = \"white\", colour = \"#3366FF\") # By default, outlier points match the colour of the box. Use # outlier.colour to override p + geom_boxplot(outlier.colour = \"red\", outlier.shape = 1) # Remove outliers when overlaying boxplot with original data points p + geom_boxplot(outlier.shape = NA) + geom_jitter(width = 0.2) # Boxplots are automatically dodged when any aesthetic is a factor p + geom_boxplot(aes(colour = drv)) # You can also use boxplots with continuous x, as long as you supply # a grouping variable. cut_width is particularly useful ggplot(diamonds, aes(carat, price)) + geom_boxplot() #> Warning: Continuous x aesthetic #> ℹ did you forget `aes(group = ...)`? ggplot(diamonds, aes(carat, price)) + geom_boxplot(aes(group = cut_width(carat, 0.25))) # Adjust the transparency of outliers using outlier.alpha ggplot(diamonds, aes(carat, price)) + geom_boxplot(aes(group = cut_width(carat, 0.25)), outlier.alpha = 0.1) # \\donttest{ # It's possible to draw a boxplot with your own computations if you # use stat = \"identity\": set.seed(1) y <- rnorm(100) df <- data.frame( x = 1, y0 = min(y), y25 = quantile(y, 0.25), y50 = median(y), y75 = quantile(y, 0.75), y100 = max(y) ) ggplot(df, aes(x)) + geom_boxplot( aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100), stat = \"identity\" ) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":null,"dir":"Reference","previous_headings":"","what":"2D contours of a 3D surface — geom_contour","title":"2D contours of a 3D surface — geom_contour","text":"ggplot2 can draw true 3D surfaces, can use geom_contour(), geom_contour_filled(), geom_tile() visualise 3D surfaces 2D. functions require regular data, x y coordinates form equally spaced grid, combination x y appears . Missing values z allowed, contouring work grid points four corners non-missing. irregular data, need first interpolate grid visualising, using interp::interp(), akima::bilinear(), similar.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"2D contours of a 3D surface — geom_contour","text":"","code":"geom_contour( mapping = NULL, data = NULL, stat = \"contour\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, lineend = \"butt\", linejoin = \"round\", linemitre = 10, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_contour_filled( mapping = NULL, data = NULL, stat = \"contour_filled\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_contour( mapping = NULL, data = NULL, geom = \"contour\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_contour_filled( mapping = NULL, data = NULL, geom = \"contour_filled\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"2D contours of a 3D surface — geom_contour","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. bins Number contour bins. Overridden breaks. binwidth width contour bins. Overridden bins. breaks One : Numeric vector set contour breaks function takes range data binwidth input returns breaks output. function can created formula (e.g. ~ fullseq(.x, .y)). Overrides binwidth bins. default, vector length ten pretty() breaks. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"2D contours of a 3D surface — geom_contour","text":"geom_contour() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\"). geom_contour_filled() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_contour() understands following aesthetics (required aesthetics bold): x y z group order Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_contour_filled() understands following aesthetics (required aesthetics bold): x y z fill group order Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"2D contours of a 3D surface — geom_contour","text":"calculated 'stat' part layers can accessed delayed evaluation. computed variables differ somewhat contour lines (computed stat_contour()) contour bands (filled contours, computed stat_contour_filled()). variables nlevel piece available , whereas level_low, level_high, level_mid available bands. variable level numeric factor depending whether lines bands calculated. after_stat(level) Height contour. contour lines, numeric vector represents bin boundaries. contour bands, ordered factor represents bin ranges. after_stat(level_low), after_stat(level_high), after_stat(level_mid) (contour bands ) Lower upper bin boundaries band, well mid point boundaries. after_stat(nlevel) Height contour, scaled maximum 1. after_stat(piece) Contour piece (integer).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"2D contours of a 3D surface — geom_contour","text":"z contouring, z values individual data points longer available.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"2D contours of a 3D surface — geom_contour","text":"","code":"# Basic plot v <- ggplot(faithfuld, aes(waiting, eruptions, z = density)) v + geom_contour() # Or compute from raw data ggplot(faithful, aes(waiting, eruptions)) + geom_density_2d() # \\donttest{ # use geom_contour_filled() for filled contours v + geom_contour_filled() # Setting bins creates evenly spaced contours in the range of the data v + geom_contour(bins = 3) v + geom_contour(bins = 5) # Setting binwidth does the same thing, parameterised by the distance # between contours v + geom_contour(binwidth = 0.01) v + geom_contour(binwidth = 0.001) # Other parameters v + geom_contour(aes(colour = after_stat(level))) v + geom_contour(colour = \"red\") v + geom_raster(aes(fill = density)) + geom_contour(colour = \"white\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":null,"dir":"Reference","previous_headings":"","what":"Count overlapping points — geom_count","title":"Count overlapping points — geom_count","text":"variant geom_point() counts number observations location, maps count point area. useful discrete data overplotting.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Count overlapping points — geom_count","text":"","code":"geom_count( mapping = NULL, data = NULL, stat = \"sum\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_sum( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Count overlapping points — geom_count","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_count() stat_sum(). information overriding connections, see stat geom arguments work.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Count overlapping points — geom_count","text":"geom_point() understands following aesthetics (required aesthetics bold): x y alpha colour fill group shape size stroke Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Count overlapping points — geom_count","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(n) Number observations position. after_stat(prop) Percent points panel position.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Count overlapping points — geom_count","text":"","code":"ggplot(mpg, aes(cty, hwy)) + geom_point() ggplot(mpg, aes(cty, hwy)) + geom_count() # Best used in conjunction with scale_size_area which ensures that # counts of zero would be given size 0. Doesn't make much different # here because the smallest count is already close to 0. ggplot(mpg, aes(cty, hwy)) + geom_count() + scale_size_area() # Display proportions instead of counts ------------------------------------- # By default, all categorical variables in the plot form the groups. # Specifying geom_count without a group identifier leads to a plot which is # not useful: d <- ggplot(diamonds, aes(x = cut, y = clarity)) d + geom_count(aes(size = after_stat(prop))) # To correct this problem and achieve a more desirable plot, we need # to specify which group the proportion is to be calculated over. d + geom_count(aes(size = after_stat(prop), group = 1)) + scale_size_area(max_size = 10) # Or group by x/y variables to have rows/columns sum to 1. d + geom_count(aes(size = after_stat(prop), group = cut)) + scale_size_area(max_size = 10) d + geom_count(aes(size = after_stat(prop), group = clarity)) + scale_size_area(max_size = 10)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":null,"dir":"Reference","previous_headings":"","what":"Smoothed density estimates — geom_density","title":"Smoothed density estimates — geom_density","text":"Computes draws kernel density estimate, smoothed version histogram. useful alternative histogram continuous data comes underlying smooth distribution.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Smoothed density estimates — geom_density","text":"","code":"geom_density( mapping = NULL, data = NULL, stat = \"density\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, outline.type = \"upper\" ) stat_density( mapping = NULL, data = NULL, geom = \"area\", position = \"stack\", ..., bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512, trim = FALSE, na.rm = FALSE, bounds = c(-Inf, Inf), orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Smoothed density estimates — geom_density","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). outline.type Type outline area; \"\" draws upper lower lines, \"upper\"/\"lower\" draws respective lines . \"full\" draws closed polygon around area. geom, stat Use override default connection geom_density() stat_density(). information overriding connections, see stat geom arguments work. bw smoothing bandwidth used. numeric, standard deviation smoothing kernel. character, rule choose bandwidth, listed stats::bw.nrd(). Note automatic calculation bandwidth take weights account. adjust multiplicate bandwidth adjustment. makes possible adjust bandwidth still using bandwidth estimator. example, adjust = 1/2 means use half default bandwidth. kernel Kernel. See list available kernels density(). n number equally spaced points density estimated, power two, see density() details trim FALSE, default, density computed full range data. TRUE, density computed range group: typically means estimated x values line-, hence able stack density values. parameter matters displaying multiple densities one plot manually adjusting scale limits. bounds Known lower upper bounds estimated data. Default c(-Inf, Inf) means (finite) bounds. bound finite, boundary effect default density estimation corrected reflecting tails outside bounds around closest edge. Data points outside bounds removed warning.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Smoothed density estimates — geom_density","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Smoothed density estimates — geom_density","text":"geom_density() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Smoothed density estimates — geom_density","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(density) density estimate. after_stat(count) density * number points - useful stacked density plots. after_stat(wdensity) density * sum weights. absence weights, count. after_stat(scaled) density estimate, scaled maximum 1. after_stat(n) number points. after_stat(ndensity) alias scaled, mirror syntax stat_bin().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Smoothed density estimates — geom_density","text":"","code":"ggplot(diamonds, aes(carat)) + geom_density() # Map the values to y to flip the orientation ggplot(diamonds, aes(y = carat)) + geom_density() ggplot(diamonds, aes(carat)) + geom_density(adjust = 1/5) ggplot(diamonds, aes(carat)) + geom_density(adjust = 5) ggplot(diamonds, aes(depth, colour = cut)) + geom_density() + xlim(55, 70) #> Warning: Removed 45 rows containing non-finite outside the scale range #> (`stat_density()`). ggplot(diamonds, aes(depth, fill = cut, colour = cut)) + geom_density(alpha = 0.1) + xlim(55, 70) #> Warning: Removed 45 rows containing non-finite outside the scale range #> (`stat_density()`). # Use `bounds` to adjust computation for known data limits big_diamonds <- diamonds[diamonds$carat >= 1, ] ggplot(big_diamonds, aes(carat)) + geom_density(color = 'red') + geom_density(bounds = c(1, Inf), color = 'blue') # \\donttest{ # Stacked density plots: if you want to create a stacked density plot, you # probably want to 'count' (density * n) variable instead of the default # density # Loses marginal densities ggplot(diamonds, aes(carat, fill = cut)) + geom_density(position = \"stack\") # Preserves marginal densities ggplot(diamonds, aes(carat, after_stat(count), fill = cut)) + geom_density(position = \"stack\") # You can use position=\"fill\" to produce a conditional density estimate ggplot(diamonds, aes(carat, after_stat(count), fill = cut)) + geom_density(position = \"fill\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":null,"dir":"Reference","previous_headings":"","what":"Contours of a 2D density estimate — geom_density_2d","title":"Contours of a 2D density estimate — geom_density_2d","text":"Perform 2D kernel density estimation using MASS::kde2d() display results contours. can useful dealing overplotting. 2D version geom_density(). geom_density_2d() draws contour lines, geom_density_2d_filled() draws filled contour bands.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Contours of a 2D density estimate — geom_density_2d","text":"","code":"geom_density_2d( mapping = NULL, data = NULL, stat = \"density_2d\", position = \"identity\", ..., contour_var = \"density\", lineend = \"butt\", linejoin = \"round\", linemitre = 10, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_density_2d_filled( mapping = NULL, data = NULL, stat = \"density_2d_filled\", position = \"identity\", ..., contour_var = \"density\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_density_2d( mapping = NULL, data = NULL, geom = \"density_2d\", position = \"identity\", ..., contour = TRUE, contour_var = \"density\", n = 100, h = NULL, adjust = c(1, 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_density_2d_filled( mapping = NULL, data = NULL, geom = \"density_2d_filled\", position = \"identity\", ..., contour = TRUE, contour_var = \"density\", n = 100, h = NULL, adjust = c(1, 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Contours of a 2D density estimate — geom_density_2d","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... Arguments passed geom_contour binwidth width contour bins. Overridden bins. bins Number contour bins. Overridden breaks. breaks One : Numeric vector set contour breaks function takes range data binwidth input returns breaks output. function can created formula (e.g. ~ fullseq(.x, .y)). Overrides binwidth bins. default, vector length ten pretty() breaks. contour_var Character string identifying variable contour . Can one \"density\", \"ndensity\", \"count\". See section computed variables details. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_density_2d() stat_density_2d(). information overriding connections, see stat geom arguments work. contour TRUE, contour results 2d density estimation. n Number grid points direction. h Bandwidth (vector length two). NULL, estimated using MASS::bandwidth.nrd(). adjust multiplicative bandwidth adjustment used 'h' 'NULL'. makes possible adjust bandwidth still using bandwidth estimator. example, adjust = 1/2 means use half default bandwidth.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Contours of a 2D density estimate — geom_density_2d","text":"geom_density_2d() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\"). geom_density_2d_filled() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Contours of a 2D density estimate — geom_density_2d","text":"calculated 'stat' part layers can accessed delayed evaluation. stat_density_2d() stat_density_2d_filled() compute different variables depending whether contouring turned . contouring (contour = FALSE), stats behave , following variables provided: after_stat(density) density estimate. after_stat(ndensity) Density estimate, scaled maximum 1. after_stat(count) Density estimate * number observations group. after_stat(n) Number observations group. contouring (contour = TRUE), either stat_contour() stat_contour_filled() (contour lines contour bands, respectively) run density estimate obtained, computed variables determined stats. Contours calculated one three types density estimates obtained contouring, density, ndensity, count. used determined contour_var parameter.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Contours of a 2D density estimate — geom_density_2d","text":"z density estimation, z values individual data points longer available. contouring enabled, similarly density, ndensity, count longer available contouring pass.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Contours of a 2D density estimate — geom_density_2d","text":"","code":"m <- ggplot(faithful, aes(x = eruptions, y = waiting)) + geom_point() + xlim(0.5, 6) + ylim(40, 110) # contour lines m + geom_density_2d() # \\donttest{ # contour bands m + geom_density_2d_filled(alpha = 0.5) # contour bands and contour lines m + geom_density_2d_filled(alpha = 0.5) + geom_density_2d(linewidth = 0.25, colour = \"black\") set.seed(4393) dsmall <- diamonds[sample(nrow(diamonds), 1000), ] d <- ggplot(dsmall, aes(x, y)) # If you map an aesthetic to a categorical variable, you will get a # set of contours for each value of that variable d + geom_density_2d(aes(colour = cut)) # If you draw filled contours across multiple facets, the same bins are # used across all facets d + geom_density_2d_filled() + facet_wrap(vars(cut)) # If you want to make sure the peak intensity is the same in each facet, # use `contour_var = \"ndensity\"`. d + geom_density_2d_filled(contour_var = \"ndensity\") + facet_wrap(vars(cut)) # If you want to scale intensity by the number of observations in each group, # use `contour_var = \"count\"`. d + geom_density_2d_filled(contour_var = \"count\") + facet_wrap(vars(cut)) # If we turn contouring off, we can use other geoms, such as tiles: d + stat_density_2d( geom = \"raster\", aes(fill = after_stat(density)), contour = FALSE ) + scale_fill_viridis_c() # Or points: d + stat_density_2d(geom = \"point\", aes(size = after_stat(density)), n = 20, contour = FALSE) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Dot plot — geom_dotplot","title":"Dot plot — geom_dotplot","text":"dot plot, width dot corresponds bin width (maximum width, depending binning algorithm), dots stacked, dot representing one observation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Dot plot — geom_dotplot","text":"","code":"geom_dotplot( mapping = NULL, data = NULL, position = \"identity\", ..., binwidth = NULL, binaxis = \"x\", method = \"dotdensity\", binpositions = \"bygroup\", stackdir = \"up\", stackratio = 1, dotsize = 1, stackgroups = FALSE, origin = NULL, right = TRUE, width = 0.9, drop = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Dot plot — geom_dotplot","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. binwidth method \"dotdensity\", specifies maximum bin width. method \"histodot\", specifies bin width. Defaults 1/30 range data binaxis axis bin along, \"x\" (default) \"y\" method \"dotdensity\" (default) dot-density binning, \"histodot\" fixed bin widths (like stat_bin) binpositions method \"dotdensity\", \"bygroup\" (default) determines positions bins group separately. \"\" determines positions bins data taken together; used aligning dot stacks across multiple groups. stackdir direction stack dots. \"\" (default), \"\", \"center\", \"centerwhole\" (centered, dots aligned) stackratio close stack dots. Default 1, dots just touch. Use smaller values closer, overlapping dots. dotsize diameter dots relative binwidth, default 1. stackgroups dots stacked across groups? effect position = \"stack\" , (geom odd properties). origin method \"histodot\", origin first bin right method \"histodot\", intervals closed right (, b], [, b) width binaxis \"y\", spacing dot stacks dodging. drop TRUE, remove bins zero counts na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Dot plot — geom_dotplot","text":"two basic approaches: dot-density histodot. dot-density binning, bin positions determined data binwidth, maximum width bin. See Wilkinson (1999) details dot-density binning algorithm. histodot binning, bins fixed positions fixed widths, much like histogram. binning along x axis stacking along y axis, numbers y axis meaningful, due technical limitations ggplot2. can hide y axis, one examples, manually scale match number dots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Dot plot — geom_dotplot","text":"geom_dotplot() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype stroke weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Dot plot — geom_dotplot","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x) center bin, binaxis \"x\". after_stat(y) center bin, binaxis \"x\". after_stat(binwidth) maximum width bin method \"dotdensity\"; width bin method \"histodot\". after_stat(count) number points bin. after_stat(ncount) count, scaled maximum 1. after_stat(density) density points bin, scaled integrate 1, method \"histodot\". after_stat(ndensity) density, scaled maximum 1, method \"histodot\".","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Dot plot — geom_dotplot","text":"Wilkinson, L. (1999) Dot plots. American Statistician, 53(3), 276-281.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Dot plot — geom_dotplot","text":"","code":"ggplot(mtcars, aes(x = mpg)) + geom_dotplot() #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5) # Use fixed-width bins ggplot(mtcars, aes(x = mpg)) + geom_dotplot(method=\"histodot\", binwidth = 1.5) # Some other stacking methods ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, stackdir = \"center\") ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, stackdir = \"centerwhole\") # y axis isn't really meaningful, so hide it ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5) + scale_y_continuous(NULL, breaks = NULL) # Overlap dots vertically ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, stackratio = .7) # Expand dot diameter ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, dotsize = 1.25) # Change dot fill colour, stroke width ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, fill = \"white\", stroke = 2) # \\donttest{ # Examples with stacking along y axis instead of x ggplot(mtcars, aes(x = 1, y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"centerwhole\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = factor(vs), fill = factor(cyl), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\", position = \"dodge\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. # binpositions=\"all\" ensures that the bins are aligned between groups ggplot(mtcars, aes(x = factor(am), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\", binpositions=\"all\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. # Stacking multiple groups, with different fill ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + geom_dotplot(stackgroups = TRUE, binwidth = 1, binpositions = \"all\") ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + geom_dotplot(stackgroups = TRUE, binwidth = 1, method = \"histodot\") ggplot(mtcars, aes(x = 1, y = mpg, fill = factor(cyl))) + geom_dotplot(binaxis = \"y\", stackgroups = TRUE, binwidth = 1, method = \"histodot\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":null,"dir":"Reference","previous_headings":"","what":"Horizontal error bars — geom_errorbarh","title":"Horizontal error bars — geom_errorbarh","text":"rotated version geom_errorbar().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Horizontal error bars — geom_errorbarh","text":"","code":"geom_errorbarh( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Horizontal error bars — geom_errorbarh","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Horizontal error bars — geom_errorbarh","text":"geom_errorbarh() understands following aesthetics (required aesthetics bold): xmin xmax y alpha colour group height linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Horizontal error bars — geom_errorbarh","text":"","code":"df <- data.frame( trt = factor(c(1, 1, 2, 2)), resp = c(1, 5, 3, 4), group = factor(c(1, 2, 1, 2)), se = c(0.1, 0.3, 0.3, 0.2) ) # Define the top and bottom of the errorbars p <- ggplot(df, aes(resp, trt, colour = group)) p + geom_point() + geom_errorbarh(aes(xmax = resp + se, xmin = resp - se)) p + geom_point() + geom_errorbarh(aes(xmax = resp + se, xmin = resp - se, height = .2))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":null,"dir":"Reference","previous_headings":"","what":"Draw a function as a continuous curve — geom_function","title":"Draw a function as a continuous curve — geom_function","text":"Computes draws function continuous curve. makes easy superimpose function top existing plot. function called grid evenly spaced values along x axis, results drawn (default) line.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Draw a function as a continuous curve — geom_function","text":"","code":"geom_function( mapping = NULL, data = NULL, stat = \"function\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_function( mapping = NULL, data = NULL, geom = \"function\", position = \"identity\", ..., fun, xlim = NULL, n = 101, args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Draw a function as a continuous curve — geom_function","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data Ignored stat_function(), use. stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. fun Function use. Either 1) anonymous function base rlang formula syntax (see rlang::as_function()) 2) quoted character name referencing function; see examples. Must vectorised. xlim Optionally, specify range function. n Number points interpolate along x axis. args List additional arguments passed function defined fun.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Draw a function as a continuous curve — geom_function","text":"geom_function() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Draw a function as a continuous curve — geom_function","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x)x values along grid. after_stat(y) values function evaluated corresponding x.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Draw a function as a continuous curve — geom_function","text":"","code":"# geom_function() is useful for overlaying functions set.seed(1492) ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density() + geom_function(fun = dnorm, colour = \"red\") # To plot functions without data, specify range of x-axis base <- ggplot() + xlim(-5, 5) base + geom_function(fun = dnorm) base + geom_function(fun = dnorm, args = list(mean = 2, sd = .5)) # The underlying mechanics evaluate the function at discrete points # and connect the points with lines base + stat_function(fun = dnorm, geom = \"point\") base + stat_function(fun = dnorm, geom = \"point\", n = 20) base + stat_function(fun = dnorm, geom = \"polygon\", color = \"blue\", fill = \"blue\", alpha = 0.5) base + geom_function(fun = dnorm, n = 20) # Two functions on the same plot base + geom_function(aes(colour = \"normal\"), fun = dnorm) + geom_function(aes(colour = \"t, df = 1\"), fun = dt, args = list(df = 1)) # Using a custom anonymous function base + geom_function(fun = function(x) 0.5 * exp(-abs(x))) # or using lambda syntax: # base + geom_function(fun = ~ 0.5 * exp(-abs(.x))) # or in R4.1.0 and above: # base + geom_function(fun = \\(x) 0.5 * exp(-abs(x))) # or using a custom named function: # f <- function(x) 0.5 * exp(-abs(x)) # base + geom_function(fun = f) # Using xlim to restrict the range of function ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density() + geom_function(fun = dnorm, colour = \"red\", xlim=c(-1, 1)) # Using xlim to widen the range of function ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density() + geom_function(fun = dnorm, colour = \"red\", xlim=c(-7, 7))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":null,"dir":"Reference","previous_headings":"","what":"Hexagonal heatmap of 2d bin counts — geom_hex","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"Divides plane regular hexagons, counts number cases hexagon, (default) maps number cases hexagon fill. Hexagon bins avoid visual artefacts sometimes generated regular alignment geom_bin_2d().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"","code":"geom_hex( mapping = NULL, data = NULL, stat = \"binhex\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_bin_hex( mapping = NULL, data = NULL, geom = \"hex\", position = \"identity\", ..., bins = 30, binwidth = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Override default connection geom_hex() stat_bin_hex(). information overriding connections, see stat geom arguments work. bins numeric vector giving number bins vertical horizontal directions. Set 30 default. binwidth Numeric vector giving bin width vertical horizontal directions. Overrides bins set.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"geom_hex() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(density) density points bin, scaled integrate 1. after_stat(ncount) count, scaled maximum 1. after_stat(ndensity) density, scaled maximum 1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"","code":"d <- ggplot(diamonds, aes(carat, price)) d + geom_hex() # \\donttest{ # You can control the size of the bins by specifying the number of # bins in each direction: d + geom_hex(bins = 10) d + geom_hex(bins = 30) # Or by specifying the width of the bins d + geom_hex(binwidth = c(1, 1000)) d + geom_hex(binwidth = c(.1, 500)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":null,"dir":"Reference","previous_headings":"","what":"Histograms and frequency polygons — geom_freqpoly","title":"Histograms and frequency polygons — geom_freqpoly","text":"Visualise distribution single continuous variable dividing x axis bins counting number observations bin. Histograms (geom_histogram()) display counts bars; frequency polygons (geom_freqpoly()) display counts lines. Frequency polygons suitable want compare distribution across levels categorical variable.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Histograms and frequency polygons — geom_freqpoly","text":"","code":"geom_freqpoly( mapping = NULL, data = NULL, stat = \"bin\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_histogram( mapping = NULL, data = NULL, stat = \"bin\", position = \"stack\", ..., binwidth = NULL, bins = NULL, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_bin( mapping = NULL, data = NULL, geom = \"bar\", position = \"stack\", ..., binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, breaks = NULL, closed = c(\"right\", \"left\"), pad = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Histograms and frequency polygons — geom_freqpoly","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). binwidth width bins. Can specified numeric value function takes x scale transformation input returns single numeric value. specifying function along grouping structure, function called per group. default use number bins bins, covering range data. always override value, exploring multiple widths find best illustrate stories data. bin width date variable number days time; bin width time variable number seconds. bins Number bins. Overridden binwidth. Defaults 30. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. geom, stat Use override default connection geom_histogram()/geom_freqpoly() stat_bin(). information overriding connections, see stat geom arguments work. center, boundary bin position specifiers. one, center boundary, may specified single plot. center specifies center one bins. boundary specifies boundary two bins. Note either range data, things shifted appropriate integer multiple binwidth. example, center integers use binwidth = 1 center = 0, even 0 outside range data. Alternatively, alignment can specified binwidth = 1 boundary = 0.5, even 0.5 outside range data. breaks Alternatively, can supply numeric vector giving bin boundaries. Overrides binwidth, bins, center, boundary. Can also function takes group-wise values input returns bin boundaries. closed One \"right\" \"left\" indicating whether right left edges bins included bin. pad TRUE, adds empty bins either end x. ensures frequency polygons touch 0. Defaults FALSE.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Histograms and frequency polygons — geom_freqpoly","text":"stat_bin() suitable continuous x data. x data discrete, probably want use stat_count(). default, underlying computation (stat_bin()) uses 30 bins; good default, idea get experimenting different number bins. can also experiment modifying binwidth center boundary arguments. binwidth overrides bins one change time. may need look options uncover full story behind data. addition geom_histogram(), can create histogram plot using scale_x_binned() geom_bar(). method default plots tick marks bar.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Histograms and frequency polygons — geom_freqpoly","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Histograms and frequency polygons — geom_freqpoly","text":"geom_histogram() uses aesthetics geom_bar(); geom_freqpoly() uses aesthetics geom_line().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Histograms and frequency polygons — geom_freqpoly","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(density) density points bin, scaled integrate 1. after_stat(ncount) count, scaled maximum 1. after_stat(ndensity) density, scaled maximum 1. after_stat(width) widths bins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Histograms and frequency polygons — geom_freqpoly","text":"weight binning, weights individual data points (supplied) longer available.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Histograms and frequency polygons — geom_freqpoly","text":"","code":"ggplot(diamonds, aes(carat)) + geom_histogram() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(diamonds, aes(carat)) + geom_histogram(binwidth = 0.01) ggplot(diamonds, aes(carat)) + geom_histogram(bins = 200) # Map values to y to flip the orientation ggplot(diamonds, aes(y = carat)) + geom_histogram() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # For histograms with tick marks between each bin, use `geom_bar()` with # `scale_x_binned()`. ggplot(diamonds, aes(carat)) + geom_bar() + scale_x_binned() # Rather than stacking histograms, it's easier to compare frequency # polygons ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500) ggplot(diamonds, aes(price, colour = cut)) + geom_freqpoly(binwidth = 500) # To make it easier to compare distributions with very different counts, # put density on the y axis instead of the default count ggplot(diamonds, aes(price, after_stat(density), colour = cut)) + geom_freqpoly(binwidth = 500) if (require(\"ggplot2movies\")) { # Often we don't want the height of the bar to represent the # count of observations, but the sum of some other variable. # For example, the following plot shows the number of movies # in each rating. m <- ggplot(movies, aes(rating)) m + geom_histogram(binwidth = 0.1) # If, however, we want to see the number of votes cast in each # category, we need to weight by the votes variable m + geom_histogram(aes(weight = votes), binwidth = 0.1) + ylab(\"votes\") # For transformed scales, binwidth applies to the transformed data. # The bins have constant width on the transformed scale. m + geom_histogram() + scale_x_log10() m + geom_histogram(binwidth = 0.05) + scale_x_log10() # For transformed coordinate systems, the binwidth applies to the # raw data. The bins have constant width on the original scale. # Using log scales does not work here, because the first # bar is anchored at zero, and so when transformed becomes negative # infinity. This is not a problem when transforming the scales, because # no observations have 0 ratings. m + geom_histogram(boundary = 0) + coord_trans(x = \"log10\") # Use boundary = 0, to make sure we don't take sqrt of negative values m + geom_histogram(boundary = 0) + coord_trans(x = \"sqrt\") # You can also transform the y axis. Remember that the base of the bars # has value 0, so log transformations are not appropriate m <- ggplot(movies, aes(x = rating)) m + geom_histogram(binwidth = 0.5) + scale_y_sqrt() } # You can specify a function for calculating binwidth, which is # particularly useful when faceting along variables with # different ranges because the function will be called once per facet ggplot(economics_long, aes(value)) + facet_wrap(~variable, scales = 'free_x') + geom_histogram(binwidth = function(x) 2 * IQR(x) / (length(x)^(1/3)))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":null,"dir":"Reference","previous_headings":"","what":"Jittered points — geom_jitter","title":"Jittered points — geom_jitter","text":"jitter geom convenient shortcut geom_point(position = \"jitter\"). adds small amount random variation location point, useful way handling overplotting caused discreteness smaller datasets.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Jittered points — geom_jitter","text":"","code":"geom_jitter( mapping = NULL, data = NULL, stat = \"identity\", position = \"jitter\", ..., width = NULL, height = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Jittered points — geom_jitter","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. width, height Amount vertical horizontal jitter. jitter added positive negative directions, total spread twice value specified . omitted, defaults 40% resolution data: means jitter values occupy 80% implied bins. Categorical data aligned integers, width height 0.5 spread data possible see distinction categories. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Jittered points — geom_jitter","text":"geom_point() understands following aesthetics (required aesthetics bold): x y alpha colour fill group shape size stroke Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Jittered points — geom_jitter","text":"","code":"p <- ggplot(mpg, aes(cyl, hwy)) p + geom_point() p + geom_jitter() # Add aesthetic mappings p + geom_jitter(aes(colour = class)) # Use smaller width/height to emphasise categories ggplot(mpg, aes(cyl, hwy)) + geom_jitter() ggplot(mpg, aes(cyl, hwy)) + geom_jitter(width = 0.25) # Use larger width/height to completely smooth away discreteness ggplot(mpg, aes(cty, hwy)) + geom_jitter() ggplot(mpg, aes(cty, hwy)) + geom_jitter(width = 0.5, height = 0.5)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":null,"dir":"Reference","previous_headings":"","what":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"Various ways representing vertical interval defined x, ymin ymax. case draws single graphical object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"","code":"geom_crossbar( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., fatten = 2.5, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_errorbar( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_linerange( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_pointrange( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., fatten = 4, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. fatten multiplicative factor used increase size middle bar geom_crossbar() middle point geom_pointrange(). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"geom_linerange() understands following aesthetics (required aesthetics bold): x y ymin xmin ymax xmax alpha colour group linetype linewidth Note geom_pointrange() also understands size size points. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"","code":"# Create a simple example dataset df <- data.frame( trt = factor(c(1, 1, 2, 2)), resp = c(1, 5, 3, 4), group = factor(c(1, 2, 1, 2)), upper = c(1.1, 5.3, 3.3, 4.2), lower = c(0.8, 4.6, 2.4, 3.6) ) p <- ggplot(df, aes(trt, resp, colour = group)) p + geom_linerange(aes(ymin = lower, ymax = upper)) p + geom_pointrange(aes(ymin = lower, ymax = upper)) p + geom_crossbar(aes(ymin = lower, ymax = upper), width = 0.2) p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) # Flip the orientation by changing mapping ggplot(df, aes(resp, trt, colour = group)) + geom_linerange(aes(xmin = lower, xmax = upper)) # Draw lines connecting group means p + geom_line(aes(group = group)) + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) # If you want to dodge bars and errorbars, you need to manually # specify the dodge width p <- ggplot(df, aes(trt, resp, fill = group)) p + geom_col(position = \"dodge\") + geom_errorbar(aes(ymin = lower, ymax = upper), position = \"dodge\", width = 0.25) # Because the bars and errorbars have different widths # we need to specify how wide the objects we are dodging are dodge <- position_dodge(width=0.9) p + geom_col(position = dodge) + geom_errorbar(aes(ymin = lower, ymax = upper), position = dodge, width = 0.25) # When using geom_errorbar() with position_dodge2(), extra padding will be # needed between the error bars to keep them aligned with the bars. p + geom_col(position = \"dodge2\") + geom_errorbar( aes(ymin = lower, ymax = upper), position = position_dodge2(width = 0.5, padding = 0.5) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":null,"dir":"Reference","previous_headings":"","what":"Polygons from a reference map — geom_map","title":"Polygons from a reference map — geom_map","text":"Display polygons map. meant annotation, affect position scales. Note function predates geom_sf() framework work sf geometry columns input. However, can used conjunction geom_sf() layers /coord_sf() (see examples).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Polygons from a reference map — geom_map","text":"","code":"geom_map( mapping = NULL, data = NULL, stat = \"identity\", ..., map, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Polygons from a reference map — geom_map","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. map Data frame contains map coordinates. typically created using fortify() spatial object. must contain columns x long, y lat, region id. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Polygons from a reference map — geom_map","text":"geom_map() understands following aesthetics (required aesthetics bold): map_id alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Polygons from a reference map — geom_map","text":"","code":"# First, a made-up example containing a few polygons, to explain # how `geom_map()` works. It requires two data frames: # One contains the coordinates of each polygon (`positions`), and is # provided via the `map` argument. The other contains the # other the values associated with each polygon (`values`). An id # variable links the two together. ids <- factor(c(\"1.1\", \"2.1\", \"1.2\", \"2.2\", \"1.3\", \"2.3\")) values <- data.frame( id = ids, value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5) ) positions <- data.frame( id = rep(ids, each = 4), x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3), y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2) ) ggplot(values) + geom_map(aes(map_id = id), map = positions) + expand_limits(positions) ggplot(values, aes(fill = value)) + geom_map(aes(map_id = id), map = positions) + expand_limits(positions) ggplot(values, aes(fill = value)) + geom_map(aes(map_id = id), map = positions) + expand_limits(positions) + ylim(0, 3) # Now some examples with real maps if (require(maps)) { crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests) # Equivalent to crimes %>% tidyr::pivot_longer(Murder:Rape) vars <- lapply(names(crimes)[-1], function(j) { data.frame(state = crimes$state, variable = j, value = crimes[[j]]) }) crimes_long <- do.call(\"rbind\", vars) states_map <- map_data(\"state\") # without geospatial coordinate system, the resulting plot # looks weird ggplot(crimes, aes(map_id = state)) + geom_map(aes(fill = Murder), map = states_map) + expand_limits(x = states_map$long, y = states_map$lat) # in combination with `coord_sf()` we get an appropriate result ggplot(crimes, aes(map_id = state)) + geom_map(aes(fill = Murder), map = states_map) + # crs = 5070 is a Conus Albers projection for North America, # see: https://epsg.io/5070 # default_crs = 4326 tells coord_sf() that the input map data # are in longitude-latitude format coord_sf( crs = 5070, default_crs = 4326, xlim = c(-125, -70), ylim = c(25, 52) ) ggplot(crimes_long, aes(map_id = state)) + geom_map(aes(fill = value), map = states_map) + coord_sf( crs = 5070, default_crs = 4326, xlim = c(-125, -70), ylim = c(25, 52) ) + facet_wrap(~variable) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":null,"dir":"Reference","previous_headings":"","what":"Connect observations — geom_path","title":"Connect observations — geom_path","text":"geom_path() connects observations order appear data. geom_line() connects order variable x axis. geom_step() creates stairstep plot, highlighting exactly changes occur. group aesthetic determines cases connected together.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Connect observations — geom_path","text":"","code":"geom_path( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., lineend = \"butt\", linejoin = \"round\", linemitre = 10, arrow = NULL, arrow.fill = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_line( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, ... ) geom_step( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", direction = \"hv\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Connect observations — geom_path","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). arrow Arrow specification, created grid::arrow(). arrow.fill fill colour use arrow head (closed). NULL means use colour aesthetic. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. direction direction stairs: 'vh' vertical horizontal, 'hv' horizontal vertical, 'mid' step half-way adjacent x-values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Connect observations — geom_path","text":"alternative parameterisation geom_segment(), line corresponds single case provides start end coordinates.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Connect observations — geom_path","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Connect observations — geom_path","text":"geom_path() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"missing-value-handling","dir":"Reference","previous_headings":"","what":"Missing value handling","title":"Connect observations — geom_path","text":"geom_path(), geom_line(), geom_step() handle NA follows: NA occurs middle line, breaks line. warning shown, regardless whether na.rm TRUE FALSE. NA occurs start end line na.rm FALSE (default), NA removed warning. NA occurs start end line na.rm TRUE, NA removed silently, without warning.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Connect observations — geom_path","text":"","code":"# geom_line() is suitable for time series ggplot(economics, aes(date, unemploy)) + geom_line() # separate by colour and use \"timeseries\" legend key glyph ggplot(economics_long, aes(date, value01, colour = variable)) + geom_line(key_glyph = \"timeseries\") # You can get a timeseries that run vertically by setting the orientation ggplot(economics, aes(unemploy, date)) + geom_line(orientation = \"y\") # geom_step() is useful when you want to highlight exactly when # the y value changes recent <- economics[economics$date > as.Date(\"2013-01-01\"), ] ggplot(recent, aes(date, unemploy)) + geom_line() ggplot(recent, aes(date, unemploy)) + geom_step() # geom_path lets you explore how two variables are related over time, # e.g. unemployment and personal savings rate m <- ggplot(economics, aes(unemploy/pop, psavert)) m + geom_path() m + geom_path(aes(colour = as.numeric(date))) # Changing parameters ---------------------------------------------- ggplot(economics, aes(date, unemploy)) + geom_line(colour = \"red\") # Use the arrow parameter to add an arrow to the line # See ?arrow for more details c <- ggplot(economics, aes(x = date, y = pop)) c + geom_line(arrow = arrow()) c + geom_line( arrow = arrow(angle = 15, ends = \"both\", type = \"closed\") ) # Control line join parameters df <- data.frame(x = 1:3, y = c(4, 1, 9)) base <- ggplot(df, aes(x, y)) base + geom_path(linewidth = 10) base + geom_path(linewidth = 10, lineend = \"round\") base + geom_path(linewidth = 10, linejoin = \"mitre\", lineend = \"butt\") # You can use NAs to break the line. df <- data.frame(x = 1:5, y = c(1, 2, NA, 4, 5)) ggplot(df, aes(x, y)) + geom_point() + geom_line() #> Warning: Removed 1 row containing missing values or values outside the scale range #> (`geom_point()`). # \\donttest{ # Setting line type vs colour/size # Line type needs to be applied to a line as a whole, so it can # not be used with colour or size that vary across a line x <- seq(0.01, .99, length.out = 100) df <- data.frame( x = rep(x, 2), y = c(qlogis(x), 2 * qlogis(x)), group = rep(c(\"a\",\"b\"), each = 100) ) p <- ggplot(df, aes(x=x, y=y, group=group)) # These work p + geom_line(linetype = 2) p + geom_line(aes(colour = group), linetype = 2) p + geom_line(aes(colour = x)) # But this doesn't should_stop(p + geom_line(aes(colour = x), linetype=2)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":null,"dir":"Reference","previous_headings":"","what":"Points — geom_point","title":"Points — geom_point","text":"point geom used create scatterplots. scatterplot useful displaying relationship two continuous variables. can used compare one continuous one categorical variable, two categorical variables, variation like geom_jitter(), geom_count(), geom_bin_2d() usually appropriate. bubblechart scatterplot third variable mapped size points.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Points — geom_point","text":"","code":"geom_point( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Points — geom_point","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"overplotting","dir":"Reference","previous_headings":"","what":"Overplotting","title":"Points — geom_point","text":"biggest potential problem scatterplot overplotting: whenever points, points may plotted top one another. can severely distort visual appearance plot. one solution problem, techniques can help. can add additional information geom_smooth(), geom_quantile() geom_density_2d(). unique x values, geom_boxplot() may also useful. Alternatively, can summarise number points location display way, using geom_count(), geom_hex(), geom_density2d(). Another technique make points transparent (e.g. geom_point(alpha = 0.05)) small (e.g. geom_point(shape = \".\")).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Points — geom_point","text":"geom_point() understands following aesthetics (required aesthetics bold): x y alpha colour fill group shape size stroke fill aesthetic applies shapes 21-25. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Points — geom_point","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point() # Add aesthetic mappings p + geom_point(aes(colour = factor(cyl))) p + geom_point(aes(shape = factor(cyl))) # A \"bubblechart\": p + geom_point(aes(size = qsec)) # Set aesthetics to fixed value ggplot(mtcars, aes(wt, mpg)) + geom_point(colour = \"red\", size = 3) # \\donttest{ # Varying alpha is useful for large datasets d <- ggplot(diamonds, aes(carat, price)) d + geom_point(alpha = 1/10) d + geom_point(alpha = 1/20) d + geom_point(alpha = 1/100) # } # For shapes that have a border (like 21), you can colour the inside and # outside separately. Use the stroke aesthetic to modify the width of the # border ggplot(mtcars, aes(wt, mpg)) + geom_point(shape = 21, colour = \"black\", fill = \"white\", size = 5, stroke = 5) # \\donttest{ # You can create interesting shapes by layering multiple points of # different sizes p <- ggplot(mtcars, aes(mpg, wt, shape = factor(cyl))) p + geom_point(aes(colour = factor(cyl)), size = 4) + geom_point(colour = \"grey90\", size = 1.5) p + geom_point(colour = \"black\", size = 4.5) + geom_point(colour = \"pink\", size = 4) + geom_point(aes(shape = factor(cyl))) # geom_point warns when missing values have been dropped from the data set # and not plotted, you can turn this off by setting na.rm = TRUE set.seed(1) mtcars2 <- transform(mtcars, mpg = ifelse(runif(32) < 0.2, NA, mpg)) ggplot(mtcars2, aes(wt, mpg)) + geom_point() #> Warning: Removed 4 rows containing missing values or values outside the scale #> range (`geom_point()`). ggplot(mtcars2, aes(wt, mpg)) + geom_point(na.rm = TRUE) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":null,"dir":"Reference","previous_headings":"","what":"Polygons — geom_polygon","title":"Polygons — geom_polygon","text":"Polygons similar paths (drawn geom_path()) except start end points connected inside coloured fill. group aesthetic determines cases connected together polygon. R 3.6 onwards possible draw polygons holes providing subgroup aesthetic differentiates outer ring points describing holes polygon.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Polygons — geom_polygon","text":"","code":"geom_polygon( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", rule = \"evenodd\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Polygons — geom_polygon","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. rule Either \"evenodd\" \"winding\". polygons holes drawn (using subgroup aesthetic) argument defines hole coordinates interpreted. See examples grid::pathGrob() explanation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Polygons — geom_polygon","text":"geom_polygon() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Polygons — geom_polygon","text":"","code":"# When using geom_polygon, you will typically need two data frames: # one contains the coordinates of each polygon (positions), and the # other the values associated with each polygon (values). An id # variable links the two together ids <- factor(c(\"1.1\", \"2.1\", \"1.2\", \"2.2\", \"1.3\", \"2.3\")) values <- data.frame( id = ids, value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5) ) positions <- data.frame( id = rep(ids, each = 4), x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3), y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2) ) # Currently we need to manually merge the two together datapoly <- merge(values, positions, by = c(\"id\")) p <- ggplot(datapoly, aes(x = x, y = y)) + geom_polygon(aes(fill = value, group = id)) p # Which seems like a lot of work, but then it's easy to add on # other features in this coordinate system, e.g.: set.seed(1) stream <- data.frame( x = cumsum(runif(50, max = 0.1)), y = cumsum(runif(50,max = 0.1)) ) p + geom_line(data = stream, colour = \"grey30\", linewidth = 5) # And if the positions are in longitude and latitude, you can use # coord_map to produce different map projections. if (packageVersion(\"grid\") >= \"3.6\") { # As of R version 3.6 geom_polygon() supports polygons with holes # Use the subgroup aesthetic to differentiate holes from the main polygon holes <- do.call(rbind, lapply(split(datapoly, datapoly$id), function(df) { df$x <- df$x + 0.5 * (mean(df$x) - df$x) df$y <- df$y + 0.5 * (mean(df$y) - df$y) df })) datapoly$subid <- 1L holes$subid <- 2L datapoly <- rbind(datapoly, holes) p <- ggplot(datapoly, aes(x = x, y = y)) + geom_polygon(aes(fill = value, group = id, subgroup = subid)) p }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":null,"dir":"Reference","previous_headings":"","what":"A quantile-quantile plot — geom_qq_line","title":"A quantile-quantile plot — geom_qq_line","text":"geom_qq() stat_qq() produce quantile-quantile plots. geom_qq_line() stat_qq_line() compute slope intercept line connecting points specified quartiles theoretical sample distributions.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A quantile-quantile plot — geom_qq_line","text":"","code":"geom_qq_line( mapping = NULL, data = NULL, geom = \"path\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), line.p = c(0.25, 0.75), fullrange = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_qq_line( mapping = NULL, data = NULL, geom = \"path\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), line.p = c(0.25, 0.75), fullrange = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_qq( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_qq( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A quantile-quantile plot — geom_qq_line","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. distribution Distribution function use, x specified dparams Additional parameters passed distribution function. line.p Vector quantiles use fitting Q-Q line, defaults defaults c(.25, .75). fullrange q-q line span full range plot, just data na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"A quantile-quantile plot — geom_qq_line","text":"stat_qq() understands following aesthetics (required aesthetics bold): sample group x y Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_qq_line() understands following aesthetics (required aesthetics bold): sample group x y Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"A quantile-quantile plot — geom_qq_line","text":"calculated 'stat' part layers can accessed delayed evaluation. Variables computed stat_qq(): after_stat(sample) Sample quantiles. after_stat(theoretical) Theoretical quantiles. Variables computed stat_qq_line(): after_stat(x) x-coordinates endpoints line segment connecting points chosen quantiles theoretical sample distributions. after_stat(y) y-coordinates endpoints.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A quantile-quantile plot — geom_qq_line","text":"","code":"# \\donttest{ df <- data.frame(y = rt(200, df = 5)) p <- ggplot(df, aes(sample = y)) p + stat_qq() + stat_qq_line() # Use fitdistr from MASS to estimate distribution params params <- as.list(MASS::fitdistr(df$y, \"t\")$estimate) #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced ggplot(df, aes(sample = y)) + stat_qq(distribution = qt, dparams = params[\"df\"]) + stat_qq_line(distribution = qt, dparams = params[\"df\"]) # Using to explore the distribution of a variable ggplot(mtcars, aes(sample = mpg)) + stat_qq() + stat_qq_line() ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) + stat_qq() + stat_qq_line() # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":null,"dir":"Reference","previous_headings":"","what":"Quantile regression — geom_quantile","title":"Quantile regression — geom_quantile","text":"fits quantile regression data draws fitted quantiles lines. continuous analogue geom_boxplot().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Quantile regression — geom_quantile","text":"","code":"geom_quantile( mapping = NULL, data = NULL, stat = \"quantile\", position = \"identity\", ..., lineend = \"butt\", linejoin = \"round\", linemitre = 10, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_quantile( mapping = NULL, data = NULL, geom = \"quantile\", position = \"identity\", ..., quantiles = c(0.25, 0.5, 0.75), formula = NULL, method = \"rq\", method.args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Quantile regression — geom_quantile","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_quantile() stat_quantile(). information overriding connections, see stat geom arguments work. quantiles conditional quantiles y calculate display formula formula relating y variables x variables method Quantile regression method use. Available options \"rq\" (quantreg::rq()) \"rqss\" (quantreg::rqss()). method.args List additional arguments passed modelling function defined method.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Quantile regression — geom_quantile","text":"geom_quantile() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Quantile regression — geom_quantile","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(quantile) Quantile distribution.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Quantile regression — geom_quantile","text":"","code":"m <- ggplot(mpg, aes(displ, 1 / hwy)) + geom_point() m + geom_quantile() #> Smoothing formula not specified. Using: y ~ x m + geom_quantile(quantiles = 0.5) #> Smoothing formula not specified. Using: y ~ x q10 <- seq(0.05, 0.95, by = 0.05) m + geom_quantile(quantiles = q10) #> Smoothing formula not specified. Using: y ~ x # You can also use rqss to fit smooth quantiles m + geom_quantile(method = \"rqss\") #> Smoothing formula not specified. Using: y ~ qss(x, lambda = 1) # Note that rqss doesn't pick a smoothing constant automatically, so # you'll need to tweak lambda yourself m + geom_quantile(method = \"rqss\", lambda = 0.1) #> Smoothing formula not specified. Using: y ~ qss(x, lambda = 0.1) # Set aesthetics to fixed value m + geom_quantile(colour = \"red\", linewidth = 2, alpha = 0.5) #> Smoothing formula not specified. Using: y ~ x"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":null,"dir":"Reference","previous_headings":"","what":"Ribbons and area plots — geom_ribbon","title":"Ribbons and area plots — geom_ribbon","text":"x value, geom_ribbon() displays y interval defined ymin ymax. geom_area() special case geom_ribbon(), ymin fixed 0 y used instead ymax.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Ribbons and area plots — geom_ribbon","text":"","code":"geom_ribbon( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, outline.type = \"both\" ) geom_area( mapping = NULL, data = NULL, stat = \"align\", position = \"stack\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, ..., outline.type = \"upper\" ) stat_align( mapping = NULL, data = NULL, geom = \"area\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Ribbons and area plots — geom_ribbon","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). outline.type Type outline area; \"\" draws upper lower lines, \"upper\"/\"lower\" draws respective lines . \"full\" draws closed polygon around area. geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Ribbons and area plots — geom_ribbon","text":"area plot continuous analogue stacked bar chart (see geom_bar()), can used show composition whole varies range x. Choosing order different components stacked important, becomes increasing hard see individual pattern move stack. See position_stack() details stacking algorithm. facilitate stacking, default stat = \"align\" interpolates groups common set x-coordinates. turn interpolation, stat = \"identity\" can used instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Ribbons and area plots — geom_ribbon","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Ribbons and area plots — geom_ribbon","text":"geom_ribbon() understands following aesthetics (required aesthetics bold): x y ymin xmin ymax xmax alpha colour fill group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Ribbons and area plots — geom_ribbon","text":"","code":"# Generate data huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron)) h <- ggplot(huron, aes(year)) h + geom_ribbon(aes(ymin=0, ymax=level)) h + geom_area(aes(y = level)) # Orientation cannot be deduced by mapping, so must be given explicitly for # flipped orientation h + geom_area(aes(x = level, y = year), orientation = \"y\") # Add aesthetic mappings h + geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = \"grey70\") + geom_line(aes(y = level)) # The underlying stat_align() takes care of unaligned data points df <- data.frame( g = c(\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"), x = c(1, 3, 5, 2, 4, 6), y = c(2, 5, 1, 3, 6, 7) ) a <- ggplot(df, aes(x, y, fill = g)) + geom_area() # Two groups have points on different X values. a + geom_point(size = 8) + facet_grid(g ~ .) # stat_align() interpolates and aligns the value so that the areas can stack # properly. a + geom_point(stat = \"align\", position = \"stack\", size = 8) # To turn off the alignment, the stat can be set to \"identity\" ggplot(df, aes(x, y, fill = g)) + geom_area(stat = \"identity\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":null,"dir":"Reference","previous_headings":"","what":"Rug plots in the margins — geom_rug","title":"Rug plots in the margins — geom_rug","text":"rug plot compact visualisation designed supplement 2d display two 1d marginal distributions. Rug plots display individual cases best used smaller datasets.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Rug plots in the margins — geom_rug","text":"","code":"geom_rug( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., outside = FALSE, sides = \"bl\", length = unit(0.03, \"npc\"), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Rug plots in the margins — geom_rug","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. outside logical controls whether move rug tassels outside plot area. Default (FALSE). also need use coord_cartesian(clip = \"\"). set TRUE, also consider changing sides argument \"tr\". See examples. sides string controls sides plot rugs appear . can set string containing \"trbl\", top, right, bottom, left. length grid::unit() object sets length rug lines. Use scale expansion avoid overplotting data. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Rug plots in the margins — geom_rug","text":"default, rug lines drawn length corresponds 3% total plot size. Since default scale expansion continuous variables 5% ends scale, rug overlap data points default settings.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Rug plots in the margins — geom_rug","text":"geom_rug() understands following aesthetics (required aesthetics bold): alpha colour group linetype linewidth x y Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Rug plots in the margins — geom_rug","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() p p + geom_rug() p + geom_rug(sides=\"b\") # Rug on bottom only p + geom_rug(sides=\"trbl\") # All four sides # Use jittering to avoid overplotting for smaller datasets ggplot(mpg, aes(displ, cty)) + geom_point() + geom_rug() ggplot(mpg, aes(displ, cty)) + geom_jitter() + geom_rug(alpha = 1/2, position = \"jitter\") # move the rug tassels to outside the plot # remember to set clip = \"off\". p + geom_rug(outside = TRUE) + coord_cartesian(clip = \"off\") # set sides to top right, and then move the margins p + geom_rug(outside = TRUE, sides = \"tr\") + coord_cartesian(clip = \"off\") + theme(plot.margin = margin(1, 1, 1, 1, \"cm\")) # increase the line length and # expand axis to avoid overplotting p + geom_rug(length = unit(0.05, \"npc\")) + scale_y_continuous(expand = c(0.1, 0.1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":null,"dir":"Reference","previous_headings":"","what":"Line segments and curves — geom_segment","title":"Line segments and curves — geom_segment","text":"geom_segment() draws straight line points (x, y) (xend, yend). geom_curve() draws curved line. See underlying drawing function grid::curveGrob() parameters control curve.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Line segments and curves — geom_segment","text":"","code":"geom_segment( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., arrow = NULL, arrow.fill = NULL, lineend = \"butt\", linejoin = \"round\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_curve( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., curvature = 0.5, angle = 90, ncp = 5, arrow = NULL, arrow.fill = NULL, lineend = \"butt\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Line segments and curves — geom_segment","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. arrow specification arrow heads, created grid::arrow(). arrow.fill fill colour use arrow head (closed). NULL means use colour aesthetic. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). curvature numeric value giving amount curvature. Negative values produce left-hand curves, positive values produce right-hand curves, zero produces straight line. angle numeric value 0 180, giving amount skew control points curve. Values less 90 skew curve towards start point values greater 90 skew curve towards end point. ncp number control points used draw curve. control points creates smoother curve.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Line segments and curves — geom_segment","text":"geoms draw single segment/curve per case. See geom_path() need connect points across multiple cases.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Line segments and curves — geom_segment","text":"geom_segment() understands following aesthetics (required aesthetics bold): x y xend yend alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Line segments and curves — geom_segment","text":"","code":"b <- ggplot(mtcars, aes(wt, mpg)) + geom_point() df <- data.frame(x1 = 2.62, x2 = 3.57, y1 = 21.0, y2 = 15.0) b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2, colour = \"curve\"), data = df) + geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2, colour = \"segment\"), data = df) b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2), data = df, curvature = -0.2) b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2), data = df, curvature = 1) b + geom_curve( aes(x = x1, y = y1, xend = x2, yend = y2), data = df, arrow = arrow(length = unit(0.03, \"npc\")) ) if (requireNamespace('maps', quietly = TRUE)) { ggplot(seals, aes(long, lat)) + geom_segment(aes(xend = long + delta_long, yend = lat + delta_lat), arrow = arrow(length = unit(0.1,\"cm\"))) + borders(\"state\") } # Use lineend and linejoin to change the style of the segments df2 <- expand.grid( lineend = c('round', 'butt', 'square'), linejoin = c('round', 'mitre', 'bevel'), stringsAsFactors = FALSE ) df2 <- data.frame(df2, y = 1:9) ggplot(df2, aes(x = 1, y = y, xend = 2, yend = y, label = paste(lineend, linejoin))) + geom_segment( lineend = df2$lineend, linejoin = df2$linejoin, size = 3, arrow = arrow(length = unit(0.3, \"inches\")) ) + geom_text(hjust = 'outside', nudge_x = -0.2) + xlim(0.5, 2) # You can also use geom_segment to recreate plot(type = \"h\") : set.seed(1) counts <- as.data.frame(table(x = rpois(100,5))) counts$x <- as.numeric(as.character(counts$x)) with(counts, plot(x, Freq, type = \"h\", lwd = 10)) ggplot(counts, aes(x, Freq)) + geom_segment(aes(xend = x, yend = 0), linewidth = 10, lineend = \"butt\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":null,"dir":"Reference","previous_headings":"","what":"Smoothed conditional means — geom_smooth","title":"Smoothed conditional means — geom_smooth","text":"Aids eye seeing patterns presence overplotting. geom_smooth() stat_smooth() effectively aliases: use arguments. Use stat_smooth() want display results non-standard geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Smoothed conditional means — geom_smooth","text":"","code":"geom_smooth( mapping = NULL, data = NULL, stat = \"smooth\", position = \"identity\", ..., method = NULL, formula = NULL, se = TRUE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_smooth( mapping = NULL, data = NULL, geom = \"smooth\", position = \"identity\", ..., method = NULL, formula = NULL, se = TRUE, n = 80, span = 0.75, fullrange = FALSE, xseq = NULL, level = 0.95, method.args = list(), na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Smoothed conditional means — geom_smooth","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. method Smoothing method (function) use, accepts either NULL character vector, e.g. \"lm\", \"glm\", \"gam\", \"loess\" function, e.g. MASS::rlm mgcv::gam, stats::lm, stats::loess. \"auto\" also accepted backwards compatibility. equivalent NULL. method = NULL smoothing method chosen based size largest group (across panels). stats::loess() used less 1,000 observations; otherwise mgcv::gam() used formula = y ~ s(x, bs = \"cs\") method = \"REML\". Somewhat anecdotally, loess gives better appearance, \\(O(N^{2})\\) memory, work larger datasets. fewer 1,000 observations want use gam() model method = NULL use, set method = \"gam\", formula = y ~ s(x, bs = \"cs\"). formula Formula use smoothing function, eg. y ~ x, y ~ poly(x, 2), y ~ log(x). NULL default, case method = NULL implies formula = y ~ x fewer 1,000 observations formula = y ~ s(x, bs = \"cs\") otherwise. se Display confidence band around smooth? (TRUE default, see level control.) na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_smooth() stat_smooth(). information overriding connections, see stat geom arguments work. n Number points evaluate smoother. span Controls amount smoothing default loess smoother. Smaller numbers produce wigglier lines, larger numbers produce smoother lines. used loess, .e. method = \"loess\", method = NULL (default) fewer 1,000 observations. fullrange TRUE, smoothing line gets expanded range plot, potentially beyond data. extend line additional padding created expansion. xseq numeric vector values smoother evaluated. NULL (default), xseq internally evaluated sequence n equally spaced points continuous data. level Level confidence band use (0.95 default). method.args List additional arguments passed modelling function defined method.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Smoothed conditional means — geom_smooth","text":"Calculation performed (currently undocumented) predictdf() generic methods. methods standard error bounds computed using predict() method – exceptions loess(), uses t-based approximation, glm(), normal confidence band constructed link scale back-transformed response scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Smoothed conditional means — geom_smooth","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Smoothed conditional means — geom_smooth","text":"geom_smooth() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth weight ymax ymin Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Smoothed conditional means — geom_smooth","text":"calculated 'stat' part layers can accessed delayed evaluation. stat_smooth() provides following variables, depend orientation: after_stat(y) after_stat(x) Predicted value. after_stat(ymin) after_stat(xmin) Lower pointwise confidence band around mean. after_stat(ymax) after_stat(xmax) Upper pointwise confidence band around mean. after_stat(se) Standard error.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Smoothed conditional means — geom_smooth","text":"","code":"ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth() #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # If you need the fitting to be done along the y-axis set the orientation ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(orientation = \"y\") #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Use span to control the \"wiggliness\" of the default loess smoother. # The span is the fraction of points used to fit each local regression: # small numbers make a wigglier curve, larger numbers make a smoother curve. ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(span = 0.3) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Instead of a loess smooth, you can use any other modelling function: ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = lm, se = FALSE) #> `geom_smooth()` using formula = 'y ~ x' ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = lm, formula = y ~ splines::bs(x, 3), se = FALSE) # Smooths are automatically fit to each group (defined by categorical # aesthetics or the group aesthetic) and for each facet. ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + geom_smooth(se = FALSE, method = lm) #> `geom_smooth()` using formula = 'y ~ x' ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(span = 0.8) + facet_wrap(~drv) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # \\donttest{ binomial_smooth <- function(...) { geom_smooth(method = \"glm\", method.args = list(family = \"binomial\"), ...) } # To fit a logistic regression, you need to coerce the values to # a numeric vector lying between 0 and 1. ggplot(rpart::kyphosis, aes(Age, Kyphosis)) + geom_jitter(height = 0.05) + binomial_smooth() #> `geom_smooth()` using formula = 'y ~ x' #> Warning: Failed to fit group 2. #> Caused by error: #> ! y values must be 0 <= y <= 1 ggplot(rpart::kyphosis, aes(Age, as.numeric(Kyphosis) - 1)) + geom_jitter(height = 0.05) + binomial_smooth() #> `geom_smooth()` using formula = 'y ~ x' ggplot(rpart::kyphosis, aes(Age, as.numeric(Kyphosis) - 1)) + geom_jitter(height = 0.05) + binomial_smooth(formula = y ~ splines::ns(x, 2)) # But in this case, it's probably better to fit the model yourself # so you can exercise more control and see whether or not it's a good model. # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":null,"dir":"Reference","previous_headings":"","what":"Line segments parameterised by location, direction and distance — geom_spoke","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"polar parameterisation geom_segment(). useful variables describe direction distance. angles start east increase counterclockwise.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"","code":"geom_spoke( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"geom_spoke() understands following aesthetics (required aesthetics bold): x y angle radius alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"","code":"df <- expand.grid(x = 1:10, y=1:10) set.seed(1) df$angle <- runif(100, 0, 2*pi) df$speed <- runif(100, 0, sqrt(0.1 * df$x)) ggplot(df, aes(x, y)) + geom_point() + geom_spoke(aes(angle = angle), radius = 0.5) ggplot(df, aes(x, y)) + geom_point() + geom_spoke(aes(angle = angle, radius = speed))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":null,"dir":"Reference","previous_headings":"","what":"Text — geom_label","title":"Text — geom_label","text":"Text geoms useful labeling plots. can used scatterplots combination geoms, example, labeling points annotating height bars. geom_text() adds text plot. geom_label() draws rectangle behind text, making easier read.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Text — geom_label","text":"","code":"geom_label( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, label.padding = unit(0.25, \"lines\"), label.r = unit(0.15, \"lines\"), label.size = 0.25, size.unit = \"mm\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_text( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE, size.unit = \"mm\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Text — geom_label","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. jointy specified nudge_x nudge_y. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. parse TRUE, labels parsed expressions displayed described ?plotmath. nudge_x, nudge_y Horizontal vertical adjustment nudge labels . Useful offsetting text points, particularly discrete scales. jointly specified position. label.padding Amount padding around label. Defaults 0.25 lines. label.r Radius rounded corners. Defaults 0.15 lines. label.size Size label border, mm. size.unit size aesthetic interpreted: millimetres (\"mm\", default), points (\"pt\"), centimetres (\"cm\"), inches (\"\"), picas (\"pc\"). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). check_overlap TRUE, text overlaps previous text layer plotted. check_overlap happens draw time order data. Therefore data arranged label column calling geom_text(). Note argument supported geom_label().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Text — geom_label","text":"Note resize plot, text labels stay size, even though size plot area changes. happens \"width\" \"height\" text element 0. Obviously, text labels height width, physical units, data units. reason, stacking dodging text work default, axis limits automatically expanded include text. geom_text() geom_label() add labels row data, even coordinates x, y set single values call geom_label() geom_text(). add labels specified points use annotate() annotate(geom = \"text\", ...) annotate(geom = \"label\", ...). automatically position non-overlapping text labels see ggrepel package.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Text — geom_label","text":"geom_text() understands following aesthetics (required aesthetics bold): x y label alpha angle colour family fontface group hjust lineheight size vjust Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"geom-label-","dir":"Reference","previous_headings":"","what":"geom_label()","title":"Text — geom_label","text":"Currently geom_label() support check_overlap argument. Also, considerably slower geom_text(). fill aesthetic controls background colour label.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"alignment","dir":"Reference","previous_headings":"","what":"Alignment","title":"Text — geom_label","text":"can modify text alignment vjust hjust aesthetics. can either number 0 (right/bottom) 1 (top/left) character (\"left\", \"middle\", \"right\", \"bottom\", \"center\", \"top\"). two special alignments: \"inward\" \"outward\". Inward always aligns text towards center, outward aligns away center.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Text — geom_label","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) p + geom_text() # Avoid overlaps p + geom_text(check_overlap = TRUE) # Labels with background p + geom_label() # Change size of the label p + geom_text(size = 10) # Set aesthetics to fixed value p + geom_point() + geom_text(hjust = 0, nudge_x = 0.05) p + geom_point() + geom_text(vjust = 0, nudge_y = 0.5) p + geom_point() + geom_text(angle = 45) if (FALSE) { # \\dontrun{ # Doesn't work on all systems p + geom_text(family = \"Times New Roman\") } # } # Add aesthetic mappings p + geom_text(aes(colour = factor(cyl))) p + geom_text(aes(colour = factor(cyl))) + scale_colour_discrete(l = 40) p + geom_label(aes(fill = factor(cyl)), colour = \"white\", fontface = \"bold\") # Scale size of text, and change legend key glyph from a to point p + geom_text(aes(size = wt), key_glyph = \"point\") # Scale height of text, rather than sqrt(height) p + geom_text(aes(size = wt), key_glyph = \"point\") + scale_radius(range = c(3,6)) # You can display expressions by setting parse = TRUE. The # details of the display are described in ?plotmath, but note that # geom_text uses strings, not expressions. p + geom_text( aes(label = paste(wt, \"^(\", cyl, \")\", sep = \"\")), parse = TRUE ) # Add a text annotation p + geom_text() + annotate( \"text\", label = \"plot mpg vs. wt\", x = 2, y = 15, size = 8, colour = \"red\" ) # \\donttest{ # Aligning labels and bars -------------------------------------------------- df <- data.frame( x = factor(c(1, 1, 2, 2)), y = c(1, 3, 2, 1), grp = c(\"a\", \"b\", \"a\", \"b\") ) # ggplot2 doesn't know you want to give the labels the same virtual width # as the bars: ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = \"dodge\") + geom_text(aes(label = y), position = \"dodge\") #> Warning: Width not defined #> ℹ Set with `position_dodge(width = ...)` # So tell it: ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = \"dodge\") + geom_text(aes(label = y), position = position_dodge(0.9)) # You can't nudge and dodge text, so instead adjust the y position ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = \"dodge\") + geom_text( aes(label = y, y = y + 0.05), position = position_dodge(0.9), vjust = 0 ) # To place text in the middle of each bar in a stacked barplot, you # need to set the vjust parameter of position_stack() ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp)) + geom_text(aes(label = y), position = position_stack(vjust = 0.5)) # Justification ------------------------------------------------------------- df <- data.frame( x = c(1, 1, 2, 2, 1.5), y = c(1, 2, 1, 2, 1.5), text = c(\"bottom-left\", \"top-left\", \"bottom-right\", \"top-right\", \"center\") ) ggplot(df, aes(x, y)) + geom_text(aes(label = text)) ggplot(df, aes(x, y)) + geom_text(aes(label = text), vjust = \"inward\", hjust = \"inward\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":null,"dir":"Reference","previous_headings":"","what":"Rectangles — geom_raster","title":"Rectangles — geom_raster","text":"geom_rect() geom_tile() thing, parameterised differently: geom_tile() uses center tile size (x, y, width, height), geom_rect() can use locations corners (xmin, xmax, ymin ymax). geom_raster() high performance special case tiles size, pattern fills applied.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Rectangles — geom_raster","text":"","code":"geom_raster( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., hjust = 0.5, vjust = 0.5, interpolate = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_rect( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., linejoin = \"mitre\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_tile( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., linejoin = \"mitre\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Rectangles — geom_raster","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. hjust, vjust horizontal vertical justification grob. justification value number 0 1. Defaults 0.5 , centering pixel data location. interpolate TRUE interpolate linearly, FALSE (default) interpolate. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). linejoin Line join style (round, mitre, bevel).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Rectangles — geom_raster","text":"Please note width height aesthetics true position aesthetics therefore subject scale transformation. transformation aesthetics applied.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Rectangles — geom_raster","text":"geom_rect() understands following aesthetics (required aesthetics bold): x width xmin xmax y height ymin ymax alpha colour fill group linetype linewidth geom_tile() understands x/width y/height combinations. Note geom_raster() ignores colour. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Rectangles — geom_raster","text":"","code":"# The most common use for rectangles is to draw a surface. You always want # to use geom_raster here because it's so much faster, and produces # smaller output when saving to PDF ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) # Interpolation smooths the surface & is most helpful when rendering images. ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density), interpolate = TRUE) # If you want to draw arbitrary rectangles, use geom_tile() or geom_rect() df <- data.frame( x = rep(c(2, 5, 7, 9, 12), 2), y = rep(c(1, 2), each = 5), z = factor(rep(1:5, each = 2)), w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2) ) ggplot(df, aes(x, y)) + geom_tile(aes(fill = z), colour = \"grey50\") ggplot(df, aes(x, y, width = w)) + geom_tile(aes(fill = z), colour = \"grey50\") ggplot(df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = y, ymax = y + 1)) + geom_rect(aes(fill = z), colour = \"grey50\") # \\donttest{ # Justification controls where the cells are anchored df <- expand.grid(x = 0:5, y = 0:5) set.seed(1) df$z <- runif(nrow(df)) # default is compatible with geom_tile() ggplot(df, aes(x, y, fill = z)) + geom_raster() # zero padding ggplot(df, aes(x, y, fill = z)) + geom_raster(hjust = 0, vjust = 0) # Inspired by the image-density plots of Ken Knoblauch cars <- ggplot(mtcars, aes(mpg, factor(cyl))) cars + geom_point() cars + stat_bin_2d(aes(fill = after_stat(count)), binwidth = c(3,1)) cars + stat_bin_2d(aes(fill = after_stat(density)), binwidth = c(3,1)) cars + stat_density( aes(fill = after_stat(density)), geom = \"raster\", position = \"identity\" ) cars + stat_density( aes(fill = after_stat(count)), geom = \"raster\", position = \"identity\" ) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":null,"dir":"Reference","previous_headings":"","what":"Violin plot — geom_violin","title":"Violin plot — geom_violin","text":"violin plot compact display continuous distribution. blend geom_boxplot() geom_density(): violin plot mirrored density plot displayed way boxplot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Violin plot — geom_violin","text":"","code":"geom_violin( mapping = NULL, data = NULL, stat = \"ydensity\", position = \"dodge\", ..., draw_quantiles = NULL, trim = TRUE, bounds = c(-Inf, Inf), scale = \"area\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_ydensity( mapping = NULL, data = NULL, geom = \"violin\", position = \"dodge\", ..., bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", trim = TRUE, scale = \"area\", drop = TRUE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, bounds = c(-Inf, Inf) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Violin plot — geom_violin","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. draw_quantiles (NULL) (default), draw horizontal lines given quantiles density estimate. trim TRUE (default), trim tails violins range data. FALSE, trim tails. bounds Known lower upper bounds estimated data. Default c(-Inf, Inf) means (finite) bounds. bound finite, boundary effect default density estimation corrected reflecting tails outside bounds around closest edge. Data points outside bounds removed warning. scale \"area\" (default), violins area (trimming tails). \"count\", areas scaled proportionally number observations. \"width\", violins maximum width. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_violin() stat_ydensity(). information overriding connections, see stat geom arguments work. bw smoothing bandwidth used. numeric, standard deviation smoothing kernel. character, rule choose bandwidth, listed stats::bw.nrd(). Note automatic calculation bandwidth take weights account. adjust multiplicate bandwidth adjustment. makes possible adjust bandwidth still using bandwidth estimator. example, adjust = 1/2 means use half default bandwidth. kernel Kernel. See list available kernels density(). drop Whether discard groups less 2 observations (TRUE, default) keep groups position adjustment purposes (FALSE).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Violin plot — geom_violin","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Violin plot — geom_violin","text":"geom_violin() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Violin plot — geom_violin","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(density) Density estimate. after_stat(scaled) Density estimate, scaled maximum 1. after_stat(count) Density * number points - probably useless violin plots. after_stat(violinwidth) Density scaled violin plot, according area, counts constant maximum width. after_stat(n) Number points. after_stat(width) Width violin bounding box.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Violin plot — geom_violin","text":"Hintze, J. L., Nelson, R. D. (1998) Violin Plots: Box Plot-Density Trace Synergism. American Statistician 52, 181-184.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Violin plot — geom_violin","text":"","code":"p <- ggplot(mtcars, aes(factor(cyl), mpg)) p + geom_violin() # Orientation follows the discrete axis ggplot(mtcars, aes(mpg, factor(cyl))) + geom_violin() # \\donttest{ p + geom_violin() + geom_jitter(height = 0, width = 0.1) # Scale maximum width proportional to sample size: p + geom_violin(scale = \"count\") # Scale maximum width to 1 for all violins: p + geom_violin(scale = \"width\") # Default is to trim violins to the range of the data. To disable: p + geom_violin(trim = FALSE) # Use a smaller bandwidth for closer density fit (default is 1). p + geom_violin(adjust = .5) # Add aesthetic mappings # Note that violins are automatically dodged when any aesthetic is # a factor p + geom_violin(aes(fill = cyl)) p + geom_violin(aes(fill = factor(cyl))) p + geom_violin(aes(fill = factor(vs))) #> Warning: Groups with fewer than two datapoints have been dropped. #> ℹ Set `drop = FALSE` to consider such groups for position adjustment #> purposes. p + geom_violin(aes(fill = factor(am))) # Set aesthetics to fixed value p + geom_violin(fill = \"grey80\", colour = \"#3366FF\") # Show quartiles p + geom_violin(draw_quantiles = c(0.25, 0.5, 0.75)) # Scales vs. coordinate transforms ------- if (require(\"ggplot2movies\")) { # Scale transformations occur before the density statistics are computed. # Coordinate transformations occur afterwards. Observe the effect on the # number of outliers. m <- ggplot(movies, aes(y = votes, x = rating, group = cut_width(rating, 0.5))) m + geom_violin() m + geom_violin() + scale_y_log10() m + geom_violin() + coord_trans(y = \"log10\") m + geom_violin() + scale_y_log10() + coord_trans(y = \"log10\") # Violin plots with continuous x: # Use the group aesthetic to group observations in violins ggplot(movies, aes(year, budget)) + geom_violin() ggplot(movies, aes(year, budget)) + geom_violin(aes(group = cut_width(year, 10)), scale = \"width\") } #> Warning: Removed 53573 rows containing non-finite outside the scale range #> (`stat_ydensity()`). #> Warning: Groups with fewer than two datapoints have been dropped. #> ℹ Set `drop = FALSE` to consider such groups for position adjustment #> purposes. # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract alt text from a plot — get_alt_text","title":"Extract alt text from a plot — get_alt_text","text":"function returns text can used alt-text webpages etc. Currently use alt label, added + labs(alt = <...>), return empty string, future might try generate alt text information stored plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract alt text from a plot — get_alt_text","text":"","code":"get_alt_text(p, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract alt text from a plot — get_alt_text","text":"p ggplot object ... Arguments passed methods.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Extract alt text from a plot — get_alt_text","text":"text string","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Extract alt text from a plot — get_alt_text","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Returns an empty string get_alt_text(p) #> [1] \"\" # A user provided alt text p <- p + labs( alt = paste(\"A scatterplot showing the negative correlation between engine\", \"displacement as a function of highway miles per gallon\") ) get_alt_text(p) #> [1] \"A scatterplot showing the negative correlation between engine displacement as a function of highway miles per gallon\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":null,"dir":"Reference","previous_headings":"","what":"Resolve and get geom defaults — get_geom_defaults","title":"Resolve and get geom defaults — get_geom_defaults","text":"Resolve get geom defaults","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Resolve and get geom defaults — get_geom_defaults","text":"","code":"get_geom_defaults(geom, theme = theme_get())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Resolve and get geom defaults — get_geom_defaults","text":"geom definition geom: function creates layer, e.g. geom_path(). layer created function string naming geom class snake case without geom_-prefix, e.g. \"contour_filled\". geom class object. theme theme object. Defaults current global theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Resolve and get geom defaults — get_geom_defaults","text":"list aesthetics","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Resolve and get geom defaults — get_geom_defaults","text":"","code":"# Using a function get_geom_defaults(geom_raster) #> fill alpha #> 1 #333333FF NA # Using a layer includes static aesthetics as default get_geom_defaults(geom_tile(fill = \"white\")) #> fill colour linewidth linetype alpha width height #> 1 white NA 0.2 1 NA NA NA # Using a class name get_geom_defaults(\"density_2d\") #> colour linewidth linetype alpha #> 1 #3366FF 0.5 1 NA # Using a class get_geom_defaults(GeomPoint) #> shape colour size fill alpha stroke #> 1 19 black 1.5 NA NA 0.5 # Changed theme get_geom_defaults(\"point\", theme(geom = element_geom(ink = \"purple\"))) #> shape colour size fill alpha stroke #> 1 19 purple 1.5 NA NA 0.5"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract tick information from guides — get_guide_data","title":"Extract tick information from guides — get_guide_data","text":"get_guide_data() builds plot extracts information guide keys. information typically contains positions, values /labels, depending aesthetic queried guide used.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract tick information from guides — get_guide_data","text":"","code":"get_guide_data(plot = get_last_plot(), aesthetic, panel = 1L)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract tick information from guides — get_guide_data","text":"plot ggplot ggplot_build object. aesthetic string describes single aesthetic extract guide information. example: \"colour\", \"size\", \"x\" \"y.sec\". panel integer giving panel number return position guide information.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Extract tick information from guides — get_guide_data","text":"One following: data.frame representing guide key, guide unique aesthetic. list coord support position axes multiple guides match aesthetic. NULL guide key found.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Extract tick information from guides — get_guide_data","text":"","code":"# A standard plot p <- ggplot(mtcars) + aes(mpg, disp, colour = drat, size = drat) + geom_point() + facet_wrap(vars(cyl), scales = \"free_x\") # Guide information for legends get_guide_data(p, \"size\") #> size .value .label #> 1 2.662822 3.0 3.0 #> 2 3.919819 3.5 3.5 #> 3 4.779645 4.0 4.0 #> 4 5.477285 4.5 4.5 # Note that legend guides can be merged merged <- p + guides(colour = \"legend\") get_guide_data(merged, \"size\") #> colour .value .label size #> 1 #1A3855 3.0 3.0 2.662822 #> 2 #28557C 3.5 3.5 3.919819 #> 3 #3874A5 4.0 4.0 4.779645 #> 4 #4894D0 4.5 4.5 5.477285 # Guide information for positions get_guide_data(p, \"x\", panel = 2) #> x .value .label y #> 1 0.0959596 18 18 0 #> 2 0.3484848 19 19 0 #> 3 0.6010101 20 20 0 #> 4 0.8535354 21 21 0 # Coord polar doesn't support proper guides, so we get a list polar <- p + coord_polar() get_guide_data(polar, \"theta\", panel = 2) #> $theta.range #> [1] 17.8 21.4 #> #> $theta.major #> [1] 18 19 20 21 #> #> $theta.minor #> [1] 18.0 18.5 19.0 19.5 20.0 20.5 21.0 #> #> $theta.labels #> [1] \"18\" \"19\" \"20\" \"21\" #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_last_plot.html","id":null,"dir":"Reference","previous_headings":"","what":"Retrieve the last plot to be modified or created. — get_last_plot","title":"Retrieve the last plot to be modified or created. — get_last_plot","text":"Retrieve last plot modified created.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_last_plot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Retrieve the last plot to be modified or created. — get_last_plot","text":"","code":"get_last_plot() last_plot()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":null,"dir":"Reference","previous_headings":"","what":"Accessing a plot's facet strip labels — get_strip_labels","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"functions retrieves labels facet strips labeller applied.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"","code":"get_strip_labels(plot = get_last_plot())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"plot ggplot build ggplot object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"NULL labels, otherwise list data.frames containing labels.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"","code":"# Basic plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() get_strip_labels(p) # empty facets #> NULL get_strip_labels(p + facet_wrap(year ~ cyl)) #> $facets #> year cyl #> 1 1999 4 #> 2 1999 6 #> 3 1999 8 #> 4 2008 4 #> 5 2008 5 #> 6 2008 6 #> 7 2008 8 #> get_strip_labels(p + facet_grid(year ~ cyl)) #> $cols #> cyl #> 1 4 #> 2 5 #> 3 6 #> 4 8 #> #> $rows #> year #> 1 1999 #> 2 2008 #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Get, set, and modify the active theme — get_theme","title":"Get, set, and modify the active theme — get_theme","text":"current/active theme (see theme()) automatically applied every plot draw. Use get_theme() get current theme, set_theme() completely override . update_theme() replace_theme() shorthands changing individual elements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get, set, and modify the active theme — get_theme","text":"","code":"get_theme() theme_get() set_theme(new) theme_set(new) update_theme(...) theme_update(...) replace_theme(...) theme_replace(...) e1 %+replace% e2"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get, set, and modify the active theme — get_theme","text":"new new theme (list theme elements) ... named list theme settings e1, e2 Theme element combine","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get, set, and modify the active theme — get_theme","text":"set_theme(), update_theme(), replace_theme() invisibly return previous theme can easily save , later restore .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"adding-on-to-a-theme","dir":"Reference","previous_headings":"","what":"Adding on to a theme","title":"Get, set, and modify the active theme — get_theme","text":"+ %+replace% can used modify elements themes. + updates elements e1 differ elements specified (NULL) e2. Thus operator can used incrementally add modify attributes ggplot theme. contrast, %+replace% replaces entire element; element theme specified e2 present resulting theme (.e. NULL). Thus operator can used overwrite entire theme. update_theme() uses + operator, unspecified values theme element default values set theme. replace_theme() uses %+replace% completely replace element, unspecified values overwrite current value theme NULL. summary, main differences set_theme(), update_theme(), replace_theme() : set_theme() completely overrides current theme. update_theme() modifies particular element current theme using + operator. replace_theme() modifies particular element current theme using %+replace% operator.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get, set, and modify the active theme — get_theme","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p # Use set_theme() to completely override the current theme. # update_theme() and replace_theme() are similar except they # apply directly to the current/active theme. # update_theme() modifies a particular element of the current theme. # Here we have the old theme so we can later restore it. # Note that the theme is applied when the plot is drawn, not # when it is created. old <- set_theme(theme_bw()) p set_theme(old) update_theme(panel.grid.minor = element_line(colour = \"red\")) p set_theme(old) replace_theme(panel.grid.minor = element_line(colour = \"red\")) p set_theme(old) p # Modifying theme objects ----------------------------------------- # You can use + and %+replace% to modify a theme object. # They differ in how they deal with missing arguments in # the theme elements. add_el <- theme_grey() + theme(text = element_text(family = \"Times\")) add_el$text #> List of 11 #> $ family : chr \"Times\" #> $ face : chr \"plain\" #> $ colour : chr \"black\" #> $ size : num 11 #> $ hjust : num 0.5 #> $ vjust : num 0.5 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 0points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" rep_el <- theme_grey() %+replace% theme(text = element_text(family = \"Times\")) rep_el$text #> List of 11 #> $ family : chr \"Times\" #> $ face : NULL #> $ colour : NULL #> $ size : NULL #> $ hjust : NULL #> $ vjust : NULL #> $ angle : NULL #> $ lineheight : NULL #> $ margin : NULL #> $ debug : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":null,"dir":"Reference","previous_headings":"","what":"Add components to a plot — +.gg","title":"Add components to a plot — +.gg","text":"+ key constructing sophisticated ggplot2 graphics. allows start simple, get complex, checking work step.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Add components to a plot — +.gg","text":"","code":"# S3 method for class 'gg' e1 + e2 e1 %+% e2"},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Add components to a plot — +.gg","text":"e1 object class ggplot() theme(). e2 plot component, described .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"what-can-you-add-","dir":"Reference","previous_headings":"","what":"What can you add?","title":"Add components to a plot — +.gg","text":"can add following types objects: aes() object replaces default aesthetics. layer created geom_ stat_ function adds new layer. scale overrides existing scale. theme() modifies current theme. coord overrides current coordinate system. facet specification overrides current faceting. replace current default data frame, must use %+%, due S3 method precedence issues. can also supply list, case element list added turn.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Add components to a plot — +.gg","text":"","code":"base <- ggplot(mpg, aes(displ, hwy)) + geom_point() base + geom_smooth() #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # To override the data, you must use %+% base %+% subset(mpg, fl == \"p\") # Alternatively, you can add multiple components with a list. # This can be useful to return from a function. base + list(subset(mpg, fl == \"p\"), geom_smooth()) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_dep.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Give a deprecation error, warning, or message, depending on version number. — gg_dep","text":"","code":"gg_dep(version, msg)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_dep.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Give a deprecation error, warning, or message, depending on version number. — gg_dep","text":"version last version ggplot2 function good (words, last version deprecated). msg message print.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":null,"dir":"Reference","previous_headings":"","what":"Interpreter for graphical parameters — gg_par","title":"Interpreter for graphical parameters — gg_par","text":"wrapper grid::gpar() applies ggplot2's interpretation graphical parameters.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Interpreter for graphical parameters — gg_par","text":"","code":"gg_par(..., stroke = NULL, pointsize = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Interpreter for graphical parameters — gg_par","text":"... Named arguments passed gpar(). stroke Linewidth points. Populates lwd grid parameter. pointsize Size points. Populates fontsize grid parameter.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Interpreter for graphical parameters — gg_par","text":"object class 'gpar'.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new ggplot — ggplot","title":"Create a new ggplot — ggplot","text":"ggplot() initializes ggplot object. can used declare input data frame graphic specify set plot aesthetics intended common throughout subsequent layers unless specifically overridden.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new ggplot — ggplot","text":"","code":"ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new ggplot — ggplot","text":"data Default dataset use plot. already data.frame, converted one fortify(). specified, must supplied layer added plot. mapping Default list aesthetic mappings use plot. specified, must supplied layer added plot. ... arguments passed methods. currently used. environment Used prior tidy evaluation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new ggplot — ggplot","text":"ggplot() used construct initial plot object, almost always followed plus sign (+) add components plot. three common patterns used invoke ggplot(): ggplot(data = df, mapping = aes(x, y, aesthetics)) ggplot(data = df) ggplot() first pattern recommended layers use data set aesthetics, although method can also used adding layer using data another data frame. second pattern specifies default data frame use plot, aesthetics defined front. useful one data frame used predominantly plot, aesthetics vary one layer another. third pattern initializes skeleton ggplot object, fleshed layers added. useful multiple data frames used produce different layers, often case complex graphics. data = mapping = specifications arguments optional (often omitted practice), long data mapping values passed function right order. examples , however, left place clarity.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new ggplot — ggplot","text":"","code":"# Create a data frame with some sample data, then create a data frame # containing the mean value for each group in the sample data. set.seed(1) sample_df <- data.frame( group = factor(rep(letters[1:3], each = 10)), value = rnorm(30) ) group_means_df <- setNames( aggregate(value ~ group, sample_df, mean), c(\"group\", \"group_mean\") ) # The following three code blocks create the same graphic, each using one # of the three patterns specified above. In each graphic, the sample data # are plotted in the first layer and the group means data frame is used to # plot larger red points on top of the sample data in the second layer. # Pattern 1 # Both the `data` and `mapping` arguments are passed into the `ggplot()` # call. Those arguments are omitted in the first `geom_point()` layer # because they get passed along from the `ggplot()` call. Note that the # second `geom_point()` layer re-uses the `x = group` aesthetic through # that mechanism but overrides the y-position aesthetic. ggplot(data = sample_df, mapping = aes(x = group, y = value)) + geom_point() + geom_point( mapping = aes(y = group_mean), data = group_means_df, colour = 'red', size = 3 ) # Pattern 2 # Same plot as above, passing only the `data` argument into the `ggplot()` # call. The `mapping` arguments are now required in each `geom_point()` # layer because there is no `mapping` argument passed along from the # `ggplot()` call. ggplot(data = sample_df) + geom_point(mapping = aes(x = group, y = value)) + geom_point( mapping = aes(x = group, y = group_mean), data = group_means_df, colour = 'red', size = 3 ) # Pattern 3 # Same plot as above, passing neither the `data` or `mapping` arguments # into the `ggplot()` call. Both those arguments are now required in # each `geom_point()` layer. This pattern can be particularly useful when # creating more complex graphics with many layers using data from multiple # data frames. ggplot() + geom_point(mapping = aes(x = group, y = value), data = sample_df) + geom_point( mapping = aes(x = group, y = group_mean), data = group_means_df, colour = 'red', size = 3 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Base ggproto classes for ggplot2 — ggplot2-ggproto","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"creating new geom, stat, position, scale another package, need extend ggplot2::Geom, ggplot2::Stat, ggplot2::Position, ggplot2::Scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"geoms","dir":"Reference","previous_headings":"","what":"Geoms","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"geom_*() functions (like geom_point()) return layer contains Geom* object (like GeomPoint). Geom* object responsible rendering data plot. Geom* objects ggproto() object, descended top-level Geom, implements various methods fields. Compared Stat Position, Geom little different execution setup compute functions split . setup_data runs position adjustments, draw_layer() run render time, much later. create new type Geom object, typically want override one following: Either draw_panel(self, data, panel_params, coord) draw_group(self, data, panel_params, coord). draw_panel called per panel, draw_group called per group. Use draw_panel row data represents single element. Use draw_group group represents element (e.g. smooth, violin). data data frame scaled aesthetics. panel_params set per-panel parameters coord. Generally, consider panel_params opaque data structure pass along whenever call coord method. must always call coord$transform(data, panel_params) get (position) scaled data plotting. work non-linear coordinate systems, typically need convert primitive geom (e.g. point, path polygon), pass corresponding draw method munching. Must return grob. Use zeroGrob() nothing draw. draw_key: Renders single legend key. required_aes: character vector aesthetics needed render geom. default_aes: list (generated aes() default values aesthetics. setup_data: Converts width height xmin xmax, ymin ymax values. can potentially set values well. See also new geoms section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"coordinate-systems","dir":"Reference","previous_headings":"","what":"Coordinate systems","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"coord_*() functions (like coord_trans()) return Coord* object (like CoordTrans). Coord* objects ggproto() object, descended top-level Coord. create new type Coord object, typically want implement one following: aspect: Returns desired aspect ratio plot. labels: Returns list containing labels x y. render_fg: Renders foreground elements. render_bg: Renders background elements. render_axis_h: Renders horizontal axes. render_axis_v: Renders vertical axes. backtransform_range(panel_params): Extracts panel range provided panel_params (created setup_panel_params(), see ) back-transforms data coordinates. back-transformation can needed coords coord_trans() range transformed coordinates differs range untransformed coordinates. Returns list two ranges, x y, correspond variables mapped x y aesthetics, even coords coord_flip() x aesthetic shown along y direction vice versa. range(panel_params): Extracts panel range provided panel_params (created setup_panel_params(), see ) returns . Unlike backtransform_range(), function perform back-transformation instead returns final transformed coordinates. Returns list two ranges, x y, correspond variables mapped x y aesthetics, even coords coord_flip() x aesthetic shown along y direction vice versa. transform: Transforms x y coordinates. distance: Calculates distance. is_linear: Returns TRUE coordinate system linear; FALSE otherwise. is_free: Returns TRUE coordinate system supports free positional scales; FALSE otherwise. setup_panel_params(scale_x, scale_y, params): Determines appropriate x y ranges panel, also calculates anything else needed render panel axes, tick positions labels major minor ticks. Returns information named list. setup_data(data, params): Allows coordinate system manipulate plot data. return list data frames. setup_layout(layout, params): Allows coordinate system manipulate layout data frame assigns data panels scales. See also new coords section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"facets","dir":"Reference","previous_headings":"","what":"Facets","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"facet_* functions returns Facet object object Facet subclass. object describes assign data different panels, apply positional scales lay panels, rendered. Extending facets can range simple modifications current facets, laborious rewrites lot gtable() manipulation. examples , please see extension vignette. Facet subclasses, like extendible ggproto classes, range methods can modified. required new subclasses, need modified need arises. required methods : compute_layout: Based layer data compute mapping panels, axes, potentially parameters faceting variable level etc. method must return data.frame containing least columns PANEL, SCALE_X, SCALE_Y containing integer keys mapping PANEL axes use. addition data.frame can contain whatever information necessary assign observations correct panel well determining position panel. map_data: method supplied data layer turn expected supply PANEL column mapping row panel defined layout. Additionally method can also add subtract data points needed e.g. case adding margins facet_grid(). draw_panels: panels assembled gtable object. method receives, among others, list grobs defining content panel generated Geoms Coord objects. responsibility method decorate panels axes strips needed, well position relative gtable. automatic functions work correctly, panel, axis, strip grob name must prefixed \"panel\", \"axis\", \"strip\" respectively. addition methods described , also possible override default behaviour one following methods: setup_params: init_scales: Given master scale x y, create panel specific scales panel defined layout. default simply clone master scale. train_scales: Based layer data train set panel scales. default train data related panel. finish_data: Make last-minute modifications layer data rendered Geoms. default modify . draw_back: Add grob background defined Coord object (usually axis grid) layer stack. default return empty grob panel. draw_front: except returned grob placed layer stack foreground defined Coord object (usually empty). default , , return empty grob. draw_labels: Given gtable returned draw_panels, add axis titles gtable. default add one title side depending position existence axes. extension methods receive content params field params argument, constructor function generally put relevant information field. exception shrink parameter used determine scales retrained Stat transformations applied. See also new facets section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"stats","dir":"Reference","previous_headings":"","what":"Stats","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"stat_*() functions (like stat_bin()) return layer contains Stat* object (like StatBin). Stat* object responsible rendering data plot. Stat* objects ggproto() object, descended top-level Stat, implements various methods fields. create new type Stat object, typically want override one following: One : compute_layer(self, data, scales, ...), compute_panel(self, data, scales, ...), compute_group(self, data, scales, ...). compute_layer() called per layer, compute_panel() called per panel, compute_group() called per group. must return data frame. usually best start overriding compute_group: find substantial performance optimisations, override higher . need read source code default methods see else . data data frame containing variables named according aesthetics mapped . scales list containing x y scales. functions called facets trained, global scales, local individual panels.... contains parameters returned setup_params(). finish_layer(data, params): called layer. Used modify data scales applied, data handed geom rendering. default modify data. Use hook stat needs access actual aesthetic values rather values mapped aesthetic. setup_params(data, params): called layer. Used setup defaults need complete dataset, inform user important choices. return list parameters. setup_data(data, params): called layer, setup_params(). return modified data. Default methods removes rows containing missing value required aesthetics (warning !na.rm). required_aes: character vector aesthetics needed render geom. default_aes: list (generated aes() default values aesthetics. dropped_aes vecor aesthetic names safe drop statistical transformation. classic example weight aesthetic consumed computation stat. See also new stats section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"guides","dir":"Reference","previous_headings":"","what":"Guides","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"guide_*() functions, guide_legend() return object responsible displaying objects plotting panel related actual values. Guide* object ggproto() object, descended top-level Guide, implements methods drawing. create new type Guide object, typically want override one following: Properties: available_aes character vector aesthetics guide supports. value \"\" indicates non-position aesthetics. params named list parameters guide needs function. following roles: params provides defaults guide. names(params) determines valid arguments new_guide(). parameters required render guide. : title, name, position, direction, order hash. build stages, params holds information guide. elements named list characters, giving name theme elements retrieved automatically, example \"legend.text\". hashables expression can evaluated context params. hash evaluated expression determines merge compatibility guides, stored params$hash. Methods: extract_key() Returns data.frame (mapped) breaks labels extracted scale, stored params$key. extract_decor() Returns data.frame containing structured information extracted scale, stored params$decor. decor guide-specific meaning: bar guide_colourbar(), specifies axis.line guide_axis(). extract_params() Updates params , unstructured information scale. example inheriting guide's title scale$name field. transform() Updates params$key based coordinates. applies position guides, rescales aesthetic [0, 1] range. merge() Combines information multiple guides params$hash. ensures e.g. guide_legend() can display shape colour guide. process_layers() Extract information layers. acts mostly filter layers include (typically) forwarded get_layer_key(). get_layer_key() can used gather information legend keys displayed. setup_params() Set parameters beginning drawing stages. can used overrule user-supplied parameters perform checks params property. override_elements() Take populated theme elements derived elements property allows overriding theme settings. build_title() Render guide's title. build_labels() Render guide's labels. build_decor() Render params$decor, different every guide. build_ticks() Render tick marks. measure_grobs() Measure dimensions graphical objects produced build_*() methods used layout assembly. arrange_layout() Set layout graphical objects produced build_*() methods arranged. assemble_drawing() Take graphical objects produced build_*() methods, measurements measure_grobs() layout arrange_layout() finalise guide. add_title Adds title gtable, taking account size title well gtable size.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"positions","dir":"Reference","previous_headings":"","what":"Positions","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"position_*() functions (like position_dodge()) return Position* object (like PositionDodge). Position* object responsible adjusting position overlapping geoms. way position_* functions work slightly different geom_* stat_* functions, position_* function actually \"instantiates\" Position* object creating descendant, returns . Position* objects ggproto() object, descended top-level Position, implements following methods: compute_layer(self, data, params, panel) called per layer. panel currently internal data structure, method overridden. compute_panel(self, data, params, scales) called per panel return modified data frame. data data frame containing variables named according aesthetics mapped . scales list containing x y scales. functions called facets trained, global scales, local individual panels. params contains parameters returned setup_params(). setup_params(data, params): called layer. Used setup defaults need complete dataset, inform user important choices. return list parameters. setup_data(data, params): called layer, setup_params(). return modified data. Default checks required aesthetics present. following fields required_aes: character vector giving aesthetics must present position adjustment work. See also new positions section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"scales","dir":"Reference","previous_headings":"","what":"Scales","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"scale_* functions like scale_x_continuous() return Scale* object like ScaleContinuous. Scale* objects ggproto() object, descended top-level Scale. Properties documented continuous_scale() discrete_scale(): call call continuous_scale() discrete_scale() constructed scale. range One continuous_range() discrete_range(). Methods: is_discrete() Returns TRUE scale discrete scale is_empty() Returns TRUE scale contains information (.e., information calculate limits). clone() Returns copy scale can trained independently without affecting original scale. transform() Transforms vector values using self$trans. occurs Stat calculated. train() Update self$range observed (transformed) data values vector (possibly) new values. reset() Reset self$range observed data values. discrete position scales, continuous range reset. map() Map transformed data values output value determined self$rescale() self$palette (except position scales, use default implementation method). output corresponds transformed data value aesthetic space (e.g., color, line width, size). rescale() Rescale transformed data range 0, 1. useful position scales. continuous scales, rescale() uses rescaler provided constructor. rescale() apply self$oob() input, means discrete values outside limits NA, values outside range values less 0 greater 1. allows guides control --bounds values displayed. transform_df(), train_df(), map_df() _df variants accept data frame, apply transform, train, map methods (respectively) columns whose names self$aesthetics. get_limits() Calculates final scale limits transformed data space based combination self$limits /range observed values (self$range). get_breaks() Calculates final scale breaks transformed data space based combination self$breaks, self$trans$breaks() (continuous scales), limits. Breaks outside limits assigned value NA (continuous scales) dropped (discrete scales). get_labels() Calculates labels given set (transformed) breaks based combination self$labels breaks. get_breaks_minor() continuous scales, calculates final scale minor breaks transformed data space based rescaled breaks, value self$minor_breaks, value self$trans$minor_breaks(). Discrete scales always return NULL. get_transformation() Returns scale's transformation object. make_title() Hook modify title calculated guide construction (non-position scales) Layout calculates x y labels (position scales). methods valid position (x y) scales: dimension() continuous scales, dimension concept limits. discrete scales, dimension() returns continuous range, limits placed integer positions. dimension() optionally expands range given expansion length 4 (see expansion()). break_info() Returns list() calculated values needed Coord transform values transformed data space. Axis grid guides also use values draw guides. called (usually expanded) continuous range, returned self$dimension() (even discrete scales). list components major_source (self$get_breaks() continuous scales, seq_along(self$get_breaks()) discrete scales), major (rescaled value major_source, ignoring self$rescaler), minor (rescaled value minor_source, ignoring self$rescaler), range (range passed break_info()), labels (label values, one element breaks). axis_order() One c(\"primary\", \"secondary\") c(\"secondary\", \"primary\") make_sec_title() Hook modify title second axis calculated Layout calculates x y labels.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-package.html","id":null,"dir":"Reference","previous_headings":"","what":"ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics — ggplot2-package","title":"ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics — ggplot2-package","text":"system 'declaratively' creating graphics, based \"Grammar Graphics\". provide data, tell 'ggplot2' map variables aesthetics, graphical primitives use, takes care details.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-package.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics — ggplot2-package","text":"Maintainer: Thomas Lin Pedersen thomas.pedersen@posit.co (ORCID) Authors: Hadley Wickham hadley@posit.co (ORCID) Winston Chang (ORCID) Lionel Henry Kohske Takahashi Claus Wilke (ORCID) Kara Woo (ORCID) Hiroaki Yutani (ORCID) Dewey Dunnington (ORCID) Teun van den Brand (ORCID) contributors: Posit, PBC [copyright holder, funder]","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplotGrob.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate a ggplot2 plot grob. — ggplotGrob","title":"Generate a ggplot2 plot grob. — ggplotGrob","text":"Generate ggplot2 plot grob.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplotGrob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate a ggplot2 plot grob. — ggplotGrob","text":"","code":"ggplotGrob(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplotGrob.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate a ggplot2 plot grob. — ggplotGrob","text":"x ggplot2 object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":null,"dir":"Reference","previous_headings":"","what":"Add custom objects to ggplot — ggplot_add","title":"Add custom objects to ggplot — ggplot_add","text":"generic allows add methods adding custom objects ggplot +.gg.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Add custom objects to ggplot — ggplot_add","text":"","code":"ggplot_add(object, plot, object_name)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Add custom objects to ggplot — ggplot_add","text":"object object add plot plot ggplot object add object object_name name object add","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Add custom objects to ggplot — ggplot_add","text":"modified ggplot object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Add custom objects to ggplot — ggplot_add","text":"Custom methods ggplot_add() intended update plot variable using information custom object. can become convenient writing extensions build pre-existing grammar like layers, facets, coords themes. ggplot_add() function never intended used directly, triggered object added plot via + operator. Please note full plot object exposed point, comes responsibility returning plot intact.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Add custom objects to ggplot — ggplot_add","text":"","code":"# making a new method for the generic # in this example, we apply a text element to the text theme setting ggplot_add.element_text <- function(object, plot, object_name) { plot + theme(text = object) } # we can now use `+` to add our object to a plot ggplot(mpg, aes(displ, cty)) + geom_point() + element_text(colour = \"red\") #> Error in ggplot_add(object, p, objectname): Can't add `element_text(colour = \"red\")` to a object. # clean-up rm(ggplot_add.element_text)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":null,"dir":"Reference","previous_headings":"","what":"Build ggplot for rendering. — ggplot_build","title":"Build ggplot for rendering. — ggplot_build","text":"ggplot_build() takes plot object, performs steps necessary produce object can rendered. function outputs two pieces: list data frames (one layer), panel object, contain information axis limits, breaks etc.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Build ggplot for rendering. — ggplot_build","text":"","code":"ggplot_build(plot) get_layer_data(plot = get_last_plot(), i = 1L) layer_data(plot = get_last_plot(), i = 1L) get_panel_scales(plot = get_last_plot(), i = 1L, j = 1L) layer_scales(plot = get_last_plot(), i = 1L, j = 1L) get_layer_grob(plot = get_last_plot(), i = 1L) layer_grob(plot = get_last_plot(), i = 1L)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Build ggplot for rendering. — ggplot_build","text":"plot ggplot object integer. get_layer_data(), data return (order added plot). get_layer_grob(), grob return (order added plot). get_panel_scales(), row facet return scales . j integer. get_panel_scales(), column facet return scales .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Build ggplot for rendering. — ggplot_build","text":"get_layer_data(), get_layer_grob(), get_panel_scales() helper functions return data, grob, scales associated given layer. useful tests.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":null,"dir":"Reference","previous_headings":"","what":"Build a plot with all the usual bits and pieces. — ggplot_gtable","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"function builds grobs necessary displaying plot, stores special data structure called gtable(). object amenable programmatic manipulation, want (e.g.) make legend box 2 cm wide, combine multiple plots single display, preserving aspect ratios across plots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"","code":"ggplot_gtable(data)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"data plot data generated ggplot_build()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"gtable() object","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new ggproto object — ggproto","title":"Create a new ggproto object — ggproto","text":"Construct new object ggproto(), test .ggproto(), access parent methods/fields ggproto_parent().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new ggproto object — ggproto","text":"","code":"ggproto(`_class` = NULL, `_inherit` = NULL, ...) ggproto_parent(parent, self) is.ggproto(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new ggproto object — ggproto","text":"_class Class name assign object. stored class attribute object. optional: NULL (default), class name added object. _inherit ggproto object inherit . NULL, inherit object. ... list named members ggproto object. can functions become methods class regular objects. parent, self Access parent class parent object self. x object test.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new ggproto object — ggproto","text":"ggproto implements protype based OO system blurs lines classes instances. inspired proto package, important differences. Notably, cleanly supports cross-package inheritance, faster performance. cases, creating new OO system used single package good idea. However, least-bad solution ggplot2 required fewest changes already complex code base.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"calling-methods","dir":"Reference","previous_headings":"","what":"Calling methods","title":"Create a new ggproto object — ggproto","text":"ggproto methods can take optional self argument: present, regular method; absent, \"static\" method (.e. use fields). Imagine ggproto object Adder, method addx = function(self, n) n + self$x. , call function, use Adder$addx(10) – self passed automatically wrapper function. self located anywhere function signature, although customarily comes first.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"calling-methods-in-a-parent","dir":"Reference","previous_headings":"","what":"Calling methods in a parent","title":"Create a new ggproto object — ggproto","text":"explicitly call methods parent, use ggproto_parent(Parent, self).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"working-with-ggproto-classes","dir":"Reference","previous_headings":"","what":"Working with ggproto classes","title":"Create a new ggproto object — ggproto","text":"ggproto objects constructed build top environments, ramifications. Environments follow 'copy modify' semantics one might accustomed regular objects. Instead 'modify place' semantics.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new ggproto object — ggproto","text":"","code":"Adder <- ggproto(\"Adder\", x = 0, add = function(self, n) { self$x <- self$x + n self$x } ) is.ggproto(Adder) #> [1] TRUE Adder$add(10) #> [1] 10 Adder$add(10) #> [1] 20 Doubler <- ggproto(\"Doubler\", Adder, add = function(self, n) { ggproto_parent(Adder, self)$add(n * 2) } ) Doubler$x #> [1] 20 Doubler$add(10) #> [1] 40"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":null,"dir":"Reference","previous_headings":"","what":"Save a ggplot (or other grid object) with sensible defaults — ggsave","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"ggsave() convenient function saving plot. defaults saving last plot displayed, using size current graphics device. also guesses type graphics device extension.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"","code":"ggsave( filename, plot = get_last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c(\"in\", \"cm\", \"mm\", \"px\"), dpi = 300, limitsize = TRUE, bg = NULL, create.dir = FALSE, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"filename File name create disk. plot Plot save, defaults last plot displayed. device Device use. Can either device function (e.g. png), one \"eps\", \"ps\", \"tex\" (pictex), \"pdf\", \"jpeg\", \"tiff\", \"png\", \"bmp\", \"svg\" \"wmf\" (windows ). NULL (default), device guessed based filename extension. path Path directory save plot : path filename combined create fully qualified file name. Defaults working directory. scale Multiplicative scaling factor. width, height Plot size units expressed units argument. supplied, uses size current graphics device. units One following units width height arguments expressed: \"\", \"cm\", \"mm\" \"px\". dpi Plot resolution. Also accepts string input: \"retina\" (320), \"print\" (300), \"screen\" (72). applies converting pixel units, typical raster output types. limitsize TRUE (default), ggsave() save images larger 50x50 inches, prevent common error specifying dimensions pixels. bg Background colour. NULL, uses plot.background fill value plot theme. create.dir Whether create new directories non-existing directory specified filename path (TRUE) return error (FALSE, default). FALSE run interactive session, prompt appear asking create new directory necessary. ... arguments passed graphics device function, specified device.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"Note: Filenames page numbers can generated including C integer format expression, %03d (default file name R graphics devices, see e.g. png()). Thus, filename = \"figure%03d.png\" produce successive filenames figure001.png, figure002.png, figure003.png, etc. write filename containing % sign, use %%. example, filename = \"figure-100%%.png\" produce filename figure-100%.png.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"saving-images-without-ggsave-","dir":"Reference","previous_headings":"","what":"Saving images without ggsave()","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"cases ggsave() simplest way save plot, sometimes may wish save plot writing directly graphics device. , can open regular R graphics device png() pdf(), print plot, close device using dev.(). technique illustrated examples section.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"","code":"if (FALSE) { # \\dontrun{ ggplot(mtcars, aes(mpg, wt)) + geom_point() # here, the device is inferred from the filename extension ggsave(\"mtcars.pdf\") ggsave(\"mtcars.png\") # setting dimensions of the plot ggsave(\"mtcars.pdf\", width = 4, height = 4) ggsave(\"mtcars.pdf\", width = 20, height = 20, units = \"cm\") # passing device-specific arguments to '...' ggsave(\"mtcars.pdf\", colormodel = \"cmyk\") # delete files with base::unlink() unlink(\"mtcars.pdf\") unlink(\"mtcars.png\") # specify device when saving to a file with unknown extension # (for example a server supplied temporary file) file <- tempfile() ggsave(file, device = \"pdf\") unlink(file) # save plot to file without using ggsave p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() png(\"mtcars.png\") print(p) dev.off() } # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":null,"dir":"Reference","previous_headings":"","what":"Visualise sf objects — CoordSf","title":"Visualise sf objects — CoordSf","text":"set geom, stat, coord used visualise simple feature (sf) objects. simple plots, need geom_sf() uses stat_sf() adds coord_sf() . geom_sf() unusual geom draw different geometric objects depending simple features present data: can get points, lines, polygons. text labels, can use geom_sf_text() geom_sf_label().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Visualise sf objects — CoordSf","text":"","code":"coord_sf( xlim = NULL, ylim = NULL, expand = TRUE, crs = NULL, default_crs = NULL, datum = sf::st_crs(4326), label_graticule = waiver(), label_axes = waiver(), lims_method = \"cross\", ndiscr = 100, default = FALSE, clip = \"on\" ) geom_sf( mapping = aes(), data = NULL, stat = \"sf\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) geom_sf_label( mapping = aes(), data = NULL, stat = \"sf_coordinates\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, label.padding = unit(0.25, \"lines\"), label.r = unit(0.15, \"lines\"), label.size = 0.25, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, fun.geometry = NULL ) geom_sf_text( mapping = aes(), data = NULL, stat = \"sf_coordinates\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, fun.geometry = NULL ) stat_sf( mapping = NULL, data = NULL, geom = \"rect\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Visualise sf objects — CoordSf","text":"xlim, ylim Limits x y axes. limits specified units default CRS. default, means projected coordinates (default_crs = NULL). limit specifications translate exact region shown plot can confusing non-linear rotated coordinate systems used default crs. First, different methods can preferable different conditions. See parameter lims_method details. Second, specifying limits along one direction can affect automatically generated limits along direction. Therefore, best always specify limits x y. Third, specifying limits via position scales xlim()/ylim() strongly discouraged, can result data points dropped plot even though visible final plot region. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. crs coordinate reference system (CRS) data projected plotting. specified, use CRS defined first sf layer plot. default_crs default CRS used non-sf layers (carry CRS information) scale limits. default value NULL means setting crs used. implies non-sf layers scale limits assumed specified projected coordinates. useful alternative setting default_crs = sf::st_crs(4326), means x y positions interpreted longitude latitude, respectively, World Geodetic System 1984 (WGS84). datum CRS provides datum use generating graticules. label_graticule Character vector indicating graticule lines labeled . Meridians run north-south, letters \"N\" \"S\" indicate labeled north south end points, respectively. Parallels run east-west, letters \"E\" \"W\" indicate labeled east west end points, respectively. Thus, label_graticule = \"SW\" label meridians south end parallels west end, whereas label_graticule = \"EW\" label parallels ends meridians . meridians parallels can general intersect side plot panel, choice label_graticule labels guaranteed reside one particular side plot panel. Also, label_graticule can cause labeling artifacts, particular graticule line coincides edge plot panel. circumstances, label_axes generally yield better results used instead. parameter can used alone combination label_axes. label_axes Character vector named list character values specifying graticule lines (meridians parallels) labeled side plot. Meridians indicated \"E\" (East) parallels \"N\" (North). Default \"--EN\", specifies (clockwise top) labels top, none right, meridians bottom, parallels left. Alternatively, setting specified list(bottom = \"E\", left = \"N\"). parameter can used alone combination label_graticule. lims_method Method specifying scale limits converted limits plot region. effect default_crs = NULL. non-linear CRS (e.g., perspective centered around North pole), available methods yield widely differing results, may want try various options. Methods currently implemented include \"cross\" (default), \"box\", \"orthogonal\", \"geometry_bbox\". method \"cross\", limits along one direction (e.g., longitude) applied midpoint direction (e.g., latitude). method avoids excessively large limits rotated coordinate systems means sometimes limits need expanded little extreme data points included final plot region. contrast, method \"box\", box generated limits along directions, limits projected coordinates chosen entire box visible. method can yield plot regions large. Finally, method \"orthogonal\" applies limits separately along axis, method \"geometry_bbox\" ignores limit information except bounding boxes objects geometry aesthetic. ndiscr Number segments use discretising graticule lines; try increasing number graticules look incorrect. default default coordinate system? FALSE (default), replacing coordinate system another one creates message alerting user coordinate system replaced. TRUE, warning suppressed. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins. mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also set one \"polygon\", \"line\", \"point\" override default legend. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. parse TRUE, labels parsed expressions displayed described ?plotmath. nudge_x, nudge_y Horizontal vertical adjustment nudge labels . Useful offsetting text points, particularly discrete scales. jointly specified position. label.padding Amount padding around label. Defaults 0.25 lines. label.r Radius rounded corners. Defaults 0.15 lines. label.size Size label border, mm. fun.geometry function takes sfc object returns sfc_POINT length input. NULL, function(x) sf::st_point_on_surface(sf::st_zm(x)) used. Note function may warn incorrectness result data projected, can ignore except really care exact locations. check_overlap TRUE, text overlaps previous text layer plotted. check_overlap happens draw time order data. Therefore data arranged label column calling geom_text(). Note argument supported geom_label(). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"geometry-aesthetic","dir":"Reference","previous_headings":"","what":"Geometry aesthetic","title":"Visualise sf objects — CoordSf","text":"geom_sf() uses unique aesthetic: geometry, giving column class sfc containing simple features data. three ways supply geometry aesthetic: nothing: default geom_sf() assumes stored geometry column. Explicitly pass sf object data argument. use primary geometry column, matter called. Supply using aes(geometry = my_column) Unlike aesthetics, geometry never inherited plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"crs","dir":"Reference","previous_headings":"","what":"CRS","title":"Visualise sf objects — CoordSf","text":"coord_sf() ensures layers use common CRS. can either specify using crs param, coord_sf() take first layer defines CRS.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"combining-sf-layers-and-regular-geoms","dir":"Reference","previous_headings":"","what":"Combining sf layers and regular geoms","title":"Visualise sf objects — CoordSf","text":"regular geoms, geom_point(), geom_path(), geom_text(), geom_polygon() etc. work fine coord_sf(). However using geoms, two problems arise. First, CRS used x y coordinates used non-sf geoms? CRS applied non-sf geoms set default_crs parameter, defaults NULL, means positions non-sf geoms interpreted projected coordinates coordinate system set crs parameter. setting allows complete control exactly items placed plot canvas, may require understanding projections work generate data projected coordinates. alternative, can set default_crs = sf::st_crs(4326), World Geodetic System 1984 (WGS84). means x y positions interpreted longitude latitude, respectively. can also specify valid CRS default CRS non-sf geoms. second problem arises non-sf geoms straight lines interpreted projected space default_crs set NULL. approach coord_sf() takes break straight lines small pieces (.e., segmentize ) transform pieces projected coordinates. default setting x y interpreted longitude latitude, approach means horizontal lines follow parallels vertical lines follow meridians. need different approach handling straight lines, manually segmentize project coordinates generate plot projected coordinates.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Visualise sf objects — CoordSf","text":"","code":"if (requireNamespace(\"sf\", quietly = TRUE)) { nc <- sf::st_read(system.file(\"shape/nc.shp\", package = \"sf\"), quiet = TRUE) ggplot(nc) + geom_sf(aes(fill = AREA)) # If not supplied, coord_sf() will take the CRS from the first layer # and automatically transform all other layers to use that CRS. This # ensures that all data will correctly line up nc_3857 <- sf::st_transform(nc, 3857) ggplot() + geom_sf(data = nc) + geom_sf(data = nc_3857, colour = \"red\", fill = NA) # Unfortunately if you plot other types of feature you'll need to use # show.legend to tell ggplot2 what type of legend to use nc_3857$mid <- sf::st_centroid(nc_3857$geometry) ggplot(nc_3857) + geom_sf(colour = \"white\") + geom_sf(aes(geometry = mid, size = AREA), show.legend = \"point\") # You can also use layers with x and y aesthetics. To have these interpreted # as longitude/latitude you need to set the default CRS in coord_sf() ggplot(nc_3857) + geom_sf() + annotate(\"point\", x = -80, y = 35, colour = \"red\", size = 4) + coord_sf(default_crs = sf::st_crs(4326)) # To add labels, use geom_sf_label(). ggplot(nc_3857[1:3, ]) + geom_sf(aes(fill = AREA)) + geom_sf_label(aes(label = NAME)) } # Thanks to the power of sf, a geom_sf nicely handles varying projections # setting the aspect ratio correctly. if (requireNamespace('maps', quietly = TRUE)) { library(maps) world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE)) ggplot() + geom_sf(data = world1) world2 <- sf::st_transform( world1, \"+proj=laea +y_0=0 +lon_0=155 +lat_0=-90 +ellps=WGS84 +no_defs\" ) ggplot() + geom_sf(data = world2) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":null,"dir":"Reference","previous_headings":"","what":"Complete themes — ggtheme","title":"Complete themes — ggtheme","text":"complete themes control non-data display. Use theme() just need tweak display existing theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Complete themes — ggtheme","text":"","code":"theme_grey( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_gray( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_bw( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_linedraw( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_light( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_dark( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_minimal( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_classic( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_void( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_test( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Complete themes — ggtheme","text":"base_size base font size, given pts. base_family base font family header_family font family titles headers. default, NULL, uses theme inheritance set font. setting affects axis titles, legend titles, plot title tag text. base_line_size base size line elements base_rect_size base size rect elements","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Complete themes — ggtheme","text":"theme_gray() signature ggplot2 theme grey background white gridlines, designed put data forward yet make comparisons easy. theme_bw() classic dark--light ggplot2 theme. May work better presentations displayed projector. theme_linedraw() theme black lines various widths white backgrounds, reminiscent line drawing. Serves purpose similar theme_bw(). Note theme thin lines (<< 1 pt) journals may refuse. theme_light() theme similar theme_linedraw() light grey lines axes, direct attention towards data. theme_dark() dark cousin theme_light(), similar line sizes dark background. Useful make thin coloured lines pop . theme_minimal() minimalistic theme background annotations. theme_classic() classic-looking theme, x y axis lines gridlines. theme_void() completely empty theme. theme_test() theme visual unit tests. ideally never change except new features.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Complete themes — ggtheme","text":"","code":"mtcars2 <- within(mtcars, { vs <- factor(vs, labels = c(\"V-shaped\", \"Straight\")) am <- factor(am, labels = c(\"Automatic\", \"Manual\")) cyl <- factor(cyl) gear <- factor(gear) }) p1 <- ggplot(mtcars2) + geom_point(aes(x = wt, y = mpg, colour = gear)) + labs( title = \"Fuel economy declines as weight increases\", subtitle = \"(1973-74)\", caption = \"Data from the 1974 Motor Trend US magazine.\", tag = \"Figure 1\", x = \"Weight (1000 lbs)\", y = \"Fuel economy (mpg)\", colour = \"Gears\" ) p1 + theme_gray() # the default p1 + theme_bw() p1 + theme_linedraw() p1 + theme_light() p1 + theme_dark() p1 + theme_minimal() p1 + theme_classic() p1 + theme_void() # Theme examples with panels # \\donttest{ p2 <- p1 + facet_grid(vs ~ am) p2 + theme_gray() # the default p2 + theme_bw() p2 + theme_linedraw() p2 + theme_light() p2 + theme_dark() p2 + theme_minimal() p2 + theme_classic() p2 + theme_void() # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/graphical-units.html","id":null,"dir":"Reference","previous_headings":"","what":"Graphical units — graphical-units","title":"Graphical units — graphical-units","text":"Multiply size mm constants order convert units grid uses internally lwd fontsize.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/graphical-units.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Graphical units — graphical-units","text":"","code":".pt .stroke"},{"path":"https://ggplot2.tidyverse.org/dev/reference/graphical-units.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Graphical units — graphical-units","text":"object class numeric length 1. object class numeric length 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":null,"dir":"Reference","previous_headings":"","what":"Axis guide — guide_axis","title":"Axis guide — guide_axis","text":"Axis guides visual representation position scales like created scale_(x|y)_continuous() scale_(x|y)_discrete().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Axis guide — guide_axis","text":"","code":"guide_axis( title = waiver(), theme = NULL, check.overlap = FALSE, angle = waiver(), n.dodge = 1, minor.ticks = FALSE, cap = \"none\", order = 0, position = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Axis guide — guide_axis","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. check.overlap silently remove overlapping labels, (recursively) prioritizing first, last, middle labels. angle Compared setting angle theme() / element_text(), also uses heuristics automatically pick hjust vjust probably want. Can one following: NULL take angles hjust/vjust directly theme. waiver() allow reasonable defaults special cases. number representing text angle degrees. n.dodge number rows (vertical axes) columns (horizontal axes) used render labels. useful displaying labels otherwise overlap. minor.ticks Whether draw minor ticks (TRUE) draw minor ticks (FALSE, default). cap character cut axis line back last breaks. Can \"none\" (default) draw axis line along whole panel, \"upper\" \"lower\" draw axis upper lower break, \"\" draw line extreme breaks. TRUE FALSE shorthand \"\" \"none\" respectively. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Axis guide — guide_axis","text":"","code":"# plot with overlapping text p <- ggplot(mpg, aes(cty * 100, hwy * 100)) + geom_point() + facet_wrap(vars(class)) # axis guides can be customized in the scale_* functions or # using guides() p + scale_x_continuous(guide = guide_axis(n.dodge = 2)) p + guides(x = guide_axis(angle = 90)) # can also be used to add a duplicate guide p + guides(x = guide_axis(n.dodge = 2), y.sec = guide_axis())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":null,"dir":"Reference","previous_headings":"","what":"Axis with logarithmic tick marks — guide_axis_logticks","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"axis guide replaces placement ticks marks intervals log10 space.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"","code":"guide_axis_logticks( long = 2.25, mid = 1.5, short = 0.75, prescale.base = NULL, negative.small = 0.1, short.theme = element_line(), expanded = TRUE, cap = \"none\", theme = NULL, prescale_base = deprecated(), negative_small = deprecated(), short_theme = deprecated(), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"long, mid, short grid::unit() object rel() object setting (relative) length long, middle short ticks. Numeric values interpreted rel() objects. rel() values used multiply values axis.ticks.length theme setting. prescale.base Base logarithm used transform data manually. default, NULL, use scale transformation calculate positions. set prescale.base data already log-transformed. using log-transform position scale coord_trans(), keep default NULL argument. negative.small scale limits include 0 negative numbers, smallest absolute value marked tick? short.theme theme element customising display shortest ticks. Must line blank element, inherits axis.minor.ticks setting relevant position. expanded Whether ticks cover range scale expansion (TRUE, default), restricted scale limits (FALSE). cap character cut axis line back last breaks. Can \"none\" (default) draw axis line along whole panel, \"upper\" \"lower\" draw axis upper lower break, \"\" draw line extreme breaks. TRUE FALSE shorthand \"\" \"none\" respectively. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. prescale_base, negative_small, short_theme ... Arguments passed guide_axis check.overlap silently remove overlapping labels, (recursively) prioritizing first, last, middle labels. angle Compared setting angle theme() / element_text(), also uses heuristics automatically pick hjust vjust probably want. Can one following: NULL take angles hjust/vjust directly theme. waiver() allow reasonable defaults special cases. number representing text angle degrees. n.dodge number rows (vertical axes) columns (horizontal axes) used render labels. useful displaying labels otherwise overlap. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right. title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"","code":"# A standard plot p <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point(na.rm = TRUE) # The logticks axis works well with log scales p + scale_x_log10(guide = \"axis_logticks\") + scale_y_log10(guide = \"axis_logticks\") # Or with log-transformed coordinates p + coord_trans(x = \"log10\", y = \"log10\") + guides(x = \"axis_logticks\", y = \"axis_logticks\") # When data is transformed manually, one should provide `prescale.base` # Keep in mind that this axis uses log10 space for placement, not log2 p + aes(x = log2(bodywt), y = log10(brainwt)) + guides( x = guide_axis_logticks(prescale.base = 2), y = guide_axis_logticks(prescale.base = 10) ) # A plot with both positive and negative extremes, pseudo-log transformed set.seed(42) p2 <- ggplot(data.frame(x = rcauchy(1000)), aes(x = x)) + geom_density() + scale_x_continuous( breaks = c(-10^(4:0), 0, 10^(0:4)), transform = \"pseudo_log\" ) # The log ticks are mirrored when 0 is included p2 + guides(x = \"axis_logticks\") # To control the tick density around 0, one can set `negative.small` p2 + guides(x = guide_axis_logticks(negative.small = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":null,"dir":"Reference","previous_headings":"","what":"Stacked axis guides — guide_axis_stack","title":"Stacked axis guides — guide_axis_stack","text":"guide can stack position guides represent position scales, like created scale_(x|y)_continuous() scale_(x|y)_discrete().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Stacked axis guides — guide_axis_stack","text":"","code":"guide_axis_stack( first = \"axis\", ..., title = waiver(), theme = NULL, spacing = NULL, order = 0, position = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Stacked axis guides — guide_axis_stack","text":"first position guide given one following: string, example \"axis\". call guide function, example guide_axis(). ... Additional guides stack given manner first. title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. spacing unit() objects determines far separate guides spaced apart. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Stacked axis guides — guide_axis_stack","text":"first guide placed closest panel subsequent guides provided ... follow given order.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Stacked axis guides — guide_axis_stack","text":"","code":"#' # A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() + theme(axis.line = element_line()) # A normal axis first, then a capped axis p + guides(x = guide_axis_stack(\"axis\", guide_axis(cap = \"both\")))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":null,"dir":"Reference","previous_headings":"","what":"Angle axis guide — guide_axis_theta","title":"Angle axis guide — guide_axis_theta","text":"specialised guide used coord_radial() represent theta position scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Angle axis guide — guide_axis_theta","text":"","code":"guide_axis_theta( title = waiver(), theme = NULL, angle = waiver(), minor.ticks = FALSE, cap = \"none\", order = 0, position = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Angle axis guide — guide_axis_theta","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. angle Compared setting angle theme() / element_text(), also uses heuristics automatically pick hjust vjust probably want. Can one following: NULL take angles hjust/vjust directly theme. waiver() allow reasonable defaults special cases. number representing text angle degrees. minor.ticks Whether draw minor ticks (TRUE) draw minor ticks (FALSE, default). cap character cut axis line back last breaks. Can \"none\" (default) draw axis line along whole panel, \"upper\" \"lower\" draw axis upper lower break, \"\" draw line extreme breaks. TRUE FALSE shorthand \"\" \"none\" respectively. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Angle axis guide — guide_axis_theta","text":"axis labels guide insensitive hjust vjust settings. distance tick marks labels determined largest margin size set theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Angle axis guide — guide_axis_theta","text":"","code":"# A plot using coord_radial p <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + coord_radial() # The `angle` argument can be used to set relative angles p + guides(theta = guide_axis_theta(angle = 0))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":null,"dir":"Reference","previous_headings":"","what":"A binned version of guide_legend — guide_bins","title":"A binned version of guide_legend — guide_bins","text":"guide version guide_legend() guide binned scales. differs places ticks correctly keys, sports small axis better show binning. Like guide_legend() can used non-position aesthetics though colour fill defaults guide_coloursteps(), merge aesthetics together guide mapped way.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A binned version of guide_legend — guide_bins","text":"","code":"guide_bins( title = waiver(), theme = NULL, position = NULL, direction = NULL, override.aes = list(), reverse = FALSE, order = 0, show.limits = NULL, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A binned version of guide_legend — guide_bins","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. position character string indicating legend placed relative plot panels. direction character string indicating direction guide. One \"horizontal\" \"vertical\". override.aes list specifying aesthetic parameters legend key. See details examples. reverse logical. TRUE order legends reversed. order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. show.limits Logical. limits scale shown labels ticks. Default NULL meaning take value scale. argument ignored labels given vector values. one limits also given breaks shown irrespective value show.limits. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"A binned version of guide_legend — guide_bins","text":"guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"use-with-discrete-scale","dir":"Reference","previous_headings":"","what":"Use with discrete scale","title":"A binned version of guide_legend — guide_bins","text":"guide intended show binned data work together ggplot2's binning scales. However, sometimes desirable perform binning separate step, either part stat (e.g. stat_contour_filled()) prior visualisation. want use guide discrete data levels must follow naming scheme implemented base::cut(). means bin must encoded \"(, ]\" giving lower bound bin giving upper bound (\"[, )\" also accepted). use base::cut() perform binning everything work expected, , recoding may needed.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A binned version of guide_legend — guide_bins","text":"","code":"p <- ggplot(mtcars) + geom_point(aes(disp, mpg, size = hp)) + scale_size_binned() # Standard look p # Remove the axis or style it p + guides(size = guide_bins( theme = theme(legend.axis.line = element_blank()) )) p + guides(size = guide_bins(show.limits = TRUE)) my_arrow <- arrow(length = unit(1.5, \"mm\"), ends = \"both\") p + guides(size = guide_bins( theme = theme(legend.axis.line = element_line(arrow = my_arrow)) )) # Guides are merged together if possible ggplot(mtcars) + geom_point(aes(disp, mpg, size = hp, colour = hp)) + scale_size_binned() + scale_colour_binned(guide = \"bins\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":null,"dir":"Reference","previous_headings":"","what":"Continuous colour bar guide — guide_colourbar","title":"Continuous colour bar guide — guide_colourbar","text":"Colour bar guide shows continuous colour scales mapped onto values. Colour bar available scale_fill scale_colour. information, see inspiration function: Matlab's colorbar function.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Continuous colour bar guide — guide_colourbar","text":"","code":"guide_colourbar( title = waiver(), theme = NULL, nbin = NULL, display = \"raster\", raster = deprecated(), alpha = NA, draw.ulim = TRUE, draw.llim = TRUE, position = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... ) guide_colorbar( title = waiver(), theme = NULL, nbin = NULL, display = \"raster\", raster = deprecated(), alpha = NA, draw.ulim = TRUE, draw.llim = TRUE, position = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Continuous colour bar guide — guide_colourbar","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. nbin numeric specifying number bins drawing colourbar. smoother colourbar results larger value. display string indicating method display colourbar. Can one following: \"raster\" display bitmap image. \"rectangles\" display series rectangles. \"gradient\" display linear gradient. Note devices able render rasters gradients. raster logical. TRUE colourbar rendered raster object. FALSE colourbar rendered set rectangles. Note graphics devices capable rendering raster image. alpha numeric 0 1 setting colour transparency bar. Use NA preserve alpha encoded colour (default). draw.ulim logical specifying upper limit tick marks visible. draw.llim logical specifying lower limit tick marks visible. position character string indicating legend placed relative plot panels. direction character string indicating direction guide. One \"horizontal\" \"vertical.\" reverse logical. TRUE colourbar reversed. default, highest value top lowest value bottom order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. available_aes vector character strings listing aesthetics colourbar can drawn. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Continuous colour bar guide — guide_colourbar","text":"guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Continuous colour bar guide — guide_colourbar","text":"Guides can specified scale_* guides(). guide=\"legend\" scale_* syntactic sugar guide=guide_legend() (e.g. scale_colour_manual(guide = \"legend\")). specify guide scale detail, see guides().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Continuous colour bar guide — guide_colourbar","text":"","code":"df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) p2 <- p1 + geom_point(aes(size = value)) # Basic form p1 + scale_fill_continuous(guide = \"colourbar\") p1 + scale_fill_continuous(guide = guide_colourbar()) p1 + guides(fill = guide_colourbar()) # Control styles # bar size p1 + guides(fill = guide_colourbar(theme = theme( legend.key.width = unit(0.5, \"lines\"), legend.key.height = unit(10, \"lines\") ))) # no label p1 + guides(fill = guide_colourbar(theme = theme( legend.text = element_blank() ))) # no tick marks p1 + guides(fill = guide_colourbar(theme = theme( legend.ticks = element_blank() ))) # label position p1 + guides(fill = guide_colourbar(theme = theme( legend.text.position = \"left\" ))) # label theme p1 + guides(fill = guide_colourbar(theme = theme( legend.text = element_text(colour = \"blue\", angle = 0) ))) # small number of bins p1 + guides(fill = guide_colourbar(nbin = 3)) # large number of bins p1 + guides(fill = guide_colourbar(nbin = 100)) # make top- and bottom-most ticks invisible p1 + scale_fill_continuous( limits = c(0,20), breaks = c(0, 5, 10, 15, 20), guide = guide_colourbar(nbin = 100, draw.ulim = FALSE, draw.llim = FALSE) ) # guides can be controlled independently p2 + scale_fill_continuous(guide = \"colourbar\") + scale_size(guide = \"legend\") p2 + guides(fill = \"colourbar\", size = \"legend\") p2 + scale_fill_continuous(guide = guide_colourbar(theme = theme( legend.direction = \"horizontal\" ))) + scale_size(guide = guide_legend(theme = theme( legend.direction = \"vertical\" )))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":null,"dir":"Reference","previous_headings":"","what":"Discretized colourbar guide — guide_coloursteps","title":"Discretized colourbar guide — guide_coloursteps","text":"guide version guide_colourbar() binned colour fill scales. shows areas breaks single constant colour instead gradient known colourbar counterpart.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discretized colourbar guide — guide_coloursteps","text":"","code":"guide_coloursteps( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, position = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... ) guide_colorsteps( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, position = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discretized colourbar guide — guide_coloursteps","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. alpha numeric 0 1 setting colour transparency bar. Use NA preserve alpha encoded colour (default). even.steps rendered size bins equal, proportional length data space? Defaults TRUE show.limits Logical. limits scale shown labels ticks. Default NULL meaning take value scale. argument ignored labels given vector values. one limits also given breaks shown irrespective value show.limits. direction character string indicating direction guide. One \"horizontal\" \"vertical.\" position character string indicating legend placed relative plot panels. reverse logical. TRUE colourbar reversed. default, highest value top lowest value bottom order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. available_aes vector character strings listing aesthetics colourbar can drawn. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Discretized colourbar guide — guide_coloursteps","text":"guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"use-with-discrete-scale","dir":"Reference","previous_headings":"","what":"Use with discrete scale","title":"Discretized colourbar guide — guide_coloursteps","text":"guide intended show binned data work together ggplot2's binning scales. However, sometimes desirable perform binning separate step, either part stat (e.g. stat_contour_filled()) prior visualisation. want use guide discrete data levels must follow naming scheme implemented base::cut(). means bin must encoded \"(, ]\" giving lower bound bin giving upper bound (\"[, )\" also accepted). use base::cut() perform binning everything work expected, , recoding may needed.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Discretized colourbar guide — guide_coloursteps","text":"","code":"df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 p <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) # Coloursteps guide is the default for binned colour scales p + scale_fill_binned() # By default each bin in the guide is the same size irrespectively of how # their sizes relate in data space p + scale_fill_binned(breaks = c(10, 25, 50)) # This can be changed with the `even.steps` argument p + scale_fill_binned( breaks = c(10, 25, 50), guide = guide_coloursteps(even.steps = FALSE) ) # By default the limits is not shown, but this can be changed p + scale_fill_binned(guide = guide_coloursteps(show.limits = TRUE)) # (can also be set in the scale) p + scale_fill_binned(show.limits = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":null,"dir":"Reference","previous_headings":"","what":"Custom guides — guide_custom","title":"Custom guides — guide_custom","text":"special guide can used display graphical object (grob) along regular guides. guide associated scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Custom guides — guide_custom","text":"","code":"guide_custom( grob, width = grobWidth(grob), height = grobHeight(grob), title = NULL, theme = NULL, position = NULL, order = 0 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Custom guides — guide_custom","text":"grob grob display. width, height allocated width height display grob, given grid::unit()s. title character string expression indicating title guide. NULL (default), title shown. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. position character string indicating legend placed relative plot panels. order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Custom guides — guide_custom","text":"","code":"# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Define a graphical object circle <- grid::circleGrob() # Rendering a grob as a guide p + guides(custom = guide_custom(circle, title = \"My circle\")) # Controlling the size of the grob defined in relative units p + guides(custom = guide_custom( circle, title = \"My circle\", width = unit(2, \"cm\"), height = unit(2, \"cm\")) ) # Size of grobs in absolute units is taken directly without the need to # set these manually p + guides(custom = guide_custom( title = \"My circle\", grob = grid::circleGrob(r = unit(1, \"cm\")) ))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":null,"dir":"Reference","previous_headings":"","what":"Legend guide — guide_legend","title":"Legend guide — guide_legend","text":"Legend type guide shows key (.e., geoms) mapped onto values. Legend guides various scales integrated possible.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Legend guide — guide_legend","text":"","code":"guide_legend( title = waiver(), theme = NULL, position = NULL, direction = NULL, override.aes = list(), nrow = NULL, ncol = NULL, reverse = FALSE, order = 0, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Legend guide — guide_legend","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. position character string indicating legend placed relative plot panels. direction character string indicating direction guide. One \"horizontal\" \"vertical\". override.aes list specifying aesthetic parameters legend key. See details examples. nrow, ncol desired number rows column legends respectively. reverse logical. TRUE order legends reversed. order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Legend guide — guide_legend","text":"Guides can specified scale_* guides(). guide = \"legend\" scale_* syntactic sugar guide = guide_legend() (e.g. scale_color_manual(guide = \"legend\")). specify guide scale detail, see guides().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Legend guide — guide_legend","text":"","code":"# \\donttest{ df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) p2 <- p1 + geom_point(aes(size = value)) # Basic form p1 + scale_fill_continuous(guide = guide_legend()) # Control styles # title position p1 + guides(fill = guide_legend( title = \"LEFT\", theme(legend.title.position = \"left\") )) # title text styles via element_text p1 + guides(fill = guide_legend(theme = theme( legend.title = element_text(size = 15, face = \"italic\", colour = \"red\") ))) # label position p1 + guides(fill = guide_legend(theme = theme( legend.text.position = \"left\", legend.text = element_text(hjust = 1) ))) # label styles p1 + scale_fill_continuous( breaks = c(5, 10, 15), labels = paste(\"long\", c(5, 10, 15)), guide = guide_legend(theme = theme( legend.direction = \"horizontal\", legend.title.position = \"top\", legend.text.position = \"bottom\", legend.text = element_text(hjust = 0.5, vjust = 1, angle = 90) )) ) # Set aesthetic of legend key # very low alpha value make it difficult to see legend key p3 <- ggplot(mtcars, aes(vs, am, colour = factor(cyl))) + geom_jitter(alpha = 1/5, width = 0.01, height = 0.01) p3 # override.aes overwrites the alpha p3 + guides(colour = guide_legend(override.aes = list(alpha = 1))) # multiple row/col legends df <- data.frame(x = 1:20, y = 1:20, color = letters[1:20]) p <- ggplot(df, aes(x, y)) + geom_point(aes(colour = color)) p + guides(col = guide_legend(nrow = 8)) p + guides(col = guide_legend(ncol = 8)) p + guides(col = guide_legend(nrow = 8, theme = theme(legend.byrow = TRUE))) # reversed order legend p + guides(col = guide_legend(reverse = TRUE)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_none.html","id":null,"dir":"Reference","previous_headings":"","what":"Empty guide — guide_none","title":"Empty guide — guide_none","text":"guide draws nothing.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_none.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Empty guide — guide_none","text":"","code":"guide_none(title = waiver(), position = waiver())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_none.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Empty guide — guide_none","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":null,"dir":"Reference","previous_headings":"","what":"Set guides for each scale — guides","title":"Set guides for each scale — guides","text":"Guides scale can set scale--scale guide argument, en masse guides().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set guides for each scale — guides","text":"","code":"guides(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set guides for each scale — guides","text":"... List scale name-guide pairs. guide can either string (.e. \"colorbar\" \"legend\"), call guide function (.e. guide_colourbar() guide_legend()) specifying additional arguments.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Set guides for each scale — guides","text":"list containing mapping scale guide.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set guides for each scale — guides","text":"","code":"# \\donttest{ # ggplot object dat <- data.frame(x = 1:5, y = 1:5, p = 1:5, q = factor(1:5), r = factor(1:5)) p <- ggplot(dat, aes(x, y, colour = p, size = q, shape = r)) + geom_point() # without guide specification p #> Warning: Using size for a discrete variable is not advised. # Show colorbar guide for colour. # All these examples below have a same effect. p + guides(colour = \"colorbar\", size = \"legend\", shape = \"legend\") #> Warning: Using size for a discrete variable is not advised. p + guides(colour = guide_colorbar(), size = guide_legend(), shape = guide_legend()) #> Warning: Using size for a discrete variable is not advised. p + scale_colour_continuous(guide = \"colorbar\") + scale_size_discrete(guide = \"legend\") + scale_shape(guide = \"legend\") #> Warning: Using size for a discrete variable is not advised. # Remove some guides p + guides(colour = \"none\") #> Warning: Using size for a discrete variable is not advised. p + guides(colour = \"colorbar\",size = \"none\") #> Warning: Using size for a discrete variable is not advised. # Guides are integrated where possible p + guides( colour = guide_legend(\"title\"), size = guide_legend(\"title\"), shape = guide_legend(\"title\") ) #> Warning: Using size for a discrete variable is not advised. # same as g <- guide_legend(\"title\") p + guides(colour = g, size = g, shape = g) #> Warning: Using size for a discrete variable is not advised. p + theme(legend.position = \"bottom\") #> Warning: Using size for a discrete variable is not advised. # position of guides # Set order for multiple guides ggplot(mpg, aes(displ, cty)) + geom_point(aes(size = hwy, colour = cyl, shape = drv)) + guides( colour = guide_colourbar(order = 1), shape = guide_legend(order = 2), size = guide_legend(order = 3) ) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":null,"dir":"Reference","previous_headings":"","what":"A selection of summary functions from Hmisc — hmisc","title":"A selection of summary functions from Hmisc — hmisc","text":"wrappers around functions Hmisc designed make easier use stat_summary(). See Hmisc documentation details: Hmisc::smean.cl.boot() Hmisc::smean.cl.normal() Hmisc::smean.sdl() Hmisc::smedian.hilow()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A selection of summary functions from Hmisc — hmisc","text":"","code":"mean_cl_boot(x, ...) mean_cl_normal(x, ...) mean_sdl(x, ...) median_hilow(x, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A selection of summary functions from Hmisc — hmisc","text":"x numeric vector ... arguments passed respective Hmisc function.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"A selection of summary functions from Hmisc — hmisc","text":"data frame columns y, ymin, ymax.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A selection of summary functions from Hmisc — hmisc","text":"","code":"if (requireNamespace(\"Hmisc\", quietly = TRUE)) { set.seed(1) x <- rnorm(100) mean_cl_boot(x) mean_cl_normal(x) mean_sdl(x) median_hilow(x) } #> y ymin ymax #> 1 0.1139092 -1.671298 1.797468"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":null,"dir":"Reference","previous_headings":"","what":"Ignoring and exposing data — ignoring_data","title":"Ignoring and exposing data — ignoring_data","text":".ignore_data() function used hide columns scale interactions ggplot_build(). .expose_data() function used restore hidden columns.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Ignoring and exposing data — ignoring_data","text":"","code":".ignore_data(data) .expose_data(data)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Ignoring and exposing data — ignoring_data","text":"data list s.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Ignoring and exposing data — ignoring_data","text":"modified list s","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Ignoring and exposing data — ignoring_data","text":"","code":"data <- list( data.frame(x = 1:3, y = I(1:3)), data.frame(w = I(1:3), z = 1:3) ) ignored <- .ignore_data(data) str(ignored) #> List of 2 #> $ :'data.frame':\t3 obs. of 2 variables: #> ..$ x : int [1:3] 1 2 3 #> ..$ .ignored:'data.frame':\t3 obs. of 1 variable: #> .. ..$ y: 'AsIs' int [1:3] 1 2 3 #> $ :'data.frame':\t3 obs. of 2 variables: #> ..$ z : int [1:3] 1 2 3 #> ..$ .ignored:'data.frame':\t3 obs. of 1 variable: #> .. ..$ w: 'AsIs' int [1:3] 1 2 3 .expose_data(ignored) #> [[1]] #> x y #> 1 1 1 #> 2 2 2 #> 3 3 3 #> #> [[2]] #> z w #> 1 1 1 #> 2 2 2 #> 3 3 3 #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.Coord.html","id":null,"dir":"Reference","previous_headings":"","what":"Is this object a coordinate system? — is.Coord","title":"Is this object a coordinate system? — is.Coord","text":"object coordinate system?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.Coord.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Is this object a coordinate system? — is.Coord","text":"","code":"is.Coord(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.facet.html","id":null,"dir":"Reference","previous_headings":"","what":"Is this object a faceting specification? — is.facet","title":"Is this object a faceting specification? — is.facet","text":"object faceting specification?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.facet.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Is this object a faceting specification? — is.facet","text":"","code":"is.facet(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.facet.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Is this object a faceting specification? — is.facet","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Reports whether x is a ggplot object — is.ggplot","title":"Reports whether x is a ggplot object — is.ggplot","text":"Reports whether x ggplot object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reports whether x is a ggplot object — is.ggplot","text":"","code":"is.ggplot(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reports whether x is a ggplot object — is.ggplot","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.rel.html","id":null,"dir":"Reference","previous_headings":"","what":"Reports whether x is a rel object — is.rel","title":"Reports whether x is a rel object — is.rel","text":"Reports whether x rel object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.rel.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reports whether x is a rel object — is.rel","text":"","code":"is.rel(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.rel.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reports whether x is a rel object — is.rel","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Reports whether x is a theme object — is.theme","title":"Reports whether x is a theme object — is.theme","text":"Reports whether x theme object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reports whether x is a theme object — is.theme","text":"","code":"is.theme(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reports whether x is a theme object — is.theme","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":null,"dir":"Reference","previous_headings":"","what":"Label with mathematical expressions — label_bquote","title":"Label with mathematical expressions — label_bquote","text":"label_bquote() offers flexible way labelling facet rows columns plotmath expressions. Backquoted variables replaced value facet.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Label with mathematical expressions — label_bquote","text":"","code":"label_bquote(rows = NULL, cols = NULL, default)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Label with mathematical expressions — label_bquote","text":"rows Backquoted labelling expression rows. cols Backquoted labelling expression columns. default Unused, kept compatibility.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Label with mathematical expressions — label_bquote","text":"","code":"# The variables mentioned in the plotmath expression must be # backquoted and referred to by their names. p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() p + facet_grid(vs ~ ., labeller = label_bquote(alpha ^ .(vs))) p + facet_grid(. ~ vs, labeller = label_bquote(cols = .(vs) ^ .(vs))) p + facet_grid(. ~ vs + am, labeller = label_bquote(cols = .(am) ^ .(vs)))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":null,"dir":"Reference","previous_headings":"","what":"Construct labelling specification — labeller","title":"Construct labelling specification — labeller","text":"function makes easy assign different labellers different factors. labeller can function can named character vector serve lookup table.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Construct labelling specification — labeller","text":"","code":"labeller( ..., .rows = NULL, .cols = NULL, keep.as.numeric = deprecated(), .multi_line = TRUE, .default = label_value )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Construct labelling specification — labeller","text":"... Named arguments form variable = labeller. labeller passed as_labeller() can lookup table, function taking returning character vectors, simply labeller function. .rows, .cols Labeller whole margin (either rows columns). passed as_labeller(). margin-wide labeller set, make sure mention ... variable belonging margin. keep..numeric supplied labellers -labeller functions able work character labels. .multi_line Whether display labels multiple factors separate lines. passed labeller function. .default Default labeller variables specified. Also used lookup tables non-labeller functions.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Construct labelling specification — labeller","text":"labeller function supply facet_grid() facet_wrap() argument labeller.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Construct labelling specification — labeller","text":"case functions, labeller class labeller, directly applied data frame labels. Otherwise, applied columns data frame labels. data frame processed function specified .default argument. intended used functions taking character vector Hmisc::capitalize().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Construct labelling specification — labeller","text":"","code":"# \\donttest{ p1 <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point() # You can assign different labellers to variables: p1 + facet_grid( vs + am ~ gear, labeller = labeller(vs = label_both, am = label_value) ) # Or whole margins: p1 + facet_grid( vs + am ~ gear, labeller = labeller(.rows = label_both, .cols = label_value) ) # You can supply functions operating on strings: capitalize <- function(string) { substr(string, 1, 1) <- toupper(substr(string, 1, 1)) string } p2 <- ggplot(msleep, aes(x = sleep_total, y = awake)) + geom_point() p2 + facet_grid(vore ~ conservation, labeller = labeller(vore = capitalize)) # Or use character vectors as lookup tables: conservation_status <- c( cd = \"Conservation Dependent\", en = \"Endangered\", lc = \"Least concern\", nt = \"Near Threatened\", vu = \"Vulnerable\", domesticated = \"Domesticated\" ) ## Source: http://en.wikipedia.org/wiki/Wikipedia:Conservation_status p2 + facet_grid(vore ~ conservation, labeller = labeller( .default = capitalize, conservation = conservation_status )) # In the following example, we rename the levels to the long form, # then apply a wrap labeller to the columns to prevent cropped text idx <- match(msleep$conservation, names(conservation_status)) msleep$conservation2 <- conservation_status[idx] p3 <- ggplot(msleep, aes(x = sleep_total, y = awake)) + geom_point() p3 + facet_grid(vore ~ conservation2, labeller = labeller(conservation2 = label_wrap_gen(10)) ) # labeller() is especially useful to act as a global labeller. You # can set it up once and use it on a range of different plots with # different facet specifications. global_labeller <- labeller( vore = capitalize, conservation = conservation_status, conservation2 = label_wrap_gen(10), .default = label_both ) p2 + facet_grid(vore ~ conservation, labeller = global_labeller) p3 + facet_wrap(~conservation2, labeller = global_labeller) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":null,"dir":"Reference","previous_headings":"","what":"Useful labeller functions — labellers","title":"Useful labeller functions — labellers","text":"Labeller functions charge formatting strip labels facet grids wraps. accept multi_line argument control whether multiple factors (defined formulae ~first + second) displayed single line separated commas, line.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Useful labeller functions — labellers","text":"","code":"label_value(labels, multi_line = TRUE) label_both(labels, multi_line = TRUE, sep = \": \") label_context(labels, multi_line = TRUE, sep = \": \") label_parsed(labels, multi_line = TRUE) label_wrap_gen(width = 25, multi_line = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Useful labeller functions — labellers","text":"labels Data frame labels. Usually contains one element, faceting multiple factors entails multiple label variables. multi_line Whether display labels multiple factors separate lines. sep String separating variables values. width Maximum number characters wrapping strip.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Useful labeller functions — labellers","text":"label_value() displays value factor label_both() displays variable name factor value. label_context() context-dependent uses label_value() single factor faceting label_both() multiple factors involved. label_wrap_gen() uses base::strwrap() line wrapping. label_parsed() interprets labels plotmath expressions. label_bquote() offers flexible way constructing plotmath expressions. See examples bquote() details syntax argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"writing-new-labeller-functions","dir":"Reference","previous_headings":"","what":"Writing New Labeller Functions","title":"Useful labeller functions — labellers","text":"Note easy way write labeller function transform function operating character vectors as_labeller(). labeller function accepts data frame labels (character vectors) containing one column factor. Multiple factors occur formula type ~first + second. return value must rectangular list 'row' characterises single facet. list elements can either character vectors lists plotmath expressions. multiple elements returned, get displayed new lines (.e., facet gets multi-line strip labels). illustrate, say labeller returns list two character vectors length 3. rectangular list elements length. first facet get first elements vector display line. second facet gets second elements vector, . useful labeller, can retrieve type attribute incoming data frame labels. value attribute reflects kind strips labeller dealing : \"cols\" columns \"rows\" rows. Note facet_wrap() columns default rows strips switched switch option. facet attribute also provides metadata labels. takes values \"grid\" \"wrap\". compatibility labeller(), labeller function must labeller S3 class.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Useful labeller functions — labellers","text":"","code":"mtcars$cyl2 <- factor(mtcars$cyl, labels = c(\"alpha\", \"beta\", \"gamma\")) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() # The default is label_value p + facet_grid(. ~ cyl, labeller = label_value) # \\donttest{ # Displaying both the values and the variables p + facet_grid(. ~ cyl, labeller = label_both) # Displaying only the values or both the values and variables # depending on whether multiple factors are facetted over p + facet_grid(am ~ vs+cyl, labeller = label_context) # Interpreting the labels as plotmath expressions p + facet_grid(. ~ cyl2) p + facet_grid(. ~ cyl2, labeller = label_parsed) # Include optional argument in label function p + facet_grid(. ~ cyl, labeller = function(x) label_both(x, sep = \"=\")) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify axis, legend, and plot labels — labs","title":"Modify axis, legend, and plot labels — labs","text":"Good labels critical making plots accessible wider audience. Always ensure axis legend labels display full variable name. Use plot title subtitle explain main findings. common use caption provide information data source. tag can used adding identification tags differentiate multiple plots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify axis, legend, and plot labels — labs","text":"","code":"labs( ..., title = waiver(), subtitle = waiver(), caption = waiver(), tag = waiver(), alt = waiver(), alt_insight = waiver() ) xlab(label) ylab(label) ggtitle(label, subtitle = waiver())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify axis, legend, and plot labels — labs","text":"... list new name-value pairs. name aesthetic. title text title. subtitle text subtitle plot displayed title. caption text caption displayed bottom-right plot default. tag text tag label displayed top-left plot default. alt, alt_insight Text used generation alt-text plot. See get_alt_text examples. alt can also function takes plot input returns text output. alt also accepts rlang lambda function notation. label title respective axis (xlab() ylab()) plot (ggtitle()).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Modify axis, legend, and plot labels — labs","text":"can also set axis legend labels individual scales (using first argument, name). changing scale options, recommended. plot already title, subtitle, caption, etc., want remove , can setting respective argument NULL. example, plot p subtitle, p + labs(subtitle = NULL) remove subtitle plot.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify axis, legend, and plot labels — labs","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point() p + labs(colour = \"Cylinders\") p + labs(x = \"New x label\") # The plot title appears at the top-left, with the subtitle # display in smaller text underneath it p + labs(title = \"New plot title\") p + labs(title = \"New plot title\", subtitle = \"A subtitle\") # The caption appears in the bottom-right, and is often used for # sources, notes or copyright p + labs(caption = \"(based on data from ...)\") # The plot tag appears at the top-left, and is typically used # for labelling a subplot with a letter. p + labs(title = \"title\", tag = \"A\") # If you want to remove a label, set it to NULL. p + labs(title = \"title\") + labs(title = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new layer — layer","title":"Create a new layer — layer","text":"layer combination data, stat geom potential position adjustment. Usually layers created using geom_* stat_* calls can also created directly using function.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new layer — layer","text":"","code":"layer( geom = NULL, stat = NULL, data = NULL, mapping = NULL, position = NULL, params = list(), inherit.aes = TRUE, check.aes = TRUE, check.param = TRUE, show.legend = NA, key_glyph = NULL, layer_class = Layer )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new layer — layer","text":"geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. params Additional parameters geom stat. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). check.aes, check.param TRUE, default, check supplied parameters aesthetics understood geom stat. Use FALSE suppress checks. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. key_glyph legend key drawing function string providing function name minus draw_key_ prefix. See draw_key details. layer_class type layer object constructed. intended ggplot2 internal use .","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new layer — layer","text":"","code":"# geom calls are just a short cut for layer ggplot(mpg, aes(displ, hwy)) + geom_point() # shortcut for ggplot(mpg, aes(displ, hwy)) + layer( geom = \"point\", stat = \"identity\", position = \"identity\", params = list(na.rm = FALSE) ) # use a function as data to plot a subset of global data ggplot(mpg, aes(displ, hwy)) + layer( geom = \"point\", stat = \"identity\", position = \"identity\", data = head, params = list(na.rm = FALSE) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":null,"dir":"Reference","previous_headings":"","what":"Layer geometry display — layer_geoms","title":"Layer geometry display — layer_geoms","text":"ggplot2, plot constructed adding layers . layer consists two important parts: geometry (geoms), statistical transformations (stats). 'geom' part layer important determines looks data. Geoms determine something displayed, displayed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":"specifying-geoms","dir":"Reference","previous_headings":"","what":"Specifying geoms","title":"Layer geometry display — layer_geoms","text":"five ways 'geom' part layer can specified. Many ways absolutely equivalent. Using stat_density(geom = \"line\") identical using geom_line(stat = \"density\"). Note layer(), need provide \"position\" argument well. give geoms string, take function name, remove geom_ prefix, geom_point becomes \"point\". well known geoms can used geom argument : \"point\", \"line\", \"area\", \"bar\" \"polygon\".","code":"# 1. The geom can have a layer constructor geom_area() # 2. A stat can default to a particular geom stat_density() # has `geom = \"area\"` as default # 3. It can be given to a stat as a string stat_function(geom = \"area\") # 4. The ggproto object of a geom can be given stat_bin(geom = GeomArea) # 5. It can be given to `layer()` directly layer( geom = \"area\", stat = \"smooth\", position = \"identity\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":"graphical-display","dir":"Reference","previous_headings":"","what":"Graphical display","title":"Layer geometry display — layer_geoms","text":"ggplot build top grid package. package understands various graphical primitives, points, lines, rectangles polygons positions, well graphical attributes, also termed aesthetics, colours, fills, linewidths linetypes. job geom part layer, translate data grid graphics can plotted. see aesthetics specified, run vignette(\"ggplot2-specs\"). see geom uses aesthetics, can find Aesthetics section documentation, example ?geom_line. almost anything can represented polygons try hard enough, always convenient manually. reason, geoms provide abstractions take hassle away. geom_ribbon() example special case geom_polygon(), two sets y-positions shared x-position. turn, geom_area() special case ribbon, one two sets y-positions set 0. addition abstraction, geoms sometimes also perform composition. boxplot particular arrangement lines, rectangles points people agreed upon summary data, performed geom_boxplot().","code":"# A hassle to build a polygon my_polygon <- data.frame( x = c(economics$date, rev(economics$date)), y = c(economics$uempmed, rev(economics$psavert)) ) ggplot(my_polygon, aes(x, y)) + geom_polygon() # More succinctly ggplot(economics, aes(date)) + geom_ribbon(aes(ymin = uempmed, ymax = psavert)) Boxplot data value <- fivenum(rnorm(100)) df <- data.frame( min = value[1], lower = value[2], middle = value[3], upper = value[4], max = value[5] ) # Drawing a boxplot manually ggplot(df, aes(x = 1, xend = 1)) + geom_rect( aes( xmin = 0.55, xmax = 1.45, ymin = lower, ymax = upper ), colour = \"black\", fill = \"white\" ) + geom_segment( aes( x = 0.55, xend = 1.45, y = middle, yend = middle ), size = 1 ) + geom_segment(aes(y = lower, yend = min)) + geom_segment(aes(y = upper, yend = max)) # More succinctly ggplot(df, aes(x = 1)) + geom_boxplot( aes(ymin = min, ymax = max, lower = lower, upper = upper, middle = middle), stat = \"identity\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":"under-the-hood","dir":"Reference","previous_headings":"","what":"Under the hood","title":"Layer geometry display — layer_geoms","text":"Internally, geoms represented ggproto classes occupy slot layer. classes inherit parental Geom ggproto object orchestrates geoms work. Briefly, geoms given opportunity draw data layer whole, facet panel, individual groups. information extending geoms, see Creating new geom section running vignette(\"extending-ggplot2\"). Additionally, see New geoms section online book.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":null,"dir":"Reference","previous_headings":"","what":"Layer position adjustments — layer_positions","title":"Layer position adjustments — layer_positions","text":"ggplot2, plot constructed adding layers . addition geoms stats, position adjustments third required part layer. 'position' part layer responsible dodging, jittering nudging groups data minimise overlap, otherwise tweaking positions. example add position = position_nudge(x = 1) layer, can offset every x-position 1. many layers, default position adjustment position_identity(), performs adjustment.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"specifying-positions","dir":"Reference","previous_headings":"","what":"Specifying positions","title":"Layer position adjustments — layer_positions","text":"4 ways 'position' part layer can specified. ways always equivalent. layers may understand position adjustment, require additional parameters passed position_*() function, may work correctly. example position_dodge() requires non-overlapping x intervals, whereas geom_point() dimensions calculate intervals . give positions string, take function name, remove position_ prefix, position_fill becomes \"fill\".","code":"1. A layer can have default position adjustments geom_jitter() # has `position = \"jitter\"` 2. It can be given to a layer as a string geom_point(position = \"jitter\") 3. The position function can be used to pass extra arguments geom_point(position = position_jitter(width = 1)) 4. It can be given to `layer()` directly layer( geom = \"point\", stat = \"identity\", position = \"jitter\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"pairing-geoms-with-positions","dir":"Reference","previous_headings":"","what":"Pairing geoms with positions","title":"Layer position adjustments — layer_positions","text":"geoms work better positions others. follows brief overview geoms position adjustments work well together.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"identity","dir":"Reference","previous_headings":"","what":"Identity","title":"Layer position adjustments — layer_positions","text":"position_identity() can work virtually geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"dodging","dir":"Reference","previous_headings":"","what":"Dodging","title":"Layer position adjustments — layer_positions","text":"position_dodge() pushes overlapping objects away one another requires group variable. position_dodge2() can work without group variables can handle variable widths. rule thumb, layers groups occupy range x-axis pair well dodging. layers width, may required specify manually position_dodge(width = ...). geoms pair well dodging geom_bar(), geom_boxplot(), geom_linerange(), geom_errorbar() geom_text().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"jittering","dir":"Reference","previous_headings":"","what":"Jittering","title":"Layer position adjustments — layer_positions","text":"position_jitter() adds random noise every point, can help overplotting. position_jitterdodge() , also dodges points. rule thumb, jittering works best points discrete x-positions. Jittering useful geom_point(), can also used geom_path() example.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"nudging","dir":"Reference","previous_headings":"","what":"Nudging","title":"Layer position adjustments — layer_positions","text":"position_nudge() can add offsets x- y-positions. can useful discrete positions want put object exactly middle. useful geom_text(), can used virtually geoms.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"stacking","dir":"Reference","previous_headings":"","what":"Stacking","title":"Layer position adjustments — layer_positions","text":"position_stack() useful displaying data top one another. can used geoms usually anchored x-axis, example geom_bar(), geom_area() geom_histogram().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"filling","dir":"Reference","previous_headings":"","what":"Filling","title":"Layer position adjustments — layer_positions","text":"position_fill() can used give proportions every x-position. Like stacking, filling useful geoms anchored x-axis, like geom_bar(), geom_area() geom_histogram().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"under-the-hood","dir":"Reference","previous_headings":"","what":"Under the hood","title":"Layer position adjustments — layer_positions","text":"Internally, positions represented ggproto classes occupy slot layer. classes inherit parental Position ggproto object orchestrates positions work. Briefly, positions given opportunity adjust data facet panel. information extending positions, see New positions section online book.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_sf.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new sf layer that auto-maps geometry data — layer_sf","title":"Create a new sf layer that auto-maps geometry data — layer_sf","text":"layer_sf() function variant layer() meant used extension developers writing new sf-based geoms stats. sf layer checks whether data contains geometry column, one found automatically mapped geometry aesthetic.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_sf.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new sf layer that auto-maps geometry data — layer_sf","text":"","code":"layer_sf( geom = NULL, stat = NULL, data = NULL, mapping = NULL, position = NULL, params = list(), inherit.aes = TRUE, check.aes = TRUE, check.param = TRUE, show.legend = NA )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_sf.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new sf layer that auto-maps geometry data — layer_sf","text":"geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. params Additional parameters geom stat. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). check.aes, check.param TRUE, default, check supplied parameters aesthetics understood geom stat. Use FALSE suppress checks. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":null,"dir":"Reference","previous_headings":"","what":"Layer statistical transformations — layer_stats","title":"Layer statistical transformations — layer_stats","text":"ggplot2, plot constructed adding layers . layer consists two important parts: geometry (geoms), statistical transformations (stats). 'stat' part layer important performs computation data displayed. Stats determine displayed, displayed. example, add stat_density() plot, kernel density estimation performed, can displayed 'geom' part layer. many geom_*() functions, stat_identity() used, performs extra computation data.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"specifying-stats","dir":"Reference","previous_headings":"","what":"Specifying stats","title":"Layer statistical transformations — layer_stats","text":"five ways 'stat' part layer can specified. Many ways absolutely equivalent. Using stat_density(geom = \"line\") identical using geom_line(stat = \"density\"). Note layer(), need provide \"position\" argument well. give stats string, take function name, remove stat_ prefix, stat_bin becomes \"bin\". well known stats can used stat argument : \"density\", \"bin\", \"count\", \"function\" \"smooth\".","code":"# 1. The stat can have a layer constructor stat_density() # 2. A geom can default to a particular stat geom_density() # has `stat = \"density\"` as default # 3. It can be given to a geom as a string geom_line(stat = \"density\") # 4. The ggproto object of a stat can be given geom_area(stat = StatDensity) # 5. It can be given to `layer()` directly: layer( geom = \"line\", stat = \"density\", position = \"identity\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"paired-geoms-and-stats","dir":"Reference","previous_headings":"","what":"Paired geoms and stats","title":"Layer statistical transformations — layer_stats","text":"geoms paired stats. cases, like geom_density(), just variant another geom, geom_area(), slightly different defaults. cases, relationship complex. case boxplots example, stat geom distinct roles. role stat compute five-number summary data. addition just displaying box five-number summary, geom also provides display options outliers widths boxplots. cases, freely exchange geoms stats: using stat_boxplot(geom = \"line\") geom_area(stat = \"boxplot\") give errors. stats geoms paired : geom_violin() stat_ydensity() geom_histogram() stat_bin() geom_contour() stat_contour() geom_function() stat_function() geom_bin_2d() stat_bin_2d() geom_boxplot() stat_boxplot() geom_count() stat_sum() geom_density() stat_density() geom_density_2d() stat_density_2d() geom_hex() stat_binhex() geom_quantile() stat_quantile() geom_smooth() stat_smooth()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"using-computed-variables","dir":"Reference","previous_headings":"","what":"Using computed variables","title":"Layer statistical transformations — layer_stats","text":"mentioned , role stats perform computation data. result, stats 'computed variables' determine compatibility geoms. computed variables documented Computed variables sections documentation, example ?stat_bin. thoroughly documented after_stat(), briefly mentioned computed stats can accessed aes(). example, ?stat_density documentation states , addition variable called density, stat computes variable named count. Instead scaling area integrates 1, count variable scales computed density values can interpreted counts. stat_density(aes(y = after_stat(count))) used, can display count-scaled densities instead regular densities. computed variables offer flexibility arbitrary geom-stat pairings can made. necessarily recommended, geom_line() can paired stat = \"boxplot\" line instructed use boxplot computed variables:","code":"ggplot(mpg, aes(factor(cyl))) + geom_line( # Stage gives 'displ' to the stat, and afterwards chooses 'middle' as # the y-variable to display aes(y = stage(displ, after_stat = middle), # Regroup after computing the stats to display a single line group = after_stat(1)), stat = \"boxplot\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"under-the-hood","dir":"Reference","previous_headings":"","what":"Under the hood","title":"Layer statistical transformations — layer_stats","text":"Internally, stats represented ggproto classes occupy slot layer. classes inherit parental Stat ggproto object orchestrates stats work. Briefly, stats given opportunity perform computation either layer whole, facet panel, individual groups. information extending stats, see Creating new stat section running vignette(\"extending-ggplot2\"). Additionally, see New stats section online book.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate correct scale type for specified limits — limits","title":"Generate correct scale type for specified limits — limits","text":"Generate correct scale type specified limits","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate correct scale type for specified limits — limits","text":"","code":"limits(lims, var, call = caller_env())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate correct scale type for specified limits — limits","text":"lims vector limits var name variable","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate correct scale type for specified limits — limits","text":"","code":"ggplot2:::limits(c(1, 5), \"x\") #> #> Range: #> Limits: 1 -- 5 ggplot2:::limits(c(5, 1), \"x\") #> #> Range: #> Limits: -5 -- -1 ggplot2:::limits(c(\"A\", \"b\", \"c\"), \"x\") #> #> aesthetics: x xmin xmax xend xintercept xmin_final xmax_final xlower ... #> axis_order: function #> break_info: function #> break_positions: function #> breaks: waiver #> call: environment #> clone: function #> dimension: function #> drop: TRUE #> expand: waiver #> get_breaks: function #> get_breaks_minor: function #> get_labels: function #> get_limits: function #> get_transformation: function #> guide: waiver #> is_discrete: function #> is_empty: function #> labels: waiver #> limits: A b c #> make_sec_title: function #> make_title: function #> map: function #> map_df: function #> minor_breaks: waiver #> n.breaks.cache: NULL #> na.translate: TRUE #> na.value: NA #> name: waiver #> palette: function #> palette.cache: NULL #> position: bottom #> range: environment #> range_c: environment #> rescale: function #> reset: function #> sec_name: function #> train: function #> train_df: function #> transform: function #> transform_df: function #> super: ggplot2:::limits(c(\"A\", \"b\", \"c\"), \"fill\") #> #> aesthetics: fill #> axis_order: function #> break_info: function #> break_positions: function #> breaks: waiver #> call: environment #> clone: function #> dimension: function #> drop: TRUE #> expand: waiver #> get_breaks: function #> get_breaks_minor: function #> get_labels: function #> get_limits: function #> get_transformation: function #> guide: legend #> is_discrete: function #> is_empty: function #> labels: waiver #> limits: A b c #> make_sec_title: function #> make_title: function #> map: function #> map_df: function #> minor_breaks: waiver #> n.breaks.cache: NULL #> na.translate: TRUE #> na.value: grey50 #> name: waiver #> palette: function #> palette.cache: NULL #> position: left #> range: environment #> rescale: function #> reset: function #> train: function #> train_df: function #> transform: function #> transform_df: function #> super: ggplot2:::limits(as.Date(c(\"2008-01-01\", \"2009-01-01\")), \"x\") #> #> Range: #> Limits: 1.39e+04 -- 1.42e+04"},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":null,"dir":"Reference","previous_headings":"","what":"Set scale limits — lims","title":"Set scale limits — lims","text":"shortcut supplying limits argument individual scales. default, values outside limits specified replaced NA. warned remove data outside limits can produce unintended results. changing x y axis limits without dropping data observations, see coord_cartesian().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set scale limits — lims","text":"","code":"lims(...) xlim(...) ylim(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set scale limits — lims","text":"... xlim() ylim(): Two numeric values, specifying left/lower limit right/upper limit scale. larger value given first, scale reversed. can leave one value NA want compute corresponding limit range data. lims(): name–value pair. name must aesthetic, value must either length-2 numeric, character, factor, date/time. numeric value create continuous scale. larger value comes first, scale reversed. can leave one value NA want compute corresponding limit range data. character factor value create discrete scale. date-time value create continuous date/time scale.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set scale limits — lims","text":"","code":"# Zoom into a specified area ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(15, 20) #> Warning: Removed 19 rows containing missing values or values outside the scale #> range (`geom_point()`). # reverse scale ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(20, 15) #> Warning: Removed 19 rows containing missing values or values outside the scale #> range (`geom_point()`). # with automatic lower limit ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(NA, 20) #> Warning: Removed 14 rows containing missing values or values outside the scale #> range (`geom_point()`). # You can also supply limits that are larger than the data. # This is useful if you want to match scales across different plots small <- subset(mtcars, cyl == 4) big <- subset(mtcars, cyl > 4) ggplot(small, aes(mpg, wt, colour = factor(cyl))) + geom_point() + lims(colour = c(\"4\", \"6\", \"8\")) ggplot(big, aes(mpg, wt, colour = factor(cyl))) + geom_point() + lims(colour = c(\"4\", \"6\", \"8\")) # There are two ways of setting the axis limits: with limits or # with coordinate systems. They work in two rather different ways. set.seed(1) last_month <- Sys.Date() - 0:59 df <- data.frame( date = last_month, price = c(rnorm(30, mean = 15), runif(30) + 0.2 * (1:30)) ) p <- ggplot(df, aes(date, price)) + geom_line() + stat_smooth() p #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Setting the limits with the scale discards all data outside the range. p + lims(x= c(Sys.Date() - 30, NA), y = c(10, 20)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' #> Warning: Removed 30 rows containing non-finite outside the scale range #> (`stat_smooth()`). #> Warning: Removed 30 rows containing missing values or values outside the scale #> range (`geom_line()`). # For changing x or y axis limits **without** dropping data # observations use [coord_cartesian()]. Setting the limits on the # coordinate system performs a visual zoom. p + coord_cartesian(xlim =c(Sys.Date() - 30, NA), ylim = c(10, 20)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'"},{"path":"https://ggplot2.tidyverse.org/dev/reference/luv_colours.html","id":null,"dir":"Reference","previous_headings":"","what":"colors() in Luv space — luv_colours","title":"colors() in Luv space — luv_colours","text":"built-colors() translated Luv colour space.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/luv_colours.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"colors() in Luv space — luv_colours","text":"","code":"luv_colours"},{"path":"https://ggplot2.tidyverse.org/dev/reference/luv_colours.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"colors() in Luv space — luv_colours","text":"data frame 657 observations 4 variables: L,u,v Position Luv colour space col Colour name","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a data frame of map data — map_data","title":"Create a data frame of map data — map_data","text":"Easily turn data maps package data frame suitable plotting ggplot2.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a data frame of map data — map_data","text":"","code":"map_data(map, region = \".\", exact = FALSE, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a data frame of map data — map_data","text":"map name map provided maps package. include maps::county(), maps::france(), maps::italy(), maps::nz(), maps::state(), maps::usa(), maps::world(), maps::world2(). region name(s) subregion(s) include. Defaults . includes subregions. See documentation maps::map() details. exact region treated regular expression (FALSE) fixed string (TRUE). ... arguments passed maps::map()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a data frame of map data — map_data","text":"","code":"if (require(\"maps\")) { states <- map_data(\"state\") arrests <- USArrests names(arrests) <- tolower(names(arrests)) arrests$region <- tolower(rownames(USArrests)) choro <- merge(states, arrests, sort = FALSE, by = \"region\") choro <- choro[order(choro$order), ] ggplot(choro, aes(long, lat)) + geom_polygon(aes(group = group, fill = assault)) + coord_map(\"albers\", lat0 = 45.5, lat1 = 29.5) } if (require(\"maps\")) { ggplot(choro, aes(long, lat)) + geom_polygon(aes(group = group, fill = assault / murder)) + coord_map(\"albers\", lat0 = 45.5, lat1 = 29.5) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":null,"dir":"Reference","previous_headings":"","what":"Get the maximal width/length of a list of grobs — max_height","title":"Get the maximal width/length of a list of grobs — max_height","text":"Get maximal width/length list grobs","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get the maximal width/length of a list of grobs — max_height","text":"","code":"max_height(grobs, value_only = FALSE) max_width(grobs, value_only = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get the maximal width/length of a list of grobs — max_height","text":"grobs list grobs value_only return value simple numeric vector giving maximum cm","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get the maximal width/length of a list of grobs — max_height","text":"largest value. measured cm unit object numeric vector depending value_only","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate mean and standard error of the mean — mean_se","title":"Calculate mean and standard error of the mean — mean_se","text":"use stat_summary()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate mean and standard error of the mean — mean_se","text":"","code":"mean_se(x, mult = 1)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate mean and standard error of the mean — mean_se","text":"x numeric vector. mult number multiples standard error.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Calculate mean and standard error of the mean — mean_se","text":"data frame three columns: y mean. ymin mean minus multiples standard error. ymax mean plus multiples standard error.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Calculate mean and standard error of the mean — mean_se","text":"","code":"set.seed(1) x <- rnorm(100) mean_se(x) #> y ymin ymax #> 1 0.1088874 0.01906743 0.1987073"},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":null,"dir":"Reference","previous_headings":"","what":"Merge a parent element into a child element — merge_element","title":"Merge a parent element into a child element — merge_element","text":"generic element classes must provide implementation method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Merge a parent element into a child element — merge_element","text":"","code":"merge_element(new, old) # Default S3 method merge_element(new, old) # S3 method for class 'element_blank' merge_element(new, old) # S3 method for class 'element' merge_element(new, old)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Merge a parent element into a child element — merge_element","text":"new child element theme hierarchy old parent element theme hierarchy","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Merge a parent element into a child element — merge_element","text":"modified version new updated properties old","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Merge a parent element into a child element — merge_element","text":"","code":"new <- element_text(colour = \"red\") old <- element_text(colour = \"blue\", size = 10) # Adopt size but ignore colour merge_element(new, old) #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : chr \"red\" #> $ size : num 10 #> $ hjust : NULL #> $ vjust : NULL #> $ angle : NULL #> $ lineheight : NULL #> $ margin : NULL #> $ debug : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":null,"dir":"Reference","previous_headings":"","what":"Midwest demographics — midwest","title":"Midwest demographics — midwest","text":"Demographic information midwest counties 2000 US census","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Midwest demographics — midwest","text":"","code":"midwest"},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Midwest demographics — midwest","text":"data frame 437 rows 28 variables: PID Unique county identifier. county County name. state State county belongs . area Area county (units unknown). poptotal Total population. popdensity Population density (person/unit area). popwhite Number whites. popblack Number blacks. popamerindian Number American Indians. popasian Number Asians. popother Number races. percwhite Percent white. percblack Percent black. percamerindan Percent American Indian. percasian Percent Asian. percother Percent races. popadults Number adults. perchsd Percent high school diploma. percollege Percent college educated. percprof Percent professional degree. poppovertyknown Population known poverty status. percpovertyknown Percent population known poverty status. percbelowpoverty Percent people poverty line. percchildbelowpovert Percent children poverty line. percadultpoverty Percent adults poverty line. percelderlypoverty Percent elderly poverty line. inmetro County considered metro area. category Miscellaneous.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Midwest demographics — midwest","text":"Note: dataset included illustrative purposes. original descriptions documented current descriptions based speculation. accurate --date US census data, see acs package.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mpg.html","id":null,"dir":"Reference","previous_headings":"","what":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","title":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","text":"dataset contains subset fuel economy data EPA makes available https://fueleconomy.gov/. contains models new release every year 1999 2008 - used proxy popularity car.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mpg.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","text":"","code":"mpg"},{"path":"https://ggplot2.tidyverse.org/dev/reference/mpg.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","text":"data frame 234 rows 11 variables: manufacturer manufacturer name model model name displ engine displacement, litres year year manufacture cyl number cylinders trans type transmission drv type drive train, 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\" car","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":null,"dir":"Reference","previous_headings":"","what":"An updated and expanded version of the mammals sleep dataset — msleep","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"updated expanded version mammals sleep dataset. Updated sleep times weights taken V. M. Savage G. B. West. quantitative, theoretical framework understanding mammalian sleep. Proceedings National Academy Sciences, 104 (3):1051-1056, 2007.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"","code":"msleep"},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"data frame 83 rows 11 variables: name common name genus vore carnivore, omnivore herbivore? order conservation conservation status animal sleep_total total amount sleep, hours sleep_rem rem sleep, hours sleep_cycle length sleep cycle, hours awake amount time spent awake, hours brainwt brain weight kilograms bodywt body weight kilograms","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"Additional variables order, conservation status vore added wikipedia.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":null,"dir":"Reference","previous_headings":"","what":"Guide constructor — new_guide","title":"Guide constructor — new_guide","text":"constructor function guides, performs standard compatibility checks guide provided arguments.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Guide constructor — new_guide","text":"","code":"new_guide(..., available_aes = \"any\", super)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Guide constructor — new_guide","text":"... Named arguments match parameters super$params theme elements super$elements. available_aes vector character strings listing aesthetics guide can drawn. super super class use constructed guide. Guide class object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Guide constructor — new_guide","text":"Guide ggproto object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/old_guide.html","id":null,"dir":"Reference","previous_headings":"","what":"The previous S3 guide system — old_guide","title":"The previous S3 guide system — old_guide","text":"guide system overhauled use ggproto infrastructure accommodate guide extensions flexibility layers, scales ggplot2 objects. rewriting, old S3 system become defunct, meaning previous methods guides superseded ggproto methods. fallback option, generics, methods, previous S3 system used encapsulated GuideOld ggproto class.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/old_guide.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"The previous S3 guide system — old_guide","text":"","code":"guide_train(guide, scale, aesthetic = NULL) guide_merge(guide, new_guide) guide_geom(guide, layers, default_mapping = NULL) guide_transform(guide, coord, panel_params) guide_gengrob(guide, theme) old_guide(guide)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/old_guide.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"The previous S3 guide system — old_guide","text":"guide old guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify transparency for patterns — pattern_alpha","title":"Modify transparency for patterns — pattern_alpha","text":"generic allows add methods adding transparency pattern-like objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify transparency for patterns — pattern_alpha","text":"","code":"pattern_alpha(x, alpha)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify transparency for patterns — pattern_alpha","text":"x Object interpreted pattern. alpha numeric vector 0 1. NA, alpha values preserved.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Modify transparency for patterns — pattern_alpha","text":"x modified transparency","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":null,"dir":"Reference","previous_headings":"","what":"Dodge overlapping objects side-to-side — position_dodge","title":"Dodge overlapping objects side-to-side — position_dodge","text":"Dodging preserves vertical position geom adjusting horizontal position. position_dodge() requires grouping variable specified global geom_* layer. Unlike position_dodge(), position_dodge2() works without grouping variable layer. position_dodge2() works bars rectangles, particularly useful arranging box plots, can variable widths.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Dodge overlapping objects side-to-side — position_dodge","text":"","code":"position_dodge( width = NULL, preserve = \"total\", orientation = \"x\", reverse = FALSE ) position_dodge2( width = NULL, preserve = \"total\", padding = 0.1, reverse = FALSE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Dodge overlapping objects side-to-side — position_dodge","text":"width Dodging width, different width individual elements. useful want align narrow geoms wider geoms. See examples. preserve dodging preserve \"total\" width elements position, width \"single\" element? orientation Fallback orientation layer data indicate explicit orientation, like geom_point(). Can \"x\" (default) \"y\". reverse TRUE, reverse default stacking order. useful rotating plot legend. padding Padding elements position. Elements shrunk proportion allow space . Defaults 0.1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Dodge overlapping objects side-to-side — position_dodge","text":"","code":"ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = \"dodge2\") # By default, dodging with `position_dodge2()` preserves the total width of # the elements. You can choose to preserve the width of each element with: ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = \"single\")) # \\donttest{ ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(position=\"dodge2\") #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # see ?geom_bar for more examples # In this case a frequency polygon is probably a better choice ggplot(diamonds, aes(price, colour = cut)) + geom_freqpoly() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # } # Dodging with various widths ------------------------------------- # To dodge items with different widths, you need to be explicit df <- data.frame( x = c(\"a\",\"a\",\"b\",\"b\"), y = 2:5, g = rep(1:2, 2) ) p <- ggplot(df, aes(x, y, group = g)) + geom_col(position = \"dodge\", fill = \"grey50\", colour = \"black\") p # A line range has no width: p + geom_linerange(aes(ymin = y - 1, ymax = y + 1), position = \"dodge\") #> Warning: Width not defined #> ℹ Set with `position_dodge(width = ...)` # So you must explicitly specify the width p + geom_linerange( aes(ymin = y - 1, ymax = y + 1), position = position_dodge(width = 0.9) ) # The same principle applies to error bars, which are usually # narrower than the bars p + geom_errorbar( aes(ymin = y - 1, ymax = y + 1), width = 0.2, position = \"dodge\" ) p + geom_errorbar( aes(ymin = y - 1, ymax = y + 1), width = 0.2, position = position_dodge(width = 0.9) ) # Box plots use position_dodge2 by default, and bars can use it too ggplot(mpg, aes(factor(year), displ)) + geom_boxplot(aes(colour = hwy < 30)) ggplot(mpg, aes(factor(year), displ)) + geom_boxplot(aes(colour = hwy < 30), varwidth = TRUE) ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = \"single\")) ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = \"total\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_identity.html","id":null,"dir":"Reference","previous_headings":"","what":"Don't adjust position — position_identity","title":"Don't adjust position — position_identity","text":"adjust position","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_identity.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Don't adjust position — position_identity","text":"","code":"position_identity()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":null,"dir":"Reference","previous_headings":"","what":"Jitter points to avoid overplotting — position_jitter","title":"Jitter points to avoid overplotting — position_jitter","text":"Counterintuitively adding random noise plot can sometimes make easier read. Jittering particularly useful small datasets least one discrete position.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Jitter points to avoid overplotting — position_jitter","text":"","code":"position_jitter(width = NULL, height = NULL, seed = NA)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Jitter points to avoid overplotting — position_jitter","text":"width, height Amount vertical horizontal jitter. jitter added positive negative directions, total spread twice value specified . omitted, defaults 40% resolution data: means jitter values occupy 80% implied bins. Categorical data aligned integers, width height 0.5 spread data possible see distinction categories. seed random seed make jitter reproducible. Useful need apply jitter twice, e.g., point corresponding label. random seed reset jittering. NA (default value), seed initialised random value; makes sure two subsequent calls start different seed. Use NULL use current random seed also avoid resetting (behaviour ggplot 2.2.1 earlier).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Jitter points to avoid overplotting — position_jitter","text":"","code":"# Jittering is useful when you have a discrete position, and a relatively # small number of points # take up as much space as a boxplot or a bar ggplot(mpg, aes(class, hwy)) + geom_boxplot(colour = \"grey50\") + geom_jitter() # If the default jittering is too much, as in this plot: ggplot(mtcars, aes(am, vs)) + geom_jitter() # You can adjust it in two ways ggplot(mtcars, aes(am, vs)) + geom_jitter(width = 0.1, height = 0.1) ggplot(mtcars, aes(am, vs)) + geom_jitter(position = position_jitter(width = 0.1, height = 0.1)) # Create a jitter object for reproducible jitter: jitter <- position_jitter(width = 0.1, height = 0.1, seed = 0) ggplot(mtcars, aes(am, vs)) + geom_point(position = jitter) + geom_point(position = jitter, color = \"red\", aes(am + 0.2, vs + 0.2))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":null,"dir":"Reference","previous_headings":"","what":"Simultaneously dodge and jitter — position_jitterdodge","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"primarily used aligning points generated geom_point() dodged boxplots (e.g., geom_boxplot() fill aesthetic supplied).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"","code":"position_jitterdodge( jitter.width = NULL, jitter.height = 0, dodge.width = 0.75, reverse = FALSE, seed = NA )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"jitter.width degree jitter x direction. Defaults 40% resolution data. jitter.height degree jitter y direction. Defaults 0. dodge.width amount dodge x direction. Defaults 0.75, default position_dodge() width. reverse TRUE, reverse default stacking order. useful rotating plot legend. seed random seed make jitter reproducible. Useful need apply jitter twice, e.g., point corresponding label. random seed reset jittering. NA (default value), seed initialised random value; makes sure two subsequent calls start different seed. Use NULL use current random seed also avoid resetting (behaviour ggplot 2.2.1 earlier).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"","code":"set.seed(596) dsub <- diamonds[sample(nrow(diamonds), 1000), ] ggplot(dsub, aes(x = cut, y = carat, fill = clarity)) + geom_boxplot(outlier.size = 0) + geom_point(pch = 21, position = position_jitterdodge())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":null,"dir":"Reference","previous_headings":"","what":"Nudge points a fixed distance — position_nudge","title":"Nudge points a fixed distance — position_nudge","text":"position_nudge() generally useful adjusting position items discrete scales small amount. Nudging built geom_text() useful moving labels small distance labelling.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Nudge points a fixed distance — position_nudge","text":"","code":"position_nudge(x = 0, y = 0)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Nudge points a fixed distance — position_nudge","text":"x, y Amount vertical horizontal distance move.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Nudge points a fixed distance — position_nudge","text":"","code":"df <- data.frame( x = c(1,3,2,5), y = c(\"a\",\"c\",\"d\",\"c\") ) ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y)) ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y), position = position_nudge(y = -0.1)) # Or, in brief ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y), nudge_y = -0.1)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":null,"dir":"Reference","previous_headings":"","what":"Stack overlapping objects on top of each another — position_stack","title":"Stack overlapping objects on top of each another — position_stack","text":"position_stack() stacks bars top ; position_fill() stacks bars standardises stack constant height.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Stack overlapping objects on top of each another — position_stack","text":"","code":"position_stack(vjust = 1, reverse = FALSE) position_fill(vjust = 1, reverse = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Stack overlapping objects on top of each another — position_stack","text":"vjust Vertical adjustment geoms position (like points lines), dimension (like bars areas). Set 0 align bottom, 0.5 middle, 1 (default) top. reverse TRUE, reverse default stacking order. useful rotating plot legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Stack overlapping objects on top of each another — position_stack","text":"position_fill() position_stack() automatically stack values reverse order group aesthetic, bar charts usually defined fill aesthetic (default group aesthetic formed combination discrete aesthetics except x y). default ensures bar colours align default legend. three ways override defaults depending want: Change order levels underlying factor. change stacking order, order keys legend. Set legend breaks change order keys without affecting stacking. Manually set group aesthetic change stacking order without affecting legend. Stacking positive negative values performed separately positive values stack upwards x-axis negative values stack downward. stacking performed scale transformations, stacking non-linear scales gives distortions easily lead misinterpretations data. therefore discouraged use position adjustments combination scale transformations, logarithmic square root scales.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Stack overlapping objects on top of each another — position_stack","text":"","code":"# Stacking and filling ------------------------------------------------------ # Stacking is the default behaviour for most area plots. # Fill makes it easier to compare proportions ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar() ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = \"fill\") ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500) ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500, position = \"fill\") # Stacking is also useful for time series set.seed(1) series <- data.frame( time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)), type = rep(c('a', 'b', 'c', 'd'), 4), value = rpois(16, 10) ) ggplot(series, aes(time, value)) + geom_area(aes(fill = type)) # Stacking order ------------------------------------------------------------ # The stacking order is carefully designed so that the plot matches # the legend. # You control the stacking order by setting the levels of the underlying # factor. See the forcats package for convenient helpers. series$type2 <- factor(series$type, levels = c('c', 'b', 'd', 'a')) ggplot(series, aes(time, value)) + geom_area(aes(fill = type2)) # You can change the order of the levels in the legend using the scale ggplot(series, aes(time, value)) + geom_area(aes(fill = type)) + scale_fill_discrete(breaks = c('a', 'b', 'c', 'd')) # If you've flipped the plot, use reverse = TRUE so the levels # continue to match ggplot(series, aes(time, value)) + geom_area(aes(fill = type2), position = position_stack(reverse = TRUE)) + coord_flip() + theme(legend.position = \"top\") # Non-area plots ------------------------------------------------------------ # When stacking across multiple layers it's a good idea to always set # the `group` aesthetic in the ggplot() call. This ensures that all layers # are stacked in the same way. ggplot(series, aes(time, value, group = type)) + geom_line(aes(colour = type), position = \"stack\") + geom_point(aes(colour = type), position = \"stack\") ggplot(series, aes(time, value, group = type)) + geom_area(aes(fill = type)) + geom_line(aes(group = type), position = \"stack\") # You can also stack labels, but the default position is suboptimal. ggplot(series, aes(time, value, group = type)) + geom_area(aes(fill = type)) + geom_text(aes(label = type), position = \"stack\") # You can override this with the vjust parameter. A vjust of 0.5 # will center the labels inside the corresponding area ggplot(series, aes(time, value, group = type)) + geom_area(aes(fill = type)) + geom_text(aes(label = type), position = position_stack(vjust = 0.5)) # Negative values ----------------------------------------------------------- df <- data.frame( x = rep(c(\"a\", \"b\"), 2:3), y = c(1, 2, 1, 3, -1), grp = c(\"x\", \"y\", \"x\", \"y\", \"y\") ) ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = position_stack(reverse = TRUE)) + geom_hline(yintercept = 0) ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp)) + geom_hline(yintercept = 0) + geom_text(aes(label = grp), position = position_stack(vjust = 0.5))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/presidential.html","id":null,"dir":"Reference","previous_headings":"","what":"Terms of 12 presidents from Eisenhower to Trump — presidential","title":"Terms of 12 presidents from Eisenhower to Trump — presidential","text":"names president, start end date term, party 12 US presidents Eisenhower Trump. data public domain.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/presidential.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Terms of 12 presidents from Eisenhower to Trump — presidential","text":"","code":"presidential"},{"path":"https://ggplot2.tidyverse.org/dev/reference/presidential.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Terms of 12 presidents from Eisenhower to Trump — presidential","text":"data frame 12 rows 4 variables: name Last name president start Presidency start date end Presidency end date party Party president","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Explicitly draw plot — print.ggplot","title":"Explicitly draw plot — print.ggplot","text":"Generally, need print plot ggplot2 plot explicitly: default top-level print method . , however, need call print() explicitly want draw plot inside function loop.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Explicitly draw plot — print.ggplot","text":"","code":"# S3 method for class 'ggplot' print(x, newpage = is.null(vp), vp = NULL, ...) # S3 method for class 'ggplot' plot(x, newpage = is.null(vp), vp = NULL, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Explicitly draw plot — print.ggplot","text":"x plot display newpage draw new (empty) page first? vp viewport draw plot ... arguments used method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Explicitly draw plot — print.ggplot","text":"Invisibly returns original plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Explicitly draw plot — print.ggplot","text":"","code":"colours <- list(~class, ~drv, ~fl) # Doesn't seem to do anything! for (colour in colours) { ggplot(mpg, aes_(~ displ, ~ hwy, colour = colour)) + geom_point() } #> Warning: `aes_()` was deprecated in ggplot2 3.0.0. #> ℹ Please use tidy evaluation idioms with `aes()` # Works when we explicitly print the plots for (colour in colours) { print(ggplot(mpg, aes_(~ displ, ~ hwy, colour = colour)) + geom_point()) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Format or print a ggproto object — print.ggproto","title":"Format or print a ggproto object — print.ggproto","text":"ggproto object $print method, call method. Otherwise, print members object, optionally, members inherited objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Format or print a ggproto object — print.ggproto","text":"","code":"# S3 method for class 'ggproto' print(x, ..., flat = TRUE) # S3 method for class 'ggproto' format(x, ..., flat = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Format or print a ggproto object — print.ggproto","text":"x ggproto object print. ... ggproto object print method, arguments passed . Otherwise, arguments unused. flat TRUE (default), show flattened list local inherited members. FALSE, show inheritance hierarchy.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Format or print a ggproto object — print.ggproto","text":"","code":"Dog <- ggproto( print = function(self, n) { cat(\"Woof!\\n\") } ) Dog #> Woof! cat(format(Dog), \"\\n\") #> #> print: function"},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Quick plot — qplot","title":"Quick plot — qplot","text":"qplot() now deprecated order encourage users learn ggplot() makes easier create complex graphics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Quick plot — qplot","text":"","code":"qplot( x, y, ..., data, facets = NULL, margins = FALSE, geom = \"auto\", xlim = c(NA, NA), ylim = c(NA, NA), log = \"\", main = NULL, xlab = NULL, ylab = NULL, asp = NA, stat = deprecated(), position = deprecated() ) quickplot( x, y, ..., data, facets = NULL, margins = FALSE, geom = \"auto\", xlim = c(NA, NA), ylim = c(NA, NA), log = \"\", main = NULL, xlab = NULL, ylab = NULL, asp = NA, stat = deprecated(), position = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Quick plot — qplot","text":"x, y, ... Aesthetics passed layer data Data frame use (optional). specified, create one, extracting vectors current environment. facets faceting formula use. Picks facet_wrap() facet_grid() depending whether formula one- two-sided margins See facet_grid(): display marginal facets? geom Character vector specifying geom(s) draw. Defaults \"point\" x y specified, \"histogram\" x specified. xlim, ylim X y axis limits log variables log transform (\"x\", \"y\", \"xy\") main, xlab, ylab Character vector (expression) giving plot title, x axis label, y axis label respectively. asp y/x aspect ratio stat, position","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Quick plot — qplot","text":"","code":"# Use data from data.frame qplot(mpg, wt, data = mtcars) #> Warning: `qplot()` was deprecated in ggplot2 3.4.0. qplot(mpg, wt, data = mtcars, colour = cyl) qplot(mpg, wt, data = mtcars, size = cyl) qplot(mpg, wt, data = mtcars, facets = vs ~ am) # \\donttest{ set.seed(1) qplot(1:10, rnorm(10), colour = runif(10)) qplot(1:10, letters[1:10]) mod <- lm(mpg ~ wt, data = mtcars) qplot(resid(mod), fitted(mod)) f <- function() { a <- 1:10 b <- a ^ 2 qplot(a, b) } f() # To set aesthetics, wrap in I() qplot(mpg, wt, data = mtcars, colour = I(\"red\")) # qplot will attempt to guess what geom you want depending on the input # both x and y supplied = scatterplot qplot(mpg, wt, data = mtcars) # just x supplied = histogram qplot(mpg, data = mtcars) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # just y supplied = scatterplot, with x = seq_along(y) qplot(y = mpg, data = mtcars) # Use different geoms qplot(mpg, wt, data = mtcars, geom = \"path\") qplot(factor(cyl), wt, data = mtcars, geom = c(\"boxplot\", \"jitter\")) qplot(mpg, data = mtcars, geom = \"dotplot\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/reexports.html","id":null,"dir":"Reference","previous_headings":"","what":"Objects exported from other packages — reexports","title":"Objects exported from other packages — reexports","text":"objects imported packages. Follow links see documentation. grid arrow, unit scales alpha","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/reexports.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Objects exported from other packages — reexports","text":"","code":"ggplot(mpg, aes(displ, hwy)) + geom_point(alpha = 0.5, colour = \"blue\") ggplot(mpg, aes(displ, hwy)) + geom_point(colour = alpha(\"blue\", 0.5))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":null,"dir":"Reference","previous_headings":"","what":"Define and register new theme elements — register_theme_elements","title":"Define and register new theme elements — register_theme_elements","text":"underlying structure ggplot2 theme defined via element tree, specifies theme element type whether inherits parent element. use cases, may necessary modify extend element tree provide default settings newly defined theme elements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Define and register new theme elements — register_theme_elements","text":"","code":"register_theme_elements(..., element_tree = NULL, complete = TRUE) reset_theme_settings(reset_current = TRUE) get_element_tree() el_def(class = NULL, inherit = NULL, description = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Define and register new theme elements — register_theme_elements","text":"... Element specifications element_tree Addition modification element tree, specifies inheritance relationship theme elements. element tree must provided list named element definitions created el_def(). complete TRUE (default), elements set inherit blank elements. reset_current TRUE (default), currently active theme reset default theme. class name element class. Examples \"element_line\" \"element_text\" \"unit\", one two reserved keywords \"character\" \"margin\". reserved keyword \"character\" implies character numeric vector, class called \"character\". keyword \"margin\" implies unit vector length 4, created margin(). inherit vector strings, naming elements element inherits . description optional character vector providing description element.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Define and register new theme elements — register_theme_elements","text":"function register_theme_elements() provides option globally register new theme elements ggplot2. general, new theme element element definition corresponding entry element tree provided. See examples details. function meant primarily developers extension packages, strongly urged adhere following best practices: Call register_theme_elements() .onLoad() function package, new theme elements available anybody using functions package, irrespective whether package attached (library() require()) . new elements create, prepend name package, avoid name clashes extension packages. example, working package ggxyz, want provide new element plot panel annotations (demonstrated Examples ), name new element ggxyz.panel.annotation. function reset_theme_settings() restores default element tree, discards new element definitions, (unless turned ) resets currently active theme default. function get_element_tree() returns currently active element tree. function el_def() used define new modified element types element inheritance relationships element tree.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Define and register new theme elements — register_theme_elements","text":"","code":"# Let's assume a package `ggxyz` wants to provide an easy way to add annotations to # plot panels. To do so, it registers a new theme element `ggxyz.panel.annotation` register_theme_elements( ggxyz.panel.annotation = element_text(color = \"blue\", hjust = 0.95, vjust = 0.05), element_tree = list(ggxyz.panel.annotation = el_def(\"element_text\", \"text\")) ) # Now the package can define a new coord that includes a panel annotation coord_annotate <- function(label = \"panel annotation\") { ggproto(NULL, CoordCartesian, limits = list(x = NULL, y = NULL), expand = TRUE, default = FALSE, clip = \"on\", render_fg = function(panel_params, theme) { element_render(theme, \"ggxyz.panel.annotation\", label = label) } ) } # Example plot with this new coord df <- data.frame(x = 1:3, y = 1:3) ggplot(df, aes(x, y)) + geom_point() + coord_annotate(\"annotation in blue\") # Revert to the original ggplot2 settings reset_theme_settings()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/remove_missing.html","id":null,"dir":"Reference","previous_headings":"","what":"Convenience function to remove missing values from a data.frame — remove_missing","title":"Convenience function to remove missing values from a data.frame — remove_missing","text":"Remove non-complete rows, warning na.rm = FALSE. ggplot somewhat accommodating missing values R generally. stats require complete data, missing values automatically removed warning. na.rm = TRUE supplied statistic, warning suppressed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/remove_missing.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Convenience function to remove missing values from a data.frame — remove_missing","text":"","code":"remove_missing(df, na.rm = FALSE, vars = names(df), name = \"\", finite = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/remove_missing.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Convenience function to remove missing values from a data.frame — remove_missing","text":"df data.frame na.rm true, suppress warning message. vars Character vector variables check missings name Optional function name improve error message. finite TRUE, also remove non-finite values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":null,"dir":"Reference","previous_headings":"","what":"Render panel axes — render_axes","title":"Render panel axes — render_axes","text":"helpers facilitates generating theme compliant axes building plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Render panel axes — render_axes","text":"","code":"render_axes(x = NULL, y = NULL, coord, theme, transpose = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Render panel axes — render_axes","text":"x, y list ranges available draw_panel method Facet subclasses. coord Coord object theme theme object transpose output transposed?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Render panel axes — render_axes","text":"list element \"x\" \"y\" containing axis specifications ranges passed . axis specification list \"top\" \"bottom\" element x-axes \"left\" \"right\" element y-axis, holding respective axis grobs. Depending content x y grobs might zeroGrobs. transpose=TRUE content x y elements transposed e.g. left-axes collected left element list grobs.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":null,"dir":"Reference","previous_headings":"","what":"Render panel strips — render_strips","title":"Render panel strips — render_strips","text":"positions rendered facet decide use","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Render panel strips — render_strips","text":"","code":"render_strips(x = NULL, y = NULL, labeller = identity, theme)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Render panel strips — render_strips","text":"x, y data.frame column variable row combination draw labeller labeller function theme theme object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Render panel strips — render_strips","text":"list \"x\" \"y\" element, containing \"top\" \"bottom\" \"left\" \"right\" element respectively. contains list rendered strips gtables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute the ","title":"Compute the ","text":"resolution smallest non-zero distance adjacent values. one unique value, resolution defined one. x integer vector, assumed represent discrete variable, resolution 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute the ","text":"","code":"resolution(x, zero = TRUE, discrete = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute the ","text":"x numeric vector zero zero value automatically included computation resolution discrete vectors mapped discrete scale treated resolution 1?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute the ","text":"","code":"resolution(1:10) #> [1] 1 resolution((1:10) - 0.5) #> [1] 0.5 resolution((1:10) - 0.5, FALSE) #> [1] 1 # Note the difference between numeric and integer vectors resolution(c(2, 10, 20, 50)) #> [1] 2 resolution(c(2L, 10L, 20L, 50L)) #> [1] 1"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Alpha transparency scales — scale_alpha","title":"Alpha transparency scales — scale_alpha","text":"Alpha-transparency scales tremendously useful, can convenient way visually -weight less important observations. scale_alpha() alias scale_alpha_continuous() since common use alpha, saves bit typing.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Alpha transparency scales — scale_alpha","text":"","code":"scale_alpha(name = waiver(), ..., range = c(0.1, 1)) scale_alpha_continuous(name = waiver(), ..., range = c(0.1, 1)) scale_alpha_binned(name = waiver(), ..., range = c(0.1, 1)) scale_alpha_discrete(...) scale_alpha_ordinal(name = waiver(), ..., range = c(0.1, 1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Alpha transparency scales — scale_alpha","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed continuous_scale(), binned_scale(), discrete_scale() appropriate, control name, limits, breaks, labels forth. range Output range alpha values. Must lie 0 1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Alpha transparency scales — scale_alpha","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point(aes(alpha = year)) # The default range of 0.1-1.0 leaves all data visible p # Include 0 in the range to make data invisible p + scale_alpha(range = c(0, 1)) # Changing the title p + scale_alpha(\"cylinders\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":null,"dir":"Reference","previous_headings":"","what":"Positional scales for binning continuous data (x & y) — scale_binned","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"scale_x_binned() scale_y_binned() scales discretize continuous position data. can use scales transform continuous inputs using geom requires discrete positions. example using scale_x_binned() geom_bar() create histogram.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"","code":"scale_x_binned( name = waiver(), n.breaks = 10, nice.breaks = TRUE, breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = squish, na.value = NA_real_, right = TRUE, show.limits = FALSE, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"bottom\" ) scale_y_binned( name = waiver(), n.breaks = 10, nice.breaks = TRUE, breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = squish, na.value = NA_real_, right = TRUE, show.limits = FALSE, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"left\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. n.breaks number break points create breaks given directly. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::squish()) squishes bounds values range. scales::censor replacing bounds values NA. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. right intervals closed right (TRUE, default) intervals closed left (FALSE)? 'Closed right' means values break positions part lower bin (open left), whereas part upper bin intervals closed left (open right). show.limits limits scale appear ticks transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"","code":"# Create a histogram by binning the x-axis ggplot(mtcars) + geom_bar(aes(mpg)) + scale_x_binned()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":null,"dir":"Reference","previous_headings":"","what":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"brewer scales provide sequential, diverging qualitative colour schemes ColorBrewer. particularly well suited display discrete values map. See https://colorbrewer2.org information.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"","code":"scale_colour_brewer( name = waiver(), ..., type = \"seq\", palette = 1, direction = 1, aesthetics = \"colour\" ) scale_fill_brewer( name = waiver(), ..., type = \"seq\", palette = 1, direction = 1, aesthetics = \"fill\" ) scale_colour_distiller( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_distiller( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_fermenter( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_fill_fermenter( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed discrete_scale(), continuous_scale(), binned_scale(), brewer, distiller, fermenter variants respectively, control name, limits, breaks, labels forth. type One \"seq\" (sequential), \"div\" (diverging) \"qual\" (qualitative) palette string, use named palette. number, index list palettes appropriate type. list available palettes can found Palettes section. direction Sets order colours scale. 1, default, colours output RColorBrewer::brewer.pal(). -1, order colours reversed. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Colour use missing values guide Type legend. Use \"colourbar\" continuous colour bar, \"legend\" discrete colour legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"brewer scales carefully designed tested discrete data. designed extended continuous data, results often look good. mileage may vary.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"distiller scales extend brewer scales smoothly interpolating 7 colours palette continuous scale. distiller scales default direction = -1. reverse, use direction = 1. fermenter scales provide binned versions brewer scales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"palettes","dir":"Reference","previous_headings":"","what":"Palettes","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"following palettes available use scales: Diverging BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral Qualitative Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3 Sequential Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd Modify palette palette argument.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"","code":"set.seed(596) dsamp <- diamonds[sample(nrow(diamonds), 1000), ] (d <- ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity))) d + scale_colour_brewer() # Change scale label d + scale_colour_brewer(\"Diamond\\nclarity\") # Select brewer palette to use, see ?scales::pal_brewer for more details d + scale_colour_brewer(palette = \"Greens\") d + scale_colour_brewer(palette = \"Set1\") # \\donttest{ # scale_fill_brewer works just the same as # scale_colour_brewer but for fill colours p <- ggplot(diamonds, aes(x = price, fill = cut)) + geom_histogram(position = \"dodge\", binwidth = 1000) p + scale_fill_brewer() # the order of colour can be reversed p + scale_fill_brewer(direction = -1) # the brewer scales look better on a darker background p + scale_fill_brewer(direction = -1) + theme_dark() # } # Use distiller variant with continuous data v <- ggplot(faithfuld) + geom_tile(aes(waiting, eruptions, fill = density)) v v + scale_fill_distiller() v + scale_fill_distiller(palette = \"Spectral\") # the order of colour can be reversed, but with scale_*_distiller(), # the default direction = -1, so to reverse, use direction = 1. v + scale_fill_distiller(palette = \"Spectral\", direction = 1) # or use blender variants to discretise continuous data v + scale_fill_fermenter()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":null,"dir":"Reference","previous_headings":"","what":"Continuous and binned colour scales — scale_colour_continuous","title":"Continuous and binned colour scales — scale_colour_continuous","text":"scales scale_colour_continuous() scale_fill_continuous() default colour scales ggplot2 uses continuous data values mapped onto colour fill aesthetics, respectively. scales scale_colour_binned() scale_fill_binned() equivalent scale functions assign discrete color bins continuous values instead using continuous color spectrum.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Continuous and binned colour scales — scale_colour_continuous","text":"","code":"scale_colour_continuous(..., type = getOption(\"ggplot2.continuous.colour\")) scale_fill_continuous(..., type = getOption(\"ggplot2.continuous.fill\")) scale_colour_binned(..., type = getOption(\"ggplot2.binned.colour\")) scale_fill_binned(..., type = getOption(\"ggplot2.binned.fill\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Continuous and binned colour scales — scale_colour_continuous","text":"... Additional parameters passed scale type type One following: \"gradient\" (default) \"viridis\" function returns continuous colour scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Continuous and binned colour scales — scale_colour_continuous","text":"colour scales use options() mechanism determine default settings. Continuous colour scales default values ggplot2.continuous.colour ggplot2.continuous.fill options, binned colour scales default values ggplot2.binned.colour ggplot2.binned.fill options. option values default \"gradient\", means scale functions actually used scale_colour_gradient()/scale_fill_gradient() continuous scales scale_colour_steps()/scale_fill_steps() binned scales. Alternative option values \"viridis\" different scale function. See description type argument details. Note binned colour scales use settings ggplot2.continuous.colour ggplot2.continuous.fill fallback, respectively, ggplot2.binned.colour ggplot2.binned.fill set. scale functions meant provide simple defaults. want manually set colors scale, consider using scale_colour_gradient() scale_colour_steps().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"color-blindness","dir":"Reference","previous_headings":"","what":"Color Blindness","title":"Continuous and binned colour scales — scale_colour_continuous","text":"Many color palettes derived RGB combinations (like \"rainbow\" color palette) suitable support viewers, especially color vision deficiencies. Using viridis type, perceptually uniform colour black--white display easy option ensure good perceptive properties visualizations. colorspace package offers functionalities generate color palettes good perceptive properties, analyse given color palette, like emulating color blindness, modify given color palette better perceptivity. information color vision deficiencies suitable color choices see paper colorspace package references therein.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Continuous and binned colour scales — scale_colour_continuous","text":"","code":"v <- ggplot(faithfuld, aes(waiting, eruptions, fill = density)) + geom_tile() v v + scale_fill_continuous(type = \"gradient\") v + scale_fill_continuous(type = \"viridis\") # The above are equivalent to v + scale_fill_gradient() v + scale_fill_viridis_c() # To make a binned version of this plot v + scale_fill_binned(type = \"viridis\") # Set a different default scale using the options # mechanism tmp <- getOption(\"ggplot2.continuous.fill\") # store current setting options(ggplot2.continuous.fill = scale_fill_distiller) v options(ggplot2.continuous.fill = tmp) # restore previous setting"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":null,"dir":"Reference","previous_headings":"","what":"Discrete colour scales — scale_colour_discrete","title":"Discrete colour scales — scale_colour_discrete","text":"default discrete colour scale. Defaults scale_fill_hue()/scale_fill_brewer() unless type (defaults ggplot2.discrete.fill/ggplot2.discrete.colour options) specified.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discrete colour scales — scale_colour_discrete","text":"","code":"scale_colour_discrete(..., type = getOption(\"ggplot2.discrete.colour\")) scale_fill_discrete(..., type = getOption(\"ggplot2.discrete.fill\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discrete colour scales — scale_colour_discrete","text":"... Additional parameters passed scale type, type One following: character vector color codes. codes used 'manual' color scale long number codes exceeds number data levels (levels codes, scale_colour_hue()/scale_fill_hue() used construct default scale). named vector, color values matched levels based names vectors. Data values match set na.value. list character vectors color codes. minimum length vector exceeds number data levels chosen color scaling. useful want change color palette based number levels. function returns discrete colour/fill scale (e.g., scale_fill_hue(), scale_fill_brewer(), etc).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Discrete colour scales — scale_colour_discrete","text":"","code":"# Template function for creating densities grouped by a variable cty_by_var <- function(var) { ggplot(mpg, aes(cty, colour = factor({{var}}), fill = factor({{var}}))) + geom_density(alpha = 0.2) } # The default, scale_fill_hue(), is not colour-blind safe cty_by_var(class) # (Temporarily) set the default to Okabe-Ito (which is colour-blind safe) okabe <- c(\"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#CC79A7\") withr::with_options( list(ggplot2.discrete.fill = okabe), print(cty_by_var(class)) ) # Define a collection of palettes to alter the default based on number of levels to encode discrete_palettes <- list( c(\"skyblue\", \"orange\"), RColorBrewer::brewer.pal(3, \"Set2\"), RColorBrewer::brewer.pal(6, \"Accent\") ) withr::with_options( list(ggplot2.discrete.fill = discrete_palettes), { # 1st palette is used when there 1-2 levels (e.g., year) print(cty_by_var(year)) # 2nd palette is used when there are 3 levels print(cty_by_var(drv)) # 3rd palette is used when there are 4-6 levels print(cty_by_var(fl)) }) #> Warning: Groups with fewer than two data points have been dropped. #> Warning: no non-missing arguments to max; returning -Inf"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":null,"dir":"Reference","previous_headings":"","what":"Position scales for continuous data (x & y) — scale_continuous","title":"Position scales for continuous data (x & y) — scale_continuous","text":"scale_x_continuous() scale_y_continuous() default scales continuous x y aesthetics. three variants set transform argument commonly used transformations: scale_*_log10(), scale_*_sqrt() scale_*_reverse().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Position scales for continuous data (x & y) — scale_continuous","text":"","code":"scale_x_continuous( name = waiver(), breaks = waiver(), minor_breaks = waiver(), n.breaks = NULL, labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_continuous( name = waiver(), breaks = waiver(), minor_breaks = waiver(), n.breaks = NULL, labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"left\", sec.axis = waiver() ) scale_x_log10(...) scale_y_log10(...) scale_x_reverse(...) scale_y_reverse(...) scale_x_sqrt(...) scale_y_sqrt(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Position scales for continuous data (x & y) — scale_continuous","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. sec.axis sec_axis() used specify secondary axis. ... arguments passed scale_(x|y)_continuous()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Position scales for continuous data (x & y) — scale_continuous","text":"simple manipulation labels limits, may wish use labs() lims() instead.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position scales for continuous data (x & y) — scale_continuous","text":"","code":"p1 <- ggplot(mpg, aes(displ, hwy)) + geom_point() p1 # Manipulating the default position scales lets you: # * change the axis labels p1 + scale_x_continuous(\"Engine displacement (L)\") + scale_y_continuous(\"Highway MPG\") # You can also use the short-cut labs(). # Use NULL to suppress axis labels p1 + labs(x = NULL, y = NULL) # * modify the axis limits p1 + scale_x_continuous(limits = c(2, 6)) #> Warning: Removed 27 rows containing missing values or values outside the scale #> range (`geom_point()`). p1 + scale_x_continuous(limits = c(0, 10)) # you can also use the short hand functions `xlim()` and `ylim()` p1 + xlim(2, 6) #> Warning: Removed 27 rows containing missing values or values outside the scale #> range (`geom_point()`). # * choose where the ticks appear p1 + scale_x_continuous(breaks = c(2, 4, 6)) # * choose your own labels p1 + scale_x_continuous( breaks = c(2, 4, 6), label = c(\"two\", \"four\", \"six\") ) # Typically you'll pass a function to the `labels` argument. # Some common formats are built into the scales package: set.seed(1) df <- data.frame( x = rnorm(10) * 100000, y = seq(0, 1, length.out = 10) ) p2 <- ggplot(df, aes(x, y)) + geom_point() p2 + scale_y_continuous(labels = scales::label_percent()) p2 + scale_y_continuous(labels = scales::label_dollar()) p2 + scale_x_continuous(labels = scales::label_comma()) # You can also override the default linear mapping by using a # transformation. There are three shortcuts: p1 + scale_y_log10() p1 + scale_y_sqrt() p1 + scale_y_reverse() # Or you can supply a transformation in the `trans` argument: p1 + scale_y_continuous(transform = scales::transform_reciprocal()) # You can also create your own. See ?scales::new_transform"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":null,"dir":"Reference","previous_headings":"","what":"Position scales for date/time data — scale_date","title":"Position scales for date/time data — scale_date","text":"default scales three date/time class. usually added automatically. override manually, use scale_*_date dates (class Date), scale_*_datetime datetimes (class POSIXct), scale_*_time times (class hms).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Position scales for date/time data — scale_date","text":"","code":"scale_x_date( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_date( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"left\", sec.axis = waiver() ) scale_x_datetime( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), timezone = NULL, limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_datetime( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), timezone = NULL, limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"left\", sec.axis = waiver() ) scale_x_time( name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_time( name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, guide = waiver(), position = \"left\", sec.axis = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Position scales for date/time data — scale_date","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() breaks specified date_breaks Date/POSIXct vector giving positions breaks function takes limits input returns breaks output date_breaks string giving distance breaks like \"2 weeks\", \"10 years\". breaks date_breaks specified, date_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. date_labels string giving formatting specification labels. Codes defined strftime(). labels date_labels specified, date_labels wins. minor_breaks One : NULL breaks waiver() breaks specified date_minor_breaks Date/POSIXct vector giving positions minor breaks function takes limits input returns minor breaks output date_minor_breaks string giving distance minor breaks like \"2 weeks\", \"10 years\". minor_breaks date_minor_breaks specified, date_minor_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. sec.axis sec_axis() used specify secondary axis. timezone timezone use display axes. default (NULL) uses timezone encoded data. na.value Missing values replaced value.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position scales for date/time data — scale_date","text":"","code":"last_month <- Sys.Date() - 0:29 set.seed(1) df <- data.frame( date = last_month, price = runif(30) ) base <- ggplot(df, aes(date, price)) + geom_line() # The date scale will attempt to pick sensible defaults for # major and minor tick marks. Override with date_breaks, date_labels # date_minor_breaks arguments. base + scale_x_date(date_labels = \"%b %d\") base + scale_x_date(date_breaks = \"1 week\", date_labels = \"%W\") base + scale_x_date(date_minor_breaks = \"1 day\") # Set limits base + scale_x_date(limits = c(Sys.Date() - 7, NA)) #> Warning: Removed 22 rows containing missing values or values outside the scale #> range (`geom_line()`)."},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":null,"dir":"Reference","previous_headings":"","what":"Position scales for discrete data — scale_x_discrete","title":"Position scales for discrete data — scale_x_discrete","text":"scale_x_discrete() scale_y_discrete() used set values discrete x y scale aesthetics. simple manipulation scale labels limits, may wish use labs() lims() instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Position scales for discrete data — scale_x_discrete","text":"","code":"scale_x_discrete( name = waiver(), ..., palette = seq_len, expand = waiver(), guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_discrete( name = waiver(), ..., palette = seq_len, expand = waiver(), guide = waiver(), position = \"left\", sec.axis = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Position scales for discrete data — scale_x_discrete","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. na.value na.translate = TRUE, aesthetic value missing values displayed ? apply position scales NA always placed far right. aesthetics names aesthetics scale works . minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. call call used construct scale reporting messages. super super class use constructed scale palette palette function called single integer argument (number levels scale) returns numerical values take. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. sec.axis dup_axis() used specify secondary axis.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Position scales for discrete data — scale_x_discrete","text":"can use continuous positions even discrete position scale - allows (e.g.) place labels bars bar chart. Continuous positions numeric values starting one first level, increasing one level (.e. labels placed integer positions). allows jittering work.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position scales for discrete data — scale_x_discrete","text":"","code":"ggplot(diamonds, aes(cut)) + geom_bar() # \\donttest{ # The discrete position scale is added automatically whenever you # have a discrete position. (d <- ggplot(subset(diamonds, carat > 1), aes(cut, clarity)) + geom_jitter()) d + scale_x_discrete(\"Cut\") d + scale_x_discrete( \"Cut\", labels = c( \"Fair\" = \"F\", \"Good\" = \"G\", \"Very Good\" = \"VG\", \"Perfect\" = \"P\", \"Ideal\" = \"I\" ) ) # Use limits to adjust the which levels (and in what order) # are displayed d + scale_x_discrete(limits = c(\"Fair\",\"Ideal\")) #> Warning: Removed 11189 rows containing missing values or values outside the scale #> range (`geom_point()`). # you can also use the short hand functions xlim and ylim d + xlim(\"Fair\",\"Ideal\", \"Good\") #> Warning: Removed 9610 rows containing missing values or values outside the scale #> range (`geom_point()`). d + ylim(\"I1\", \"IF\") #> Warning: Removed 16770 rows containing missing values or values outside the scale #> range (`geom_point()`). # See ?reorder to reorder based on the values of another variable ggplot(mpg, aes(manufacturer, cty)) + geom_point() ggplot(mpg, aes(reorder(manufacturer, cty), cty)) + geom_point() ggplot(mpg, aes(reorder(manufacturer, displ), cty)) + geom_point() # Use abbreviate as a formatter to reduce long names ggplot(mpg, aes(reorder(manufacturer, displ), cty)) + geom_point() + scale_x_discrete(labels = abbreviate) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":null,"dir":"Reference","previous_headings":"","what":"Gradient colour scales — scale_colour_gradient","title":"Gradient colour scales — scale_colour_gradient","text":"scale_*_gradient creates two colour gradient (low-high), scale_*_gradient2 creates diverging colour gradient (low-mid-high), scale_*_gradientn creates n-colour gradient. binned variants scales, see color steps scales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Gradient colour scales — scale_colour_gradient","text":"","code":"scale_colour_gradient( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_gradient( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_gradient2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_gradient2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_gradientn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\", colors ) scale_fill_gradientn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\", colors )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Gradient colour scales — scale_colour_gradient","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed continuous_scale scale_name name scale used error messages associated scale. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. trans Deprecated favour transform. call call used construct scale reporting messages. super super class use constructed scale low, high Colours low high ends gradient. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Colour use missing values guide Type legend. Use \"colourbar\" continuous colour bar, \"legend\" discrete colour legend. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). mid colour mid point midpoint midpoint (data value) diverging scale. Defaults 0. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). colours, colors Vector colours use n-colour gradient. values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Gradient colour scales — scale_colour_gradient","text":"Default colours generated munsell mnsl(c(\"2.5PB 2/4\", \"2.5PB 7/10\")). Generally, continuous colour scales want keep hue constant, vary chroma luminance. munsell package makes easy using Munsell colour system.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Gradient colour scales — scale_colour_gradient","text":"","code":"set.seed(1) df <- data.frame( x = runif(100), y = runif(100), z1 = rnorm(100), z2 = abs(rnorm(100)) ) df_na <- data.frame( value = seq(1, 20), x = runif(20), y = runif(20), z1 = c(rep(NA, 10), rnorm(10)) ) # Default colour scale colours from light blue to dark blue ggplot(df, aes(x, y)) + geom_point(aes(colour = z2)) # For diverging colour scales use gradient2 ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradient2() # Use your own colour scale with gradientn ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradientn(colours = terrain.colors(10)) # The gradientn scale can be centered by using a rescaler ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradientn( colours = c(\"blue\", \"dodgerblue\", \"white\", \"orange\", \"red\"), rescaler = ~ scales::rescale_mid(.x, mid = 0) ) # Equivalent fill scales do the same job for the fill aesthetic ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) + scale_fill_gradientn(colours = terrain.colors(10)) # Adjust colour choices with low and high ggplot(df, aes(x, y)) + geom_point(aes(colour = z2)) + scale_colour_gradient(low = \"white\", high = \"black\") # Avoid red-green colour contrasts because ~10% of men have difficulty # seeing them # Use `na.value = NA` to hide missing values but keep the original axis range ggplot(df_na, aes(x = value, y)) + geom_bar(aes(fill = z1), stat = \"identity\") + scale_fill_gradient(low = \"yellow\", high = \"red\", na.value = NA) ggplot(df_na, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradient(low = \"yellow\", high = \"red\", na.value = NA) #> Warning: Removed 10 rows containing missing values or values outside the scale #> range (`geom_point()`)."},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":null,"dir":"Reference","previous_headings":"","what":"Sequential grey colour scales — scale_colour_grey","title":"Sequential grey colour scales — scale_colour_grey","text":"Based gray.colors(). black white equivalent scale_colour_gradient().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Sequential grey colour scales — scale_colour_grey","text":"","code":"scale_colour_grey( name = waiver(), ..., start = 0.2, end = 0.8, na.value = \"red\", aesthetics = \"colour\" ) scale_fill_grey( name = waiver(), ..., start = 0.2, end = 0.8, na.value = \"red\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Sequential grey colour scales — scale_colour_grey","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale start grey value low end palette end grey value high end palette na.value Colour use missing values aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Sequential grey colour scales — scale_colour_grey","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl))) p + scale_colour_grey() p + scale_colour_grey(end = 0) # You may want to turn off the pale grey background with this scale p + scale_colour_grey() + theme_bw() # Colour of missing values is controlled with na.value: miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) + scale_colour_grey() ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) + scale_colour_grey(na.value = \"green\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":null,"dir":"Reference","previous_headings":"","what":"Evenly spaced colours for discrete data — scale_colour_hue","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"Maps level evenly spaced hue colour wheel. generate colour-blind safe palettes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"","code":"scale_colour_hue( name = waiver(), ..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = \"grey50\", aesthetics = \"colour\" ) scale_fill_hue( name = waiver(), ..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = \"grey50\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale h range hues use, [0, 360] c chroma (intensity colour), maximum value varies depending combination hue luminance. l luminance (lightness), [0, 100] h.start hue start direction direction travel around colour wheel, 1 = clockwise, -1 = counter-clockwise na.value Colour use missing values aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"","code":"# \\donttest{ set.seed(596) dsamp <- diamonds[sample(nrow(diamonds), 1000), ] (d <- ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity))) # Change scale label d + scale_colour_hue() d + scale_colour_hue(\"clarity\") d + scale_colour_hue(expression(clarity[beta])) # Adjust luminosity and chroma d + scale_colour_hue(l = 40, c = 30) d + scale_colour_hue(l = 70, c = 30) d + scale_colour_hue(l = 70, c = 150) d + scale_colour_hue(l = 80, c = 150) # Change range of hues used d + scale_colour_hue(h = c(0, 90)) d + scale_colour_hue(h = c(90, 180)) d + scale_colour_hue(h = c(180, 270)) d + scale_colour_hue(h = c(270, 360)) # Vary opacity # (only works with pdf, quartz and cairo devices) d <- ggplot(dsamp, aes(carat, price, colour = clarity)) d + geom_point(alpha = 0.9) d + geom_point(alpha = 0.5) d + geom_point(alpha = 0.2) # Colour of missing values is controlled with na.value: miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) + scale_colour_hue(na.value = \"black\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":null,"dir":"Reference","previous_headings":"","what":"Use values without scaling — scale_identity","title":"Use values without scaling — scale_identity","text":"Use set scales data already scaled, .e. already represents aesthetic values ggplot2 can handle directly. scales produce legend unless also supply breaks, labels, type guide want.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Use values without scaling — scale_identity","text":"","code":"scale_colour_identity( name = waiver(), ..., guide = \"none\", aesthetics = \"colour\" ) scale_fill_identity(name = waiver(), ..., guide = \"none\", aesthetics = \"fill\") scale_shape_identity(name = waiver(), ..., guide = \"none\") scale_linetype_identity(name = waiver(), ..., guide = \"none\") scale_linewidth_identity(name = waiver(), ..., guide = \"none\") scale_alpha_identity(name = waiver(), ..., guide = \"none\") scale_size_identity(name = waiver(), ..., guide = \"none\") scale_discrete_identity(aesthetics, name = waiver(), ..., guide = \"none\") scale_continuous_identity(aesthetics, name = waiver(), ..., guide = \"none\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Use values without scaling — scale_identity","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed discrete_scale() continuous_scale() guide Guide use scale. Defaults \"none\". aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Use values without scaling — scale_identity","text":"functions scale_colour_identity(), scale_fill_identity(), scale_size_identity(), etc. work aesthetics specified scale name: colour, fill, size, etc. However, functions scale_colour_identity() scale_fill_identity() also optional aesthetics argument can used define colour fill aesthetic mappings via single function call. functions scale_discrete_identity() scale_continuous_identity() generic scales can work aesthetic set aesthetics provided via aesthetics argument.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Use values without scaling — scale_identity","text":"","code":"ggplot(luv_colours, aes(u, v)) + geom_point(aes(colour = col), size = 3) + scale_color_identity() + coord_fixed() df <- data.frame( x = 1:4, y = 1:4, colour = c(\"red\", \"green\", \"blue\", \"yellow\") ) ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) + scale_fill_identity() # To get a legend guide, specify guide = \"legend\" ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) + scale_fill_identity(guide = \"legend\") # But you'll typically also need to supply breaks and labels: ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) + scale_fill_identity(\"trt\", labels = letters[1:4], breaks = df$colour, guide = \"legend\") # cyl scaled to appropriate size ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(size = cyl)) # cyl used as point size ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(size = cyl)) + scale_size_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":null,"dir":"Reference","previous_headings":"","what":"Scale for line patterns — scale_linetype","title":"Scale for line patterns — scale_linetype","text":"Default line types based set supplied Richard Pearson, University Manchester. Continuous values can mapped line types unless scale_linetype_binned() used. Still, linetypes inherent order, use advised.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scale for line patterns — scale_linetype","text":"","code":"scale_linetype(name = waiver(), ..., na.value = \"blank\") scale_linetype_binned(name = waiver(), ..., na.value = \"blank\") scale_linetype_continuous(...) scale_linetype_discrete(name = waiver(), ..., na.value = \"blank\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scale for line patterns — scale_linetype","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. aesthetics names aesthetics scale works . minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale na.value linetype use NA values.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scale for line patterns — scale_linetype","text":"","code":"base <- ggplot(economics_long, aes(date, value01)) base + geom_line(aes(group = variable)) base + geom_line(aes(linetype = variable)) # See scale_manual for more flexibility # Common line types ---------------------------- df_lines <- data.frame( linetype = factor( 1:4, labels = c(\"solid\", \"longdash\", \"dashed\", \"dotted\") ) ) ggplot(df_lines) + geom_hline(aes(linetype = linetype, yintercept = 0), linewidth = 2) + scale_linetype_identity() + facet_grid(linetype ~ .) + theme_void(20)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":null,"dir":"Reference","previous_headings":"","what":"Scales for line width — scale_linewidth","title":"Scales for line width — scale_linewidth","text":"scale_linewidth scales width lines polygon strokes. Due historical reasons, also possible control size aesthetic, using linewidth encourage clearly differentiate area aesthetics stroke width aesthetics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scales for line width — scale_linewidth","text":"","code":"scale_linewidth( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = \"identity\", trans = deprecated(), guide = \"legend\" ) scale_linewidth_binned( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), n.breaks = NULL, nice.breaks = TRUE, transform = \"identity\", trans = deprecated(), guide = \"bins\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scales for line width — scale_linewidth","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). range numeric vector length 2 specifies minimum maximum size plotting symbol transformation. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scales for line width — scale_linewidth","text":"","code":"p <- ggplot(economics, aes(date, unemploy, linewidth = uempmed)) + geom_line(lineend = \"round\") p p + scale_linewidth(\"Duration of\\nunemployment\") p + scale_linewidth(range = c(0, 4)) # Binning can sometimes make it easier to match the scaled data to the legend p + scale_linewidth_binned()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":null,"dir":"Reference","previous_headings":"","what":"Create your own discrete scale — scale_manual","title":"Create your own discrete scale — scale_manual","text":"functions allow specify set mappings levels data aesthetic values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create your own discrete scale — scale_manual","text":"","code":"scale_colour_manual( ..., values, aesthetics = \"colour\", breaks = waiver(), na.value = \"grey50\" ) scale_fill_manual( ..., values, aesthetics = \"fill\", breaks = waiver(), na.value = \"grey50\" ) scale_size_manual(..., values, breaks = waiver(), na.value = NA) scale_shape_manual(..., values, breaks = waiver(), na.value = NA) scale_linetype_manual(..., values, breaks = waiver(), na.value = \"blank\") scale_linewidth_manual(..., values, breaks = waiver(), na.value = NA) scale_alpha_manual(..., values, breaks = waiver(), na.value = NA) scale_discrete_manual(aesthetics, ..., values, breaks = waiver())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create your own discrete scale — scale_manual","text":"... Arguments passed discrete_scale limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale values set aesthetic values map data values . values matched order (usually alphabetical) limits scale, breaks provided. named vector, values matched based names instead. Data values match given na.value. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output na.value aesthetic value use missing (NA) values","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create your own discrete scale — scale_manual","text":"functions scale_colour_manual(), scale_fill_manual(), scale_size_manual(), etc. work aesthetics specified scale name: colour, fill, size, etc. However, functions scale_colour_manual() scale_fill_manual() also optional aesthetics argument can used define colour fill aesthetic mappings via single function call (see examples). function scale_discrete_manual() generic scale can work aesthetic set aesthetics provided via aesthetics argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"color-blindness","dir":"Reference","previous_headings":"","what":"Color Blindness","title":"Create your own discrete scale — scale_manual","text":"Many color palettes derived RGB combinations (like \"rainbow\" color palette) suitable support viewers, especially color vision deficiencies. Using viridis type, perceptually uniform colour black--white display easy option ensure good perceptive properties visualizations. colorspace package offers functionalities generate color palettes good perceptive properties, analyse given color palette, like emulating color blindness, modify given color palette better perceptivity. information color vision deficiencies suitable color choices see paper colorspace package references therein.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create your own discrete scale — scale_manual","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl))) p + scale_colour_manual(values = c(\"red\", \"blue\", \"green\")) # It's recommended to use a named vector cols <- c(\"8\" = \"red\", \"4\" = \"blue\", \"6\" = \"darkgreen\", \"10\" = \"orange\") p + scale_colour_manual(values = cols) # You can set color and fill aesthetics at the same time ggplot( mtcars, aes(mpg, wt, colour = factor(cyl), fill = factor(cyl)) ) + geom_point(shape = 21, alpha = 0.5, size = 2) + scale_colour_manual( values = cols, aesthetics = c(\"colour\", \"fill\") ) # As with other scales you can use breaks to control the appearance # of the legend. p + scale_colour_manual(values = cols) p + scale_colour_manual( values = cols, breaks = c(\"4\", \"6\", \"8\"), labels = c(\"four\", \"six\", \"eight\") ) # And limits to control the possible values of the scale p + scale_colour_manual(values = cols, limits = c(\"4\", \"8\")) p + scale_colour_manual(values = cols, limits = c(\"4\", \"6\", \"8\", \"10\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":null,"dir":"Reference","previous_headings":"","what":"Scales for shapes, aka glyphs — scale_shape","title":"Scales for shapes, aka glyphs — scale_shape","text":"scale_shape() maps discrete variables six easily discernible shapes. six levels, get warning message, seventh subsequent levels appear plot. Use scale_shape_manual() supply values. can map continuous variable shape unless scale_shape_binned() used. Still, shape inherent order, use advised.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scales for shapes, aka glyphs — scale_shape","text":"","code":"scale_shape(name = waiver(), ..., solid = TRUE) scale_shape_binned(name = waiver(), ..., solid = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scales for shapes, aka glyphs — scale_shape","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. na.value na.translate = TRUE, aesthetic value missing values displayed ? apply position scales NA always placed far right. aesthetics names aesthetics scale works . minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale solid shapes solid, TRUE, hollow, FALSE?","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scales for shapes, aka glyphs — scale_shape","text":"","code":"set.seed(596) dsmall <- diamonds[sample(nrow(diamonds), 100), ] (d <- ggplot(dsmall, aes(carat, price)) + geom_point(aes(shape = cut))) #> Warning: Using shapes for an ordinal variable is not advised d + scale_shape(solid = TRUE) # the default d + scale_shape(solid = FALSE) d + scale_shape(name = \"Cut of diamond\") # To change order of levels, change order of # underlying factor levels(dsmall$cut) <- c(\"Fair\", \"Good\", \"Very Good\", \"Premium\", \"Ideal\") # Need to recreate plot to pick up new data ggplot(dsmall, aes(price, carat)) + geom_point(aes(shape = cut)) #> Warning: Using shapes for an ordinal variable is not advised # Show a list of available shapes 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()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":null,"dir":"Reference","previous_headings":"","what":"Scales for area or radius — scale_size","title":"Scales for area or radius — scale_size","text":"scale_size() scales area, scale_radius() scales radius. size aesthetic commonly used points text, humans perceive area points (radius), provides optimal perception. scale_size_area() ensures value 0 mapped size 0. scale_size_binned() binned version scale_size() scales area (ensure 0 equals area zero). binned equivalent scale_size_area() use scale_size_binned_area().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scales for area or radius — scale_size","text":"","code":"scale_size( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = \"identity\", trans = deprecated(), guide = \"legend\" ) scale_radius( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = \"identity\", trans = deprecated(), guide = \"legend\" ) scale_size_binned( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), n.breaks = NULL, nice.breaks = TRUE, transform = \"identity\", trans = deprecated(), guide = \"bins\" ) scale_size_area(name = waiver(), ..., max_size = 6) scale_size_binned_area(name = waiver(), ..., max_size = 6)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scales for area or radius — scale_size","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). range numeric vector length 2 specifies minimum maximum size plotting symbol transformation. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. ... Arguments passed continuous_scale minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. call call used construct scale reporting messages. super super class use constructed scale max_size Size largest points.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Scales for area or radius — scale_size","text":"Historically size aesthetic used two different things: Scaling size object (like points glyphs) scaling width lines. ggplot2 3.4.0 latter moved linewidth aesthetic. backwards compatibility using size still possible, highly advised switch new linewidth aesthetic cases.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scales for area or radius — scale_size","text":"","code":"p <- ggplot(mpg, aes(displ, hwy, size = hwy)) + geom_point() p p + scale_size(\"Highway mpg\") p + scale_size(range = c(0, 10)) # If you want zero value to have zero size, use scale_size_area: p + scale_size_area() # Binning can sometimes make it easier to match the scaled data to the legend p + scale_size_binned() # This is most useful when size is a count ggplot(mpg, aes(class, cyl)) + geom_count() + scale_size_area() # If you want to map size to radius (usually bad idea), use scale_radius p + scale_radius()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":null,"dir":"Reference","previous_headings":"","what":"Binned gradient colour scales — scale_colour_steps","title":"Binned gradient colour scales — scale_colour_steps","text":"scale_*_steps creates two colour binned gradient (low-high), scale_*_steps2 creates diverging binned colour gradient (low-mid-high), scale_*_stepsn creates n-colour binned gradient. scales binned variants gradient scale family works way.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Binned gradient colour scales — scale_colour_steps","text":"","code":"scale_colour_steps( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_colour_steps2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_colour_stepsn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\", colors ) scale_fill_steps( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\" ) scale_fill_steps2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"coloursteps\", aesthetics = \"fill\" ) scale_fill_stepsn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\", colors )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Binned gradient colour scales — scale_colour_steps","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed binned_scale n.breaks number break points create breaks given directly. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::squish()) squishes bounds values range. scales::censor replacing bounds values NA. scales::squish_infinite() squishing infinite values range. right intervals closed right (TRUE, default) intervals closed left (FALSE)? 'Closed right' means values break positions part lower bin (open left), whereas part upper bin intervals closed left (open right). show.limits limits scale appear ticks breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). trans Deprecated favour transform. call call used construct scale reporting messages. super super class use constructed scale low, high Colours low high ends gradient. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Colour use missing values guide Type legend. Use \"colourbar\" continuous colour bar, \"legend\" discrete colour legend. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). mid colour mid point midpoint midpoint (data value) diverging scale. Defaults 0. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). colours, colors Vector colours use n-colour gradient. values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Binned gradient colour scales — scale_colour_steps","text":"Default colours generated munsell mnsl(c(\"2.5PB 2/4\", \"2.5PB 7/10\")). Generally, continuous colour scales want keep hue constant, vary chroma luminance. munsell package makes easy using Munsell colour system.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Binned gradient colour scales — scale_colour_steps","text":"","code":"set.seed(1) df <- data.frame( x = runif(100), y = runif(100), z1 = rnorm(100) ) # Use scale_colour_steps for a standard binned gradient ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_steps() # Get a divergent binned scale with the *2 variant ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_steps2() # Define your own colour ramp to extract binned colours from ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_stepsn(colours = terrain.colors(10))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":null,"dir":"Reference","previous_headings":"","what":"Determine default scale type — scale_type","title":"Determine default scale type — scale_type","text":"need define method method want extend ggplot2 handle new types data. simply want pass vector additional aesthetic, return \"identity\".","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Determine default scale type — scale_type","text":"","code":"scale_type(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Determine default scale type — scale_type","text":"x vector","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Determine default scale type — scale_type","text":"character vector scale types. tried turn find default scale. example, scale_type() returns c(\"foo\", \"bar\") vector used colour aesthetic, ggplot2 first look scale_colour_foo scale_colour_bar.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Determine default scale type — scale_type","text":"","code":"scale_type(1:5) #> [1] \"continuous\" scale_type(\"test\") #> [1] \"discrete\" scale_type(Sys.Date()) #> [1] \"date\" \"continuous\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":null,"dir":"Reference","previous_headings":"","what":"Viridis colour scales from viridisLite — scale_colour_viridis_d","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"viridis scales provide colour maps perceptually uniform colour black--white. also designed perceived viewers common forms colour blindness. See also https://bids.github.io/colormap/.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"","code":"scale_colour_viridis_d( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", aesthetics = \"colour\" ) scale_fill_viridis_d( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", aesthetics = \"fill\" ) scale_colour_viridis_c( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_viridis_c( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_viridis_b( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_fill_viridis_b( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed discrete_scale(), continuous_scale(), binned_scale() control name, limits, breaks, labels forth. alpha alpha transparency, number [0,1], see argument alpha hsv. begin, end (corrected) hue [0,1] color map begins ends. direction Sets order colors scale. 1, default, colors ordered darkest lightest. -1, order colors reversed. option character string indicating color map option use. Eight options available: \"magma\" (\"\") \"inferno\" (\"B\") \"plasma\" (\"C\") \"viridis\" (\"D\") \"cividis\" (\"E\") \"rocket\" (\"F\") \"mako\" (\"G\") \"turbo\" (\"H\") aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Missing values replaced value. guide function used create guide name. See guides() information.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"","code":"# viridis is the default colour/fill scale for ordered factors set.seed(596) dsamp <- diamonds[sample(nrow(diamonds), 1000), ] ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity)) # Use viridis_d with discrete data txsamp <- subset(txhousing, city %in% c(\"Houston\", \"Fort Worth\", \"San Antonio\", \"Dallas\", \"Austin\")) (d <- ggplot(data = txsamp, aes(x = sales, y = median)) + geom_point(aes(colour = city))) d + scale_colour_viridis_d() # Change scale label d + scale_colour_viridis_d(\"City\\nCenter\") # Select palette to use, see ?scales::pal_viridis for more details d + scale_colour_viridis_d(option = \"plasma\") d + scale_colour_viridis_d(option = \"inferno\") # scale_fill_viridis_d works just the same as # scale_colour_viridis_d but for fill colours p <- ggplot(txsamp, aes(x = median, fill = city)) + geom_histogram(position = \"dodge\", binwidth = 15000) p + scale_fill_viridis_d() # the order of colour can be reversed p + scale_fill_viridis_d(direction = -1) # Use viridis_c with continuous data (v <- ggplot(faithfuld) + geom_tile(aes(waiting, eruptions, fill = density))) v + scale_fill_viridis_c() v + scale_fill_viridis_c(option = \"plasma\") # Use viridis_b to bin continuous data before mapping v + scale_fill_viridis_b()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":null,"dir":"Reference","previous_headings":"","what":"Vector field of seal movements — seals","title":"Vector field of seal movements — seals","text":"vector field produced data described Brillinger, D.R., Preisler, H.K., Ager, .. Kie, J.G. \"exploratory data analysis (EDA) paths moving animals\". J. Statistical Planning Inference 122 (2004), 43-63, using methods Brillinger, D.R., \"Learning potential function trajectory\", Signal Processing Letters. December (2007).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Vector field of seal movements — seals","text":"","code":"seals"},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Vector field of seal movements — seals","text":"data frame 1155 rows 4 variables","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Vector field of seal movements — seals","text":"https://www.stat.berkeley.edu/~brill/Papers/jspifinal.pdf","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":null,"dir":"Reference","previous_headings":"","what":"Specify a secondary axis — sec_axis","title":"Specify a secondary axis — sec_axis","text":"function used conjunction position scale create secondary axis, positioned opposite primary axis. secondary axes must based one--one transformation primary axes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Specify a secondary axis — sec_axis","text":"","code":"sec_axis( transform = NULL, name = waiver(), breaks = waiver(), labels = waiver(), guide = waiver(), trans = deprecated() ) dup_axis( transform = identity, name = derive(), breaks = derive(), labels = derive(), guide = derive(), trans = deprecated() ) derive()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Specify a secondary axis — sec_axis","text":"transform formula function strictly monotonic transformation name name secondary axis breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) function takes breaks input returns labels output guide position guide used render axis plot. Usually guide_axis(). trans","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Specify a secondary axis — sec_axis","text":"sec_axis() used create specifications secondary axis. Except trans argument arguments can set derive() result secondary axis inheriting settings primary axis. dup_axis() provide shorthand creating secondary axis duplication primary axis, effectively mirroring primary axis. v3.1, date datetime scales limited secondary axis capabilities. Unlike continuous scales, secondary axis transformations date datetime scales must respect primary POSIX data structure. means may transformed via addition subtraction, e.g. ~ . + hms::hms(days = 8), ~ . - 8*60*60. Nonlinear transformations return error. produce time-since-event secondary axis context, users may consider adapting secondary axis labels.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Specify a secondary axis — sec_axis","text":"","code":"p <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() # Create a simple secondary axis p + scale_y_continuous(sec.axis = sec_axis(~ . + 10)) # Inherit the name from the primary axis p + scale_y_continuous(\"Miles/gallon\", sec.axis = sec_axis(~ . + 10, name = derive())) # Duplicate the primary axis p + scale_y_continuous(sec.axis = dup_axis()) # You can pass in a formula as a shorthand p + scale_y_continuous(sec.axis = ~ .^2) # Secondary axes work for date and datetime scales too: df <- data.frame( dx = seq( as.POSIXct(\"2012-02-29 12:00:00\", tz = \"UTC\"), length.out = 10, by = \"4 hour\" ), price = seq(20, 200000, length.out = 10) ) # This may useful for labelling different time scales in the same plot ggplot(df, aes(x = dx, y = price)) + geom_line() + scale_x_datetime( \"Date\", date_labels = \"%b %d\", date_breaks = \"6 hour\", sec.axis = dup_axis( name = \"Time of Day\", labels = scales::label_time(\"%I %p\") ) ) # or to transform axes for different timezones ggplot(df, aes(x = dx, y = price)) + geom_line() + scale_x_datetime(\" GMT\", date_labels = \"%b %d %I %p\", sec.axis = sec_axis( ~ . + 8 * 3600, name = \"GMT+8\", labels = scales::label_time(\"%b %d %I %p\") ) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/set_last_plot.html","id":null,"dir":"Reference","previous_headings":"","what":"Set the last plot to be fetched by lastplot() — set_last_plot","title":"Set the last plot to be fetched by lastplot() — set_last_plot","text":"Set last plot fetched lastplot()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/set_last_plot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set the last plot to be fetched by lastplot() — set_last_plot","text":"","code":"set_last_plot(value)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":null,"dir":"Reference","previous_headings":"","what":"Transform spatial position data — sf_transform_xy","title":"Transform spatial position data — sf_transform_xy","text":"Helper function can transform spatial position data (pairs x, y values) among coordinate systems. implemented thin wrapper around sf::sf_project().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Transform spatial position data — sf_transform_xy","text":"","code":"sf_transform_xy(data, target_crs, source_crs, authority_compliant = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Transform spatial position data — sf_transform_xy","text":"data Data frame list containing numerical columns x y. target_crs, source_crs Target source coordinate reference systems. NULL NA, data transformed. authority_compliant logical; TRUE means handle axis order authority compliant (e.g. EPSG:4326 implying x = lat, y = lon), FALSE means use visualisation order (.e. always x = lon, y = lat). Default FALSE.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Transform spatial position data — sf_transform_xy","text":"copy input data x y replaced transformed values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Transform spatial position data — sf_transform_xy","text":"","code":"if (requireNamespace(\"sf\", quietly = TRUE)) { # location of cities in NC by long (x) and lat (y) data <- data.frame( city = c(\"Charlotte\", \"Raleigh\", \"Greensboro\"), x = c(-80.843, -78.639, -79.792), y = c(35.227, 35.772, 36.073) ) # transform to projected coordinates data_proj <- sf_transform_xy(data, 3347, 4326) data_proj # transform back sf_transform_xy(data_proj, 4326, 3347) } #> city x y #> 1 Charlotte -80.843 35.227 #> 2 Raleigh -78.639 35.772 #> 3 Greensboro -79.792 36.073"},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":null,"dir":"Reference","previous_headings":"","what":"Used in examples to illustrate when errors should occur. — should_stop","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"Used examples illustrate errors occur.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"","code":"should_stop(expr)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"expr code evaluate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"","code":"should_stop(stop(\"Hi!\")) should_stop(should_stop(\"Hi!\")) #> [1] \"Hi!\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":null,"dir":"Reference","previous_headings":"","what":"Standardise aesthetic names — standardise_aes_names","title":"Standardise aesthetic names — standardise_aes_names","text":"function standardises aesthetic names converting color colour (also substrings, e.g. point_color point_colour) translating old style R names ggplot names (eg. pch shape, cex size).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Standardise aesthetic names — standardise_aes_names","text":"","code":"standardise_aes_names(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Standardise aesthetic names — standardise_aes_names","text":"x Character vector aesthetics names, c(\"colour\", \"size\", \"shape\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Standardise aesthetic names — standardise_aes_names","text":"Character vector standardised names.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute empirical cumulative distribution — stat_ecdf","title":"Compute empirical cumulative distribution — stat_ecdf","text":"empirical cumulative distribution function (ECDF) provides alternative visualisation distribution. Compared visualisations rely density (like geom_histogram()), ECDF require tuning parameters handles continuous categorical variables. downside requires training accurately interpret, underlying visual tasks somewhat challenging.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute empirical cumulative distribution — stat_ecdf","text":"","code":"stat_ecdf( mapping = NULL, data = NULL, geom = \"step\", position = \"identity\", ..., n = NULL, pad = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute empirical cumulative distribution — stat_ecdf","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. n NULL, interpolate. NULL, number points interpolate . pad TRUE, pad ecdf additional points (-Inf, 0) (Inf, 1) na.rm FALSE (default), removes missing values warning. TRUE silently removes missing values. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Compute empirical cumulative distribution — stat_ecdf","text":"statistic relies aesthetics assignment guess variable use input use output. Either x y must provided one must unused. ECDF calculated given aesthetic output unused one. weight aesthetic provided, weighted ECDF computed. case, ECDF incremented weight / sum(weight) instead 1 / length(x) observation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Compute empirical cumulative distribution — stat_ecdf","text":"stat_ecdf() understands following aesthetics (required aesthetics bold): x y group weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Compute empirical cumulative distribution — stat_ecdf","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(ecdf) Cumulative density corresponding x. after_stat(y) backward compatibility.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Compute empirical cumulative distribution — stat_ecdf","text":"weight calculation, weights individual observations (supplied), longer available.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute empirical cumulative distribution — stat_ecdf","text":"","code":"set.seed(1) df <- data.frame( x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)), g = gl(2, 100) ) ggplot(df, aes(x)) + stat_ecdf(geom = \"step\") # Don't go to positive/negative infinity ggplot(df, aes(x)) + stat_ecdf(geom = \"step\", pad = FALSE) # Multiple ECDFs ggplot(df, aes(x, colour = g)) + stat_ecdf() # Using weighted eCDF weighted <- data.frame(x = 1:10, weights = c(1:5, 5:1)) plain <- data.frame(x = rep(weighted$x, weighted$weights)) ggplot(plain, aes(x)) + stat_ecdf(linewidth = 1) + stat_ecdf( aes(weight = weights), data = weighted, colour = \"green\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute normal data ellipses — stat_ellipse","title":"Compute normal data ellipses — stat_ellipse","text":"method calculating ellipses modified car::dataEllipse (Fox Weisberg 2011, Friendly Monette 2013)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute normal data ellipses — stat_ellipse","text":"","code":"stat_ellipse( mapping = NULL, data = NULL, geom = \"path\", position = \"identity\", ..., type = \"t\", level = 0.95, segments = 51, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute normal data ellipses — stat_ellipse","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. type type ellipse. default \"t\" assumes multivariate t-distribution, \"norm\" assumes multivariate normal distribution. \"euclid\" draws circle radius equal level, representing euclidean distance center. ellipse probably appear circular unless coord_fixed() applied. level level draw ellipse, , type=\"euclid\", radius circle drawn. segments number segments used drawing ellipse. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Compute normal data ellipses — stat_ellipse","text":"John Fox Sanford Weisberg (2011). R Companion Applied Regression, Second Edition. Thousand Oaks CA: Sage. URL: https://socialsciences.mcmaster.ca/jfox/Books/Companion/ Michael Friendly. Georges Monette. John Fox. \"Elliptical Insights: Understanding Statistical Methods Elliptical Geometry.\" Statist. Sci. 28 (1) 1 - 39, February 2013. URL: https://projecteuclid.org/journals/statistical-science/volume-28/issue-1/Elliptical-Insights-Understanding-Statistical-Methods--Elliptical-Geometry/10.1214/12-STS402.full","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute normal data ellipses — stat_ellipse","text":"","code":"ggplot(faithful, aes(waiting, eruptions)) + geom_point() + stat_ellipse() ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse() ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse(type = \"norm\", linetype = 2) + stat_ellipse(type = \"t\") ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse(type = \"norm\", linetype = 2) + stat_ellipse(type = \"euclid\", level = 3) + coord_fixed() ggplot(faithful, aes(waiting, eruptions, fill = eruptions > 3)) + stat_ellipse(geom = \"polygon\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":null,"dir":"Reference","previous_headings":"","what":"Leave data as is — stat_identity","title":"Leave data as is — stat_identity","text":"identity statistic leaves data unchanged.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Leave data as is — stat_identity","text":"","code":"stat_identity( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Leave data as is — stat_identity","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Leave data as is — stat_identity","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) p + stat_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract coordinates from 'sf' objects — stat_sf_coordinates","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"stat_sf_coordinates() extracts coordinates 'sf' objects summarises one pair coordinates (x y) per geometry. convenient draw sf object geoms like text labels (geom_sf_text() geom_sf_label() relies ).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"","code":"stat_sf_coordinates( mapping = aes(), data = NULL, geom = \"point\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, fun.geometry = NULL, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). fun.geometry function takes sfc object returns sfc_POINT length input. NULL, function(x) sf::st_point_on_surface(sf::st_zm(x)) used. Note function may warn incorrectness result data projected, can ignore except really care exact locations. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"coordinates sf object can retrieved sf::st_coordinates(). , simply use sf::st_coordinates() , whereas text labels require exactly one coordinate per geometry, returns multiple ones polygon line. Thus, two steps needed: Choose one point per geometry function like sf::st_centroid() sf::st_point_on_surface(). Retrieve coordinates points sf::st_coordinates(). first step, can use arbitrary function via fun.geometry. default, function(x) sf::st_point_on_surface(sf::st_zm(x)) used; sf::st_point_on_surface() seems appropriate sf::st_centroid() since labels text usually intended put within polygon line. sf::st_zm() needed drop Z M dimension beforehand, otherwise sf::st_point_on_surface() may fail geometries M dimension.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x) X dimension simple feature. after_stat(y) Y dimension simple feature.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"","code":"if (requireNamespace(\"sf\", quietly = TRUE)) { nc <- sf::st_read(system.file(\"shape/nc.shp\", package=\"sf\")) ggplot(nc) + stat_sf_coordinates() ggplot(nc) + geom_errorbarh( aes(geometry = geometry, xmin = after_stat(x) - 0.1, xmax = after_stat(x) + 0.1, y = after_stat(y), height = 0.04), stat = \"sf_coordinates\" ) } #> Reading layer `nc' from data source #> `/home/runner/work/_temp/Library/sf/shape/nc.shp' using driver `ESRI Shapefile' #> Simple feature collection with 100 features and 14 fields #> Geometry type: MULTIPOLYGON #> Dimension: XY #> Bounding box: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965 #> Geodetic CRS: NAD27 #> Warning: st_point_on_surface may not give correct results for longitude/latitude data"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":null,"dir":"Reference","previous_headings":"","what":"Summarise y values at unique/binned x — stat_summary_bin","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"stat_summary() operates unique x y; stat_summary_bin() operates binned x y. flexible versions stat_bin(): instead just counting, can compute aggregate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"","code":"stat_summary_bin( mapping = NULL, data = NULL, geom = \"pointrange\", position = \"identity\", ..., fun.data = NULL, fun = NULL, fun.max = NULL, fun.min = NULL, fun.args = list(), bins = 30, binwidth = NULL, breaks = NULL, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, fun.y = deprecated(), fun.ymin = deprecated(), fun.ymax = deprecated() ) stat_summary( mapping = NULL, data = NULL, geom = \"pointrange\", position = \"identity\", ..., fun.data = NULL, fun = NULL, fun.max = NULL, fun.min = NULL, fun.args = list(), na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, fun.y = deprecated(), fun.ymin = deprecated(), fun.ymax = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. fun.data function given complete data return data frame variables ymin, y, ymax. fun.min, fun, fun.max Alternatively, supply three individual functions passed vector values return single number. fun.args Optional additional arguments passed functions. bins Number bins. Overridden binwidth. Defaults 30. binwidth width bins. Can specified numeric value function takes x scale transformation input returns single numeric value. specifying function along grouping structure, function called per group. default use number bins bins, covering range data. always override value, exploring multiple widths find best illustrate stories data. bin width date variable number days time; bin width time variable number seconds. breaks Alternatively, can supply numeric vector giving bin boundaries. Overrides binwidth bins. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). fun.ymin, fun.y, fun.ymax Use versions specified instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"stat_summary() understands following aesthetics (required aesthetics bold): x y group Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"summary-functions","dir":"Reference","previous_headings":"","what":"Summary functions","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"can either supply summary functions individually (fun, fun.max, fun.min), single function (fun.data): fun.data Complete summary function. take numeric vector input return data frame output fun.min min summary function (take numeric vector return single number) fun main summary function (take numeric vector return single number) fun.max max summary function (take numeric vector return single number) simple vector function easiest work can return single number, somewhat less flexible. summary function computes multiple values (e.g. min max), use fun.data. fun.data receive data oriented along x-axis return data.frame corresponds orientation. layer take care flipping input output oriented along y-axis. aggregation functions supplied, default mean_se().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"","code":"d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() d + stat_summary(fun.data = \"mean_cl_boot\", colour = \"red\", linewidth = 2, size = 3) # Orientation follows the discrete axis ggplot(mtcars, aes(mpg, factor(cyl))) + geom_point() + stat_summary(fun.data = \"mean_cl_boot\", colour = \"red\", linewidth = 2, size = 3) # You can supply individual functions to summarise the value at # each x: d + stat_summary(fun = \"median\", colour = \"red\", size = 2, geom = \"point\") d + stat_summary(fun = \"mean\", colour = \"red\", size = 2, geom = \"point\") d + aes(colour = factor(vs)) + stat_summary(fun = mean, geom=\"line\") d + stat_summary(fun = mean, fun.min = min, fun.max = max, colour = \"red\") d <- ggplot(diamonds, aes(cut)) d + geom_bar() d + stat_summary(aes(y = price), fun = \"mean\", geom = \"bar\") # Orientation of stat_summary_bin is ambiguous and must be specified directly ggplot(diamonds, aes(carat, price)) + stat_summary_bin(fun = \"mean\", geom = \"bar\", orientation = 'y') # \\donttest{ # Don't use ylim to zoom into a summary plot - this throws the # data away p <- ggplot(mtcars, aes(cyl, mpg)) + stat_summary(fun = \"mean\", geom = \"point\") p p + ylim(15, 30) #> Warning: Removed 9 rows containing non-finite outside the scale range #> (`stat_summary()`). # Instead use coord_cartesian p + coord_cartesian(ylim = c(15, 30)) # A set of useful summary functions is provided from the Hmisc package: stat_sum_df <- function(fun, geom=\"crossbar\", ...) { stat_summary(fun.data = fun, colour = \"red\", geom = geom, width = 0.2, ...) } d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() # The crossbar geom needs grouping to be specified when used with # a continuous x axis. d + stat_sum_df(\"mean_cl_boot\", mapping = aes(group = cyl)) d + stat_sum_df(\"mean_sdl\", mapping = aes(group = cyl)) d + stat_sum_df(\"mean_sdl\", fun.args = list(mult = 1), mapping = aes(group = cyl)) d + stat_sum_df(\"median_hilow\", mapping = aes(group = cyl)) # An example with highly skewed distributions: if (require(\"ggplot2movies\")) { set.seed(596) mov <- movies[sample(nrow(movies), 1000), ] m2 <- ggplot(mov, aes(x = factor(round(rating)), y = votes)) + geom_point() m2 <- m2 + stat_summary( fun.data = \"mean_cl_boot\", geom = \"crossbar\", colour = \"red\", width = 0.3 ) + xlab(\"rating\") m2 # Notice how the overplotting skews off visual perception of the mean # supplementing the raw data with summary statistics is _very_ important # Next, we'll look at votes on a log scale. # Transforming the scale means the data are transformed # first, after which statistics are computed: m2 + scale_y_log10() # Transforming the coordinate system occurs after the # statistic has been computed. This means we're calculating the summary on the raw data # and stretching the geoms onto the log scale. Compare the widths of the # standard errors. m2 + coord_trans(y=\"log10\") } # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":null,"dir":"Reference","previous_headings":"","what":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"stat_summary_2d() 2d variation stat_summary(). stat_summary_hex() hexagonal variation stat_summary_2d(). data divided bins defined x y, values z cell summarised fun.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"","code":"stat_summary_2d( mapping = NULL, data = NULL, geom = \"tile\", position = \"identity\", ..., bins = 30, binwidth = NULL, drop = TRUE, fun = \"mean\", fun.args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_summary_hex( mapping = NULL, data = NULL, geom = \"hex\", position = \"identity\", ..., bins = 30, binwidth = NULL, drop = TRUE, fun = \"mean\", fun.args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. bins numeric vector giving number bins vertical horizontal directions. Set 30 default. binwidth Numeric vector giving bin width vertical horizontal directions. Overrides bins set. drop drop output fun NA. fun function summary. fun.args list extra arguments pass fun na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"x: horizontal position y: vertical position z: value passed summary function","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x), after_stat(y) Location. after_stat(value) Value summary statistic.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"z binning, z values individual data points longer available.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"","code":"d <- ggplot(diamonds, aes(carat, depth, z = price)) d + stat_summary_2d() # Specifying function d + stat_summary_2d(fun = function(x) sum(x^2)) d + stat_summary_2d(fun = ~ sum(.x^2)) d + stat_summary_2d(fun = var) d + stat_summary_2d(fun = \"quantile\", fun.args = list(probs = 0.1)) if (requireNamespace(\"hexbin\")) { d + stat_summary_hex() d + stat_summary_hex(fun = ~ sum(.x^2)) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":null,"dir":"Reference","previous_headings":"","what":"Remove duplicates — stat_unique","title":"Remove duplicates — stat_unique","text":"Remove duplicates","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Remove duplicates — stat_unique","text":"","code":"stat_unique( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Remove duplicates — stat_unique","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Remove duplicates — stat_unique","text":"stat_unique() understands following aesthetics (required aesthetics bold): group Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Remove duplicates — stat_unique","text":"","code":"ggplot(mtcars, aes(vs, am)) + geom_point(alpha = 0.1) ggplot(mtcars, aes(vs, am)) + geom_point(alpha = 0.1, stat = \"unique\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":null,"dir":"Reference","previous_headings":"","what":"Summarise built plot objects — summarise_plot","title":"Summarise built plot objects — summarise_plot","text":"functions provide summarised information built ggplot objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Summarise built plot objects — summarise_plot","text":"","code":"summarise_layout(p) summarise_coord(p) summarise_layers(p)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Summarise built plot objects — summarise_plot","text":"p ggplot_built object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Summarise built plot objects — summarise_plot","text":"three types summary can obtained: summary plot layout, summary plot coord, summary plot layers.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"layout-summary","dir":"Reference","previous_headings":"","what":"Layout summary","title":"Summarise built plot objects — summarise_plot","text":"function summarise_layout() returns table provides information plot panel(s) built plot. table following columns: panel factor indicating individual plot panels. row Row number grid panels. col Column number grid panels. vars list lists. panel, respective list provides variables values specify panel. xmin, xmax minimum maximum values variable mapped x aesthetic, transformed coordinates. ymin, ymax minimum maximum values variable mapped y aesthetic, transformed coordinates. xscale scale object applied x aesthetic. yscale scale object applied y aesthetic. Importantly, values xmin, xmax, ymin, ymax, xscale, yscale determined variables mapped x y aes() call. even coord changes x y shown final plot (case coord_flip() coord_polar()), changes effect results returned summarise_plot().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"coord-summary","dir":"Reference","previous_headings":"","what":"Coord summary","title":"Summarise built plot objects — summarise_plot","text":"function summarise_coord() returns information log base coordinates log-transformed coord_trans(), also indicates whether coord flipped x y axes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"layer-summary","dir":"Reference","previous_headings":"","what":"Layer summary","title":"Summarise built plot objects — summarise_plot","text":"function summarise_layers() returns table single column, mapping, contains information aesthetic mapping layer.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Summarise built plot objects — summarise_plot","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(~class) b <- ggplot_build(p) summarise_layout(b) #> panel row col vars xmin xmax ymin ymax #> 1 1 1 1 2seater 1.33 7.27 10.4 45.6 #> 2 2 1 2 compact 1.33 7.27 10.4 45.6 #> 3 3 1 3 midsize 1.33 7.27 10.4 45.6 #> 4 4 2 1 minivan 1.33 7.27 10.4 45.6 #> 5 5 2 2 pickup 1.33 7.27 10.4 45.6 #> 6 6 2 3 subcompact 1.33 7.27 10.4 45.6 #> 7 7 3 1 suv 1.33 7.27 10.4 45.6 #> xscale yscale #> 1 #> 2 #> 3 #> 4 #> 5 #> 6 #> 7 summarise_coord(b) #> $xlog #> [1] NA #> #> $ylog #> [1] NA #> #> $flip #> [1] FALSE #> summarise_layers(b) #> mapping #> 1 ~displ, ~hwy"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Displays a useful description of a ggplot object — summary.ggplot","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"Displays useful description ggplot object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"","code":"# S3 method for class 'ggplot' summary(object, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"object ggplot2 object summarise ... arguments ignored (compatibility generic)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() summary(p) #> data: mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb #> [32x11] #> mapping: x = ~mpg, y = ~wt #> faceting: #> attach_axes: function #> attach_strips: function #> compute_layout: function #> draw_back: function #> draw_front: function #> draw_labels: function #> draw_panels: function #> finish_data: function #> format_strip_labels: function #> init_gtable: function #> init_scales: function #> map_data: function #> params: list #> setup_data: function #> setup_params: function #> shrink: TRUE #> train_scales: function #> vars: function #> super: #> ----------------------------------- #> geom_point: na.rm = FALSE #> stat_identity: na.rm = FALSE #> position_identity #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify components of a theme — theme","title":"Modify components of a theme — theme","text":"Themes powerful way customize non-data components plots: .e. titles, labels, fonts, background, gridlines, legends. Themes can used give plots consistent customized look. Modify single plot's theme using theme(); see theme_update() want modify active theme, affect subsequent plots. Use themes available complete themes like use complete theme theme_bw(), theme_minimal(), . Theme elements documented together according inheritance, read theme inheritance .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify components of a theme — theme","text":"","code":"theme( ..., line, rect, text, title, geom, spacing, margins, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.x.bottom, axis.title.y, axis.title.y.left, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.x.bottom, axis.text.y, axis.text.y.left, axis.text.y.right, axis.text.theta, axis.text.r, axis.ticks, axis.ticks.x, axis.ticks.x.top, axis.ticks.x.bottom, axis.ticks.y, axis.ticks.y.left, axis.ticks.y.right, axis.ticks.theta, axis.ticks.r, axis.minor.ticks.x.top, axis.minor.ticks.x.bottom, axis.minor.ticks.y.left, axis.minor.ticks.y.right, axis.minor.ticks.theta, axis.minor.ticks.r, axis.ticks.length, axis.ticks.length.x, axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, axis.ticks.length.y.left, axis.ticks.length.y.right, axis.ticks.length.theta, axis.ticks.length.r, axis.minor.ticks.length, axis.minor.ticks.length.x, axis.minor.ticks.length.x.top, axis.minor.ticks.length.x.bottom, axis.minor.ticks.length.y, axis.minor.ticks.length.y.left, axis.minor.ticks.length.y.right, axis.minor.ticks.length.theta, axis.minor.ticks.length.r, axis.line, axis.line.x, axis.line.x.top, axis.line.x.bottom, axis.line.y, axis.line.y.left, axis.line.y.right, axis.line.theta, axis.line.r, legend.background, legend.margin, legend.spacing, legend.spacing.x, legend.spacing.y, legend.key, legend.key.size, legend.key.height, legend.key.width, legend.key.spacing, legend.key.spacing.x, legend.key.spacing.y, legend.frame, legend.ticks, legend.ticks.length, legend.axis.line, legend.text, legend.text.position, legend.title, legend.title.position, legend.position, legend.position.inside, legend.direction, legend.byrow, legend.justification, legend.justification.top, legend.justification.bottom, legend.justification.left, legend.justification.right, legend.justification.inside, legend.location, 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.title.position, plot.subtitle, plot.caption, plot.caption.position, plot.tag, plot.tag.position, plot.tag.location, plot.margin, strip.background, strip.background.x, strip.background.y, strip.clip, strip.placement, strip.text, strip.text.x, strip.text.x.bottom, strip.text.x.top, strip.text.y, strip.text.y.left, strip.text.y.right, strip.switch.pad.grid, strip.switch.pad.wrap, complete = FALSE, validate = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify components of a theme — theme","text":"... additional element specifications part base ggplot2. general, also defined element tree argument. Splicing list also supported. line line elements (element_line()) rect rectangular elements (element_rect()) text text elements (element_text()) title title elements: plot, axes, legends (element_text(); inherits text) geom defaults geoms (element_geom()) spacing spacings (unit()) margins margins (margin()) aspect.ratio aspect ratio panel axis.title, axis.title.x, axis.title.y, axis.title.x.top, axis.title.x.bottom, axis.title.y.left, axis.title.y.right labels axes (element_text()). Specify axes' labels (axis.title), labels plane (using axis.title.x axis.title.y), individually axis (using axis.title.x.bottom, axis.title.x.top, axis.title.y.left, axis.title.y.right). axis.title.*.* inherits axis.title.* inherits axis.title, turn inherits text axis.text, axis.text.x, axis.text.y, axis.text.x.top, axis.text.x.bottom, axis.text.y.left, axis.text.y.right, axis.text.theta, axis.text.r tick labels along axes (element_text()). Specify axis tick labels (axis.text), tick labels plane (using axis.text.x axis.text.y), individually axis (using axis.text.x.bottom, axis.text.x.top, axis.text.y.left, axis.text.y.right). axis.text.*.* inherits axis.text.* inherits axis.text, turn inherits text axis.ticks, axis.ticks.x, axis.ticks.x.top, axis.ticks.x.bottom, axis.ticks.y, axis.ticks.y.left, axis.ticks.y.right, axis.ticks.theta, axis.ticks.r tick marks along axes (element_line()). Specify tick marks (axis.ticks), ticks plane (using axis.ticks.x axis.ticks.y), individually axis (using axis.ticks.x.bottom, axis.ticks.x.top, axis.ticks.y.left, axis.ticks.y.right). axis.ticks.*.* inherits axis.ticks.* inherits axis.ticks, turn inherits line axis.minor.ticks.x.top, axis.minor.ticks.x.bottom, axis.minor.ticks.y.left, axis.minor.ticks.y.right, axis.minor.ticks.theta, axis.minor.ticks.r, minor tick marks along axes (element_line()). axis.minor.ticks.*.* inherit corresponding major ticks axis.ticks.*.*. axis.ticks.length, axis.ticks.length.x, axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, axis.ticks.length.y.left, axis.ticks.length.y.right, axis.ticks.length.theta, axis.ticks.length.r length tick marks (unit). axis.ticks.length inherits spacing. axis.minor.ticks.length, axis.minor.ticks.length.x, axis.minor.ticks.length.x.top, axis.minor.ticks.length.x.bottom, axis.minor.ticks.length.y, axis.minor.ticks.length.y.left, axis.minor.ticks.length.y.right, axis.minor.ticks.length.theta, axis.minor.ticks.length.r length minor tick marks (unit), relative axis.ticks.length provided rel(). axis.line, axis.line.x, axis.line.x.top, axis.line.x.bottom, axis.line.y, axis.line.y.left, axis.line.y.right, axis.line.theta, axis.line.r lines along axes (element_line()). Specify lines along axes (axis.line), lines plane (using axis.line.x axis.line.y), individually axis (using axis.line.x.bottom, axis.line.x.top, axis.line.y.left, axis.line.y.right). axis.line.*.* inherits axis.line.* inherits axis.line, turn inherits line legend.background background legend (element_rect(); inherits rect) legend.margin margin around legend (margin()); inherits margins. legend.spacing, legend.spacing.x, legend.spacing.y spacing legends (unit). legend.spacing.x & legend.spacing.y inherit legend.spacing can specified separately. legend.spacing inherits spacing. legend.key background underneath legend keys (element_rect(); inherits rect) legend.key.size, legend.key.height, legend.key.width size legend keys (unit); key background height & width inherit legend.key.size can specified separately. turn legend.key.size inherits spacing. legend.key.spacing, legend.key.spacing.x, legend.key.spacing.y spacing legend keys given unit. Spacing horizontal (x) vertical (y) direction inherit legend.key.spacing can specified separately. legend.key.spacing inherits spacing. legend.frame frame drawn around bar (element_rect()). legend.ticks tick marks shown along bars axes (element_line()) legend.ticks.length length tick marks legend (unit()); inherits legend.key.size. legend.axis.line lines along axes legends (element_line()) legend.text legend item labels (element_text(); inherits text) legend.text.position placement legend text relative legend keys bars (\"top\", \"right\", \"bottom\" \"left\"). legend text placement might incompatible legend's direction guides. legend.title title legend (element_text(); inherits title) legend.title.position placement legend title relative main legend (\"top\", \"right\", \"bottom\" \"left\"). legend.position default position legends (\"none\", \"left\", \"right\", \"bottom\", \"top\", \"inside\") legend.position.inside numeric vector length two setting placement legends \"inside\" position. legend.direction layout items legends (\"horizontal\" \"vertical\") legend.byrow whether legend-matrix filled columns (FALSE, default) rows (TRUE). legend.justification anchor point positioning legend inside plot (\"center\" two-element numeric vector) justification according plot area positioned outside plot legend.justification.top, legend.justification.bottom, legend.justification.left, legend.justification.right, legend.justification.inside legend.justification specified per legend.position option. legend.location Relative placement legends outside plot string. Can \"panel\" (default) align legends panels \"plot\" align legends plot whole. legend.box arrangement multiple legends (\"horizontal\" \"vertical\") legend.box.just justification legend within overall bounding box, multiple legends (\"top\", \"bottom\", \"left\", \"right\", \"center\" \"centre\") legend.box.margin margins around full legend area, specified using margin(); inherits margins. legend.box.background background legend area (element_rect(); inherits rect) legend.box.spacing spacing plotting area legend box (unit); inherits spacing. panel.background background plotting area, drawn underneath plot (element_rect(); inherits rect) panel.border border around plotting area, drawn top plot covers tick marks grid lines. used fill = NA (element_rect(); inherits rect) panel.spacing, panel.spacing.x, panel.spacing.y spacing facet panels (unit). panel.spacing.x & panel.spacing.y inherit panel.spacing can specified separately. panel.spacing inherits spacing. panel.grid, panel.grid.major, panel.grid.minor, panel.grid.major.x, panel.grid.major.y, panel.grid.minor.x, panel.grid.minor.y grid lines (element_line()). Specify major grid lines, minor grid lines separately (using panel.grid.major panel.grid.minor) individually axis (using panel.grid.major.x, panel.grid.minor.x, panel.grid.major.y, panel.grid.minor.y). Y axis grid lines horizontal x axis grid lines vertical. panel.grid.*.* inherits panel.grid.* inherits panel.grid, turn inherits line panel.ontop option place panel (background, gridlines) data layers (logical). Usually used transparent blank panel.background. plot.background background entire plot (element_rect(); inherits rect) plot.title plot title (text appearance) (element_text(); inherits title) left-aligned default plot.title.position, plot.caption.position Alignment plot title/subtitle caption. setting plot.title.position applies title subtitle. value \"panel\" (default) means titles /caption aligned plot panels. value \"plot\" means titles /caption aligned entire plot (minus space margins plot tag). plot.subtitle plot subtitle (text appearance) (element_text(); inherits title) left-aligned default plot.caption caption plot (text appearance) (element_text(); inherits title) right-aligned default plot.tag upper-left label identify plot (text appearance) (element_text(); inherits title) left-aligned default plot.tag.position position tag string (\"topleft\", \"top\", \"topright\", \"left\", \"right\", \"bottomleft\", \"bottom\", \"bottomright\") coordinate. coordinate, can numeric vector length 2 set x,y-coordinate relative whole plot. coordinate option unavailable plot.tag.location = \"margin\". plot.tag.location placement tag string, one \"panel\", \"plot\" \"margin\". Respectively, place tag inside panel space, anywhere plot whole, margin around panel space. plot.margin margin around entire plot (unit sizes top, right, bottom, left margins); inherits margin. strip.background, strip.background.x, strip.background.y background facet labels (element_rect(); inherits rect). Horizontal facet background (strip.background.x) & vertical facet background (strip.background.y) inherit strip.background can specified separately strip.clip strip background edges strip labels clipped extend strip background? Options \"\" clip, \"\" disable clipping \"inherit\" (default) take clipping setting parent viewport. strip.placement placement strip respect axes, either \"inside\" \"outside\". important axes strips side plot. strip.text, strip.text.x, strip.text.y, strip.text.x.top, strip.text.x.bottom, strip.text.y.left, strip.text.y.right facet labels (element_text(); inherits text). Horizontal facet labels (strip.text.x) & vertical facet labels (strip.text.y) inherit strip.text can specified separately. Facet strips dedicated position-dependent theme elements (strip.text.x.top, strip.text.x.bottom, strip.text.y.left, strip.text.y.right) inherit strip.text.x strip.text.y, respectively. consequence, theme stylings need applied position-dependent elements rather parent elements strip.switch.pad.grid, strip.switch.pad.wrap space strips axes strips switched (unit); inherits spacing. complete set TRUE complete theme, one returned theme_grey(). Complete themes behave differently added ggplot object. Also, setting complete = TRUE elements set inherit blank elements. validate TRUE run validate_element(), FALSE bypass checks.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"theme-inheritance","dir":"Reference","previous_headings":"","what":"Theme inheritance","title":"Modify components of a theme — theme","text":"Theme elements inherit properties theme elements hierarchically. example, axis.title.x.bottom inherits axis.title.x inherits axis.title, turn inherits text. text elements inherit directly indirectly text; lines inherit line, rectangular objects inherit rect. means can modify appearance multiple elements setting single high-level component. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify components of a theme — theme","text":"","code":"p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + labs(title = \"Fuel economy declines as weight increases\") p1 # Plot --------------------------------------------------------------------- p1 + theme(plot.title = element_text(size = rel(2))) p1 + theme(plot.background = element_rect(fill = \"green\")) # Panels -------------------------------------------------------------------- p1 + theme(panel.background = element_rect(fill = \"white\", colour = \"grey50\")) p1 + theme(panel.border = element_rect(linetype = \"dashed\")) p1 + theme(panel.grid.major = element_line(colour = \"black\")) p1 + theme( panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank() ) # Put gridlines on top of data p1 + theme( panel.background = element_rect(fill = NA), panel.grid.major = element_line(colour = \"grey50\"), panel.ontop = TRUE ) # Axes ---------------------------------------------------------------------- # Change styles of axes texts and lines p1 + theme(axis.line = element_line(linewidth = 3, colour = \"grey80\")) p1 + theme(axis.text = element_text(colour = \"blue\")) p1 + theme(axis.ticks = element_line(linewidth = 2)) # Change the appearance of the y-axis title p1 + theme(axis.title.y = element_text(size = rel(1.5), angle = 90)) # Make ticks point outwards on y-axis and inwards on x-axis p1 + theme( axis.ticks.length.y = unit(.25, \"cm\"), axis.ticks.length.x = unit(-.25, \"cm\"), axis.text.x = element_text(margin = margin(t = .3, unit = \"cm\")) ) # \\donttest{ # Legend -------------------------------------------------------------------- p2 <- ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(colour = factor(cyl), shape = factor(vs))) + labs( x = \"Weight (1000 lbs)\", y = \"Fuel economy (mpg)\", colour = \"Cylinders\", shape = \"Transmission\" ) p2 # Position p2 + theme(legend.position = \"none\") p2 + theme(legend.justification = \"top\") p2 + theme(legend.position = \"bottom\") # Or place legends inside the plot using relative coordinates between 0 and 1 # legend.justification sets the corner that the position refers to p2 + theme( legend.position = \"inside\", legend.position.inside = c(.95, .95), legend.justification = c(\"right\", \"top\"), legend.box.just = \"right\", legend.margin = margin(6, 6, 6, 6) ) # The legend.box properties work similarly for the space around # all the legends p2 + theme( legend.box.background = element_rect(), legend.box.margin = margin(6, 6, 6, 6) ) # You can also control the display of the keys # and the justification related to the plot area can be set p2 + theme(legend.key = element_rect(fill = \"white\", colour = \"black\")) p2 + theme(legend.text = element_text(size = 8, colour = \"red\")) p2 + theme(legend.title = element_text(face = \"bold\")) # Strips -------------------------------------------------------------------- p3 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl) p3 p3 + theme(strip.background = element_rect(colour = \"black\", fill = \"white\")) p3 + theme(strip.text.x = element_text(colour = \"white\", face = \"bold\")) # More direct strip.text.x here for top # as in the facet_wrap the default strip.position is \"top\" p3 + theme(strip.text.x.top = element_text(colour = \"white\", face = \"bold\")) p3 + theme(panel.spacing = unit(1, \"lines\")) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/tidyeval.html","id":null,"dir":"Reference","previous_headings":"","what":"Tidy eval helpers — tidyeval","title":"Tidy eval helpers — tidyeval","text":"page lists tidy eval tools reexported package rlang. learn using tidy eval scripts packages high level, see dplyr programming vignette ggplot2 packages vignette. Metaprogramming section Advanced R may also useful deeper dive. tidy eval operators {{, !!, !!! syntactic constructs specially interpreted tidy eval functions. mostly need {{, !! !!! advanced operators use simple cases. curly-curly operator {{ allows tunnel data-variables passed function arguments inside tidy eval functions. {{ designed individual arguments. pass multiple arguments contained dots, use ... normal way. enquo() enquos() delay execution one several function arguments. former returns single expression, latter returns list expressions. defused, expressions longer evaluate . must injected back evaluation context !! (single expression) !!! (list expressions). simple case, code equivalent usage {{ ... . Defusing enquo() enquos() needed complex cases, instance need inspect modify expressions way. .data pronoun object represents current slice data. variable name string, use .data pronoun subset variable [[. Another tidy eval operator :=. makes possible use glue curly-curly syntax LHS =. technical reasons, R language support complex expressions left =, use := workaround. Many tidy eval functions like dplyr::mutate() dplyr::summarise() give automatic name unnamed inputs. need create sort automatic names , use as_label(). instance, glue-tunnelling syntax can reproduced manually : Expressions defused enquo() (tunnelled {{) need simple column names, can arbitrarily complex. as_label() handles cases gracefully. code assumes simple column name, use as_name() instead. safer throws error input name expected.","code":"my_function <- function(data, var, ...) { data %>% group_by(...) %>% summarise(mean = mean({{ var }})) } my_function <- function(data, var, ...) { # Defuse var <- enquo(var) dots <- enquos(...) # Inject data %>% group_by(!!!dots) %>% summarise(mean = mean(!!var)) } my_var <- \"disp\" mtcars %>% summarise(mean = mean(.data[[my_var]])) my_function <- function(data, var, suffix = \"foo\") { # Use `{{` to tunnel function arguments and the usual glue # operator `{` to interpolate plain strings. data %>% summarise(\"{{ var }}_mean_{suffix}\" := mean({{ var }})) } my_function <- function(data, var, suffix = \"foo\") { var <- enquo(var) prefix <- as_label(var) data %>% summarise(\"{prefix}_mean_{suffix}\" := mean(!!var)) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/transform_position.html","id":null,"dir":"Reference","previous_headings":"","what":"Convenience function to transform all position variables. — transform_position","title":"Convenience function to transform all position variables. — transform_position","text":"Convenience function transform position variables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/transform_position.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Convenience function to transform all position variables. — transform_position","text":"","code":"transform_position(df, trans_x = NULL, trans_y = NULL, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/transform_position.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Convenience function to transform all position variables. — transform_position","text":"trans_x, trans_y Transformation functions x y aesthetics. (transform x, xmin, xmax, xend etc) ... Additional arguments passed trans_x trans_y.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":null,"dir":"Reference","previous_headings":"","what":"Translating shape strings — translate_shape_string","title":"Translating shape strings — translate_shape_string","text":"translate_shape_string() helper function translating point shapes given character vector integers interpreted grid system.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Translating shape strings — translate_shape_string","text":"","code":"translate_shape_string(shape_string)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Translating shape strings — translate_shape_string","text":"shape_string character vector giving point shapes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Translating shape strings — translate_shape_string","text":"integer vector translated shapes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Translating shape strings — translate_shape_string","text":"","code":"translate_shape_string(c(\"circle\", \"square\", \"triangle\")) #> [1] 19 15 17 # Strings with 1 or less characters are interpreted as symbols translate_shape_string(c(\"a\", \"b\", \"?\")) #> [1] \"a\" \"b\" \"?\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/txhousing.html","id":null,"dir":"Reference","previous_headings":"","what":"Housing sales in TX — txhousing","title":"Housing sales in TX — txhousing","text":"Information housing market Texas provided TAMU real estate center, https://trerc.tamu.edu/.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/txhousing.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Housing sales in TX — txhousing","text":"","code":"txhousing"},{"path":"https://ggplot2.tidyverse.org/dev/reference/txhousing.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Housing sales in TX — txhousing","text":"data frame 8602 observations 9 variables: city Name multiple listing service (MLS) area year,month,date Date sales Number sales volume Total value sales median Median sale price listings Total active listings inventory \"Months inventory\": amount time take sell current listings current pace sales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"Functions update reset default aesthetics geoms stats.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"","code":"update_geom_defaults(geom, new) update_stat_defaults(stat, new) reset_geom_defaults() reset_stat_defaults()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"new One following: named list aesthetics serve new defaults. NULL reset defaults. stat, geom Name geom/stat modify (like \"point\" \"bin\"), Geom/Stat object (like GeomPoint StatBin).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"Please note geom defaults can set en masse via theme(geom) argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"","code":"# updating a geom's default aesthetic settings # example: change geom_point()'s default color GeomPoint$default_aes #> Aesthetic mapping: #> * `shape` -> `from_theme(pointshape)` #> * `colour` -> `from_theme(ink)` #> * `size` -> `from_theme(pointsize)` #> * `fill` -> NA #> * `alpha` -> NA #> * `stroke` -> `from_theme(borderwidth)` update_geom_defaults(\"point\", aes(color = \"red\")) GeomPoint$default_aes #> Aesthetic mapping: #> * `shape` -> `from_theme(pointshape)` #> * `colour` -> \"red\" #> * `size` -> `from_theme(pointsize)` #> * `fill` -> NA #> * `alpha` -> NA #> * `stroke` -> `from_theme(borderwidth)` ggplot(mtcars, aes(mpg, wt)) + geom_point() # reset single default update_geom_defaults(\"point\", NULL) # reset all defaults reset_geom_defaults() # updating a stat's default aesthetic settings # example: change stat_bin()'s default y-axis to the density scale StatBin$default_aes #> Aesthetic mapping: #> * `x` -> `after_stat(count)` #> * `y` -> `after_stat(count)` #> * `weight` -> 1 update_stat_defaults(\"bin\", aes(y = after_stat(density))) StatBin$default_aes #> Aesthetic mapping: #> * `x` -> `after_stat(count)` #> * `y` -> `after_stat(density)` #> * `weight` -> 1 ggplot(data.frame(x = rnorm(1e3)), aes(x)) + geom_histogram() + geom_function(fun = dnorm, color = \"red\") #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # reset single default update_stat_defaults(\"bin\", NULL) # reset all defaults reset_stat_defaults()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":null,"dir":"Reference","previous_headings":"","what":"Update axis/legend labels — update_labels","title":"Update axis/legend labels — update_labels","text":"Update axis/legend labels","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Update axis/legend labels — update_labels","text":"","code":"update_labels(p, labels)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Update axis/legend labels — update_labels","text":"p plot modify labels named list new labels","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Update axis/legend labels — update_labels","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() update_labels(p, list(x = \"New x\")) update_labels(p, list(x = expression(x / y ^ 2))) update_labels(p, list(x = \"New x\", y = \"New Y\")) update_labels(p, list(colour = \"Fail silently\")) #> Warning: Ignoring unknown labels: #> • `colour = \"Fail silently\"`"},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":null,"dir":"Reference","previous_headings":"","what":"Quote faceting variables — vars","title":"Quote faceting variables — vars","text":"Just like aes(), vars() quoting function takes inputs evaluated context dataset. inputs can : variable names complex expressions cases, results (vectors variable represents results expressions) used form faceting groups.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Quote faceting variables — vars","text":"","code":"vars(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Quote faceting variables — vars","text":"... Variables expressions automatically quoted. evaluated context data form faceting groups. Can named (names passed labeller).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Quote faceting variables — vars","text":"","code":"p <- ggplot(mtcars, aes(wt, disp)) + geom_point() p + facet_wrap(vars(vs, am)) # vars() makes it easy to pass variables from wrapper functions: wrap_by <- function(...) { facet_wrap(vars(...), labeller = label_both) } p + wrap_by(vs) p + wrap_by(vs, am) # You can also supply expressions to vars(). In this case it's often a # good idea to supply a name as well: p + wrap_by(drat = cut_number(drat, 3)) # Let's create another function for cutting and wrapping a # variable. This time it will take a named argument instead of dots, # so we'll have to use the \"enquote and unquote\" pattern: wrap_cut <- function(var, n = 3) { # Let's enquote the named argument `var` to make it auto-quoting: var <- enquo(var) # `as_label()` will create a nice default name: nm <- as_label(var) # Now let's unquote everything at the right place. Note that we also # unquote `n` just in case the data frame has a column named # `n`. The latter would have precedence over our local variable # because the data is always masking the environment. wrap_by(!!nm := cut_number(!!var, !!n)) } # Thanks to tidy eval idioms we now have another useful wrapper: p + wrap_cut(drat)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/waiver.html","id":null,"dir":"Reference","previous_headings":"","what":"A waiver object. — waiver","title":"A waiver object. — waiver","text":"waiver \"flag\" object, similar NULL, indicates calling function just use default value. used certain functions distinguish displaying nothing (NULL) displaying default value calculated elsewhere (waiver())","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/waiver.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A waiver object. — waiver","text":"","code":"waiver()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":null,"dir":"Reference","previous_headings":"","what":"Arrange 1d structure into a grid — wrap_dims","title":"Arrange 1d structure into a grid — wrap_dims","text":"Arrange 1d structure grid","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Arrange 1d structure into a grid — wrap_dims","text":"","code":"wrap_dims(n, nrow = NULL, ncol = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Arrange 1d structure into a grid — wrap_dims","text":"n length structure nrow, ncol desired dimensions grid","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Arrange 1d structure into a grid — wrap_dims","text":"grid dimension vector nrow ncol","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/zeroGrob.html","id":null,"dir":"Reference","previous_headings":"","what":"The zero grob draws nothing and has zero size. — zeroGrob","title":"The zero grob draws nothing and has zero size. — zeroGrob","text":"zero grob draws nothing zero size.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/zeroGrob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"The zero grob draws nothing and has zero size. — zeroGrob","text":"","code":"zeroGrob()"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-development-version","dir":"Changelog","previous_headings":"","what":"ggplot2 (development version)","title":"ggplot2 (development version)","text":"(Breaking) defaults geoms can set one theme. (@teunbrand based pioneering work @dpseidel, #2239) new theme(geom) argument used track defaults. element_geom() function can used populate argument. from_theme() function allows access theme default fields inside aes() function. Passing empty unmapped aesthetics layers raises warning instead throwing error (@teunbrand, #6009). Moved {mgcv} Imports Suggests (@teunbrand, #5986) New reset_geom_defaults() reset_stat_defaults() restore geom stat default aesthetics (@teunbrand, #5975). facet_wrap() can space = \"free_x\" 1-row layouts space = \"free_y\" 1-column layouts (@teunbrand) Secondary axes respect n.breaks setting continuous scales (@teunbrand, #4483). Layers can names (@teunbrand, #4066). (internal) improvements pal_qualitative() (@teunbrand, #5013) coord_radial(clip = \"\") clips panel area graphics device supports clipping paths (@teunbrand, #5952). (internal) Panel clipping responsibility moved Facet class Coord class new Coord$draw_panel() method. theme(strip.clip) now defaults \"\" independent Coord clipping (@teunbrand, 5952). (internal) rearranged code Facet$draw_paensl() method (@teunbrand). Axis labels now justified across facet panels (@teunbrand, #5820) Fixed bug stat_function() x-axis title now produced automatically data added. (@phispu, #5647). geom_sf now accepts shape names (@sierrajohnson, #5808) Added gg class labs() (@phispu, #5553). Missing values discrete palettes longer translated (@teunbrand, #5929). Fixed bug facet_grid(margins = TRUE) using expresssions (@teunbrand, #1864). geom_step() now supports orientation argument (@teunbrand, #5936). position_dodge() position_jitterdodge() now reverse argument (@teunbrand, #3610) coord_radial(r.axis.inside) can now take numeric value control placement internally placed radius axes (@teunbrand, #5805). (internal) default labels derived ggplot_build() rather ggplot_add.Layer() (@teunbrand, #5894) attempt made use variable’s label attribute default label (@teunbrand, #4631) Themes gain additional header_family argument easily set font headers titles (#5886). plot.subtitle, plot.caption plot.tag theme elements now inherit root text element instead title element (#5886). ggplot2 longer imports {glue} (@teunbrand, #5986). geom_rect() can now derive required corners positions x/width y/height parameterisation (@teunbrand, #5861). position scales now use definition x y aesthetics. lets uncommon aesthetics like xintercept expand scales usual. (#3342, #4966, @teunbrand) Bare numeric values provided Date Datetime scales get inversely transformed (cast Date/POSIXct) warning (@teunbrand). stat_bin() now accepts functions argument breaks (@aijordan, #4561) (internal) plot’s layout now coord parameter used prevent setting identical panel parameters (#5427) (internal) rearranged code Facet$draw_panels() method (@teunbrand). geom_rug() prints warning na.rm = FALSE, per documentation (@pn317, #5905) position_dodge(preserve = \"single\") now handles multi-row geoms better, geom_violin() (@teunbrand based @clauswilke’s work, #2801). position_jitterdodge() now dodges group (@teunbrand, #3656) arrow.fill parameter now applied line-based functions: geom_path(), geom_line(), geom_step() geom_function(), line geometries geom_sf() element_line(). Fixed bug binned guides keep --bounds breaks (@teunbrand, #5870). size draw_key_polygon() glyph now reflects linewidth aesthetic (#4852). New function complete_theme() replicate themes handled plot building (#5801). Special getter setter functions renamed consistency, allowing better tab-completion get_*- set_*-prefixes. old names remain available backward compatibility (@teunbrand, #5568). Discrete scales now support minor_breaks. may make sense discrete position scales, affects placement minor ticks minor gridlines (#5434). Discrete position scales now expose palette argument, can used customise spacings levels (@teunbrand, #5770). default se parameter layers geom = \"smooth\" TRUE data ymin ymax parameters FALSE absent. Note affect default geom_smooth() stat_smooth() (@teunbrand, #5572). bounded density option stat_density() uses wider range prevent discontinuities (#5641). geom_raster() now falls back rendering geom_rect() coordinates Cartesian (#5503). stat_ecdf() now optional weight aesthetic (@teunbrand, #5058). Position scales combined coord_sf() can now use functions breaks argument. addition, n.breaks works intended breaks = NULL removes grid lines axes (@teunbrand, #4622). (Internal) Applying defaults geom_sf() moved internal sf_grob() GeomSf$use_defaults() (@teunbrand). facet_wrap() new options dir argument precisely control panel directions. Internally dir = \"h\" dir = \"v\" deprecated (@teunbrand, #5212). Prevented facet_wrap(..., drop = FALSE) throwing spurious errors character facetting variable contained NAs (@teunbrand, #5485). facets coerce faceting variables factors, ‘ordered’ class dropped (@teunbrand, #5666). geom_curve() now appropriately removes missing data instead throwing errors (@teunbrand, #5831). update_geom_defaults() update_stat_defaults() reset mechanism using new = NULL invisible return previous defaults (#4993). Fixed regression axes breaks = NULL caused axes disappear instead just rendering axis line (@teunbrand, #5816). geom_point() can dodged vertically using position_dodge(..., orientation = \"y\") (@teunbrand, #5809). Fixed bug na.value incorrectly mapped non-NA values (@teunbrand, #5756). Fixed bug guide_custom() throw error theme_void() (@teunbrand, #5856). New helper function gg_par() translate ggplot2’s interpretation graphical parameters {grid}’s interpretation (@teunbrand, #5866). scale_{x/y}_discrete() can now accept sec.axis. recommended use dup_axis() set custom breaks labels, discrete variables transformed (@teunbrand, #3171). stat_density() new computed variable: wdensity, calculated density times sum weights (@teunbrand, #4176). theme() gets new spacing margins arguments spacings (non-text) margins inherit (@teunbrand, #5622). geom_ribbon() can varying fill alpha linear coordinate systems (@teunbrand, #4690). geom_tile() computes default widths heights per panel instead per layer (@teunbrand, #5740). fill panel.border theme setting ignored forced transparent (#5782). stat_align() skips computation 1 group therefore alignment necessary (#5788). position_stack() skips computation x values unique therefore stacking necessary (#5788). new ggplot_build() S3 method classes added, returns input unaltered (@teunbrand, #5800). width implemented aesthetic instead parameter geom_col() geom_bar() (#3142). Fix bug position_jitterdodge() different jitters applied different position aesthetics axis (@teunbrand, #5818). stat_bin(), default boundary now chosen better adhere nbin argument (@teunbrand, #5882, #5036) after_stat() after_scale() throw warnings computed aesthetics correct length (#5901). guide_colourbar() now correctly hands position available_aes parameters downstream (@teunbrand, #5930) geom_hline() geom_vline() now position argument (@yutannihilation, #4285). New function get_strip_labels() retrieve facet labels (@teunbrand, #4979) Fixed bug position_dodge2()’s identification range overlaps (@teunbrand, #5938, #4327). Fixed bug empty discrete scales weren’t recognised (@teunbrand, #5945). (internal) summary function stat_summary() stat_summary_bin() setup total instead per group (@teunbrand, #5971) facet_grid(space = \"free\") can now combined coord_fixed() (@teunbrand, #4584). theme_classic() now black ticks text instead dark gray. addition, theme_classic()’s axis line end \"square\" (@teunbrand, #5978). {tibble} now suggested instead imported (@teunbrand, #5986) ellipsis argument now checked fortify(), get_alt_text(), labs() several guides (@teunbrand, #3196).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-351","dir":"Changelog","previous_headings":"","what":"ggplot2 3.5.1","title":"ggplot2 3.5.1","text":"CRAN release: 2024-04-23 small release focusing fixing regressions 3.5.0 documentation updates.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-5-1","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.5.1","text":"Fixed bug discrete scales map aesthetics consisting NAs (#5623) Fixed spurious warnings sec_axis() breaks = NULL (#5713). Patterns gradients now also enabled geom_sf() (@teunbrand, #5716). default behaviour resolution() reverted pre-3.5.0 behaviour. Whether mapped discrete vectors treated resolution 1 controlled new discrete argument. Fixed bug guide_bins() guide_coloursteps() discrete breaks, levels produced cut(), ordered incorrectly (@teunbrand, #5757).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"improvements-3-5-1","dir":"Changelog","previous_headings":"","what":"Improvements","title":"ggplot2 3.5.1","text":"facets coerce faceting variables factors, ‘ordered’ class dropped (@teunbrand, #5666). coord_map() coord_polar() throw informative warnings used guide system (#5707). passing function stat_contour(breaks), function used calculate breaks even bins binwidth missing (@teunbrand, #5686). geom_step() now supports lineend, linejoin linemitre parameters (@teunbrand, #5705). Fixed performance loss .data pronoun used aes() (#5730). Facet evaluation better dealing inherited errors (@teunbrand, #5670). stat_bin() deals non-finite breaks better (@teunbrand, #5665). axes coord_radial() don’t neatly fit top/right/bottom/left organisation, specifying position = \"top\" position = \"right\" scale flip placement radial axis (#5735) Theme elements exist now throw warnings instead errors (#5719). Fixed bug coord_radial() full circles treated (@teunbrand, #5750). legends detect presence values layer, NA now detected data contains values outside given breaks (@teunbrand, #5749). annotate() now warns stat position arguments (@teunbrand, #5151) guide_coloursteps(even.steps = FALSE) now works discrete data formatted cut() (@teunbrand, #3877).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-350","dir":"Changelog","previous_headings":"","what":"ggplot2 3.5.0","title":"ggplot2 3.5.0","text":"CRAN release: 2024-02-23 minor release turned quite beefy. focused overhauling guide system: system responsible displaying information scales guise axes legends. part overhaul, new guides implemented existing guides refined. look feel guides mostly preserved, internals styling options changed drastically. Briefly summarising highlights, also welcome coord_radial() successor coord_polar(). Initial support newer graphical features, pattern fills added. API changed ()/ vectors interact scale system, namely: .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-5-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.5.0","text":"guide system. whole. See ‘new features’ information. S3 guide generics still place, S3 methods guide_train(), guide_merge(), guide_geom(), guide_transform(), guide_gengrob() superseded respective ggproto methods. practice, mean NextMethod() sub-classing ggplot2’s guides S3 system longer work. default, guide_legend() now draws key glyph layer value layer’s data. revert old behaviour, can still set show.legend = c({aesthetic} = TRUE) (@teunbrand, #3648). scale_{colour/fill}_gradient2() scale_{colour/fill}_steps2() functions, midpoint argument transformed scale transformation (#3198). legend.key theme element set inherit panel.background theme element. default themes longer set legend.key element. causes visual change default theme_gray() (#5549). scale_name argument continuous_scale(), discrete_scale() binned_scale() soft-deprecated. implemented custom scales, advised double-check unnamed arguments ends (@teunbrand, #1312). legend.text.align legend.title.align arguments theme() deprecated. hjust setting legend.text legend.title elements continues fulfill role text alignment (@teunbrand, #5347). ‘lines’ units geom_label(), often used label.padding argument, now relative text size. causes visual change, fixes misalignment issue textbox text (@teunbrand, #4753) coord_flip() marked superseded. recommended alternative swap x y aesthetic /using orientation argument layer (@teunbrand, #5130). trans argument scales secondary axes renamed transform. trans argument deprecated. access transformation scale, new get_transformation() method added Scale-classes (#5558). Providing numeric vector theme(legend.position) deprecated. set default legend position inside plot use theme(legend.position = \"inside\", legend.position.inside = c(...)) instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-5-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.5.0","text":"Plot scales now ignore AsIs objects constructed (x), instead invoking identity scale. allows columns co-exist layers need non-identity scale aesthetic. Also, makes easy specify relative positions (@teunbrand, #5142). fill aesthetic many geoms now accepts grid’s patterns gradients. developers layer extensions, feature can enabled switching fill = alpha(fill, alpha) fill = fill_alpha(fill, alpha) providing fills grid::gpar() (@teunbrand, #3997). New function check_device() testing availability advanced graphics features introduced R 4.1.0 onward (@teunbrand, #5332). coord_radial() successor coord_polar() customisation options. coord_radial() can: integrate new guide system via dedicated guide_axis_theta() display angle coordinate. addition drawing full circles, also draw circle sectors using end argument. avoid data vanishing center plot setting donut argument. adjust angle aesthetic layers, geom_text(), align coordinate system using rotate_angle argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"the-guide-system-3-5-0","dir":"Changelog","previous_headings":"New features","what":"The guide system","title":"ggplot2 3.5.0","text":"guide system encompassing axes legends, last remaining chunk ggplot2, rewritten use system instead S3 system. change necessary step officially break open guide system extension package developers. axes legends now inherit class, makes extensible manner geoms, stats, facets coords (#3329, @teunbrand) user-facing change styling guides rewired theme system. Guides now theme argument can style individual guides, theme() gained additional arguments style guides. Theme elements declared guide override theme elements set plot. new theme elements guides : legend.key.spacing{.x/.y}, legend.frame, legend.axis.line, legend.ticks, legend.ticks.length, legend.text.position legend.title.position. Previous style options arguments guide_*() functions soft-deprecated. Unfortunately, fully preserve function pre-existing guide extensions written S3 system. fallback old guides encapsulated class, calls old S3 generics. S3 methods removed part cleaning , old guides still work S3 methods reimplemented, encourage switch new system (#2728). order argument guides now strictly needs length-1 integer (#4958).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"axes-3-5-0","dir":"Changelog","previous_headings":"New features > The guide system","what":"Axes","title":"ggplot2 3.5.0","text":"New guide_axis_stack() combine axis guides top one another. New guide_axis_theta() draw axis circular arc coord_radial(). guide can controlled adding guides(theta = guide_axis_theta(...)) plot. New guide_axis_logticks() can used draw logarithmic tick marks axis. supersedes annotation_logticks() function (@teunbrand, #5325). guide_axis() gains minor.ticks argument draw minor ticks (#4387). guide_axis() gains cap argument can used trim axis line extreme breaks (#4907). Primary axis titles now placed primary guide, guides(x = guide_axis(position = \"top\")) display title top default (#4650). default vjust axis.title.y.right element now 1 instead Unknown secondary axis guide positions now inferred opposite primary axis guide latter known position (#4650).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"legends-3-5-0","dir":"Changelog","previous_headings":"New features > The guide system","what":"Legends","title":"ggplot2 3.5.0","text":"New guide_custom() function drawing custom graphical objects (grobs) unrelated scales legend positions (#5416). legends acquired position argument, allows individual guides deviate legend.position set theme() function. means legends can now placed multiple sides plot (#5488). spacing legend keys labels, addition legends titles, now controlled text’s margin setting. specifying margins automatically add appropriate text margins. control spacing within legend keys, new legend.key.spacing.{x/y} argument can used theme(). leaves legend.spacing theme setting dedicated solely controlling spacing different guides (#5455). guide_colourbar() guide_coloursteps() gain alpha argument set transparency bar (#5085). New display argument guide_colourbar() supplants raster argument. R 4.1.0 , display = \"gradient\" draw gradient. Legend keys can draw arrows size adjusted arrows. legend titles larger legend, title justification extends placement keys labels (#1903). Glyph drawing functions draw_key_*() family can now set \"width\" \"height\" attributes (centimetres) produced keys control displayed size legend. coord_sf() now uses customisable guides provided scales guides() function (@teunbrand).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"improvements-3-5-0","dir":"Changelog","previous_headings":"","what":"Improvements","title":"ggplot2 3.5.0","text":"guide_coloursteps(even.steps = FALSE) now draws one rectangle per interval instead many small ones (#5481). draw_key_label() now better reflects appearance labels (#5561). position_stack() longer silently removes missing data, now handled geom instead position (#3532). minor_breaks function argument scales can now also take function two arguments: scale’s limits scale’s major breaks (#3583). Failing fit predict stat_smooth() now gives warning omits failed group, instead throwing error (@teunbrand, #5352). labeller() now handles unspecified entries lookup tables (@92amartins, #4599). fortify.default() now accepts data-frame-like object granted object exhibits healthy dim(), colnames(), .data.frame() behaviours (@hpages, #5390). geom_violin() gains bounds argument analogous geom_density()s (@eliocamp, #5493). apply dodging consistently violin plots, stat_ydensity() now drop argument keep discard groups 1 observation. geom_boxplot() gains new argument, staplewidth can draw staples ends whiskers (@teunbrand, #5126) geom_boxplot() gains outliers argument switch outliers , manner affects scale range. hiding outliers affect scale range, can continue use outlier.shape = NA (@teunbrand, #4892). Nicer error messages xlim/ylim arguments coord-* functions (@92amartins, #4601, #5297). can now omit either xend yend geom_segment() one now required. one missing, filled x y aesthetics respectively. makes drawing horizontal vertical segments little bit convenient (@teunbrand, #5140). geom_path() aesthetics varying within groups, arrow() applied groups instead individual segments (@teunbrand, #4935). geom_text() geom_label() gained size.unit parameter set text size millimetres, points, centimetres, inches picas (@teunbrand, #3799). geom_label() now uses angle aesthetic (@teunbrand, #2785) label.padding argument geom_label() now supports inputs created margin() function (#5030). ScaleContinuous$get_breaks() now calls scales::zero_range() limits transformed space, rather data space (#5304). Scales throw informative messages (@teunbrand, #4185, #4258) scale_*_manual() named values argument now emits warning none names match values found data (@teunbrand, #5298). name argument scales now explicitly first argument (#5535) translate_shape_string() internal function now exported use extensions point layers (@teunbrand, #5191). improve width calculation bar plots empty factor levels, resolution() considers mapped_discrete values resolution 1 (@teunbrand, #5211) theme(), elements can specified rel() inherit unit-class objects relative fashion (@teunbrand, #3951). theme() now supports splicing list arguments (#5542). theme element hierarchy, parent elements strict subclass child elements now confer subclass upon children (#5457). New plot.tag.location theme() can control placement plot tag \"margin\", \"plot\" new \"panel\" option (#4297). coord_munch() can now close polygon shapes (@teunbrand, #3271) Aesthetics listed geom_*() stat_*() layers now point relevant documentation (@teunbrand, #5123). new argument axes facet_grid() facet_wrap() controls display axes interior panel positions. Additionally, axis.labels argument can used draw tick marks fully labelled axes (@teunbrand, #4064). coord_polar() can free scales facets (@teunbrand, #2815). get_guide_data() function can used extract position label information plot (#5004). Improve performance layers without positional scales (@zeehio, #4990) informative error mismatched direction/theme(legend.direction = ...) arguments (#4364, #4930).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-5-0","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.5.0","text":"Fixed regression guide_legend() linewidth key size wasn’t adapted width lines (#5160). guide_bins(), title longer arbitrarily becomes offset guide long labels. guide_colourbar() guide_coloursteps() merge properly one aesthetics dropped (#5324). using geom_dotplot(binaxis = \"x\") discrete y-variable, dots now stacked y-position rather 0 (@teunbrand, #5462) stat_count() treats x unique manner unique() (#4609). plot’s title, subtitle caption now obey horizontal text margins (#5533). Contour functions fail options(\"OutDec\") . (@eliocamp, #5555). Lines linewidth = NA now dropped geom_sf() (#5204). ggsave() longer sometimes creates new directories, now controlled new create.dir argument (#5489). Legend titles longer take space ’ve removed setting legend.title = element_blank() (@teunbrand, #3587). resolution() small tolerance, preventing spuriously small resolutions due rounding errors (@teunbrand, #2516). stage() now works correctly, even aesthetics scales (#5408) stat_ydensity() incomplete groups calculates default width parameter stably (@teunbrand, #5396) size argument annotation_logticks() deprecated favour linewidth argument (#5292). Binned scales now treat NAs limits way continuous scales (#5355). Binned scales work better trans = \"reverse\" (#5355). Integers valid input theme arguments expect numeric input (@teunbrand, #5369) Legends scale_*_manual() can show NA values values named vector (@teunbrand, #5214, #5286). Fixed bug coord_sf() graticule lines didn’t obey panel.grid.major’s linewidth setting (@teunbrand, #5179) Fixed bug annotation_logticks() suitable tick positions found (@teunbrand, #5248). default width geom_bar() now based panel-wise resolution data, rather global resolution (@teunbrand, #4336). stat_align() now applied per panel instead globally, preventing issues facets different ranges (@teunbrand, #5227). stacking bug stat_align() fixed (@teunbrand, #5176). stat_contour() stat_contour_filled() now warn remove duplicated coordinates (@teunbrand, #5215). guide_coloursteps() guide_bins() sort breaks (#5152).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"internal-changes-3-5-0","dir":"Changelog","previous_headings":"","what":"Internal changes","title":"ggplot2 3.5.0","text":"ScaleContinuous$get_breaks() method longer censors computed breaks. ggplot object now contains $layout points Layout ggproto object used ggplot_build.ggplot method. exposed package developers may extend behaviour Layout ggproto object without needing develop entirely new ggplot_build method (@jtlandis, #5077). Guide building now part ggplot_build() instead ggplot_gtable() allow guides observe unmapped data (#5483). titleGrob() function refactored faster less complicated. scales_*() functions related managing class implemented methods class, rather stray functions (#1310).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-344","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.4","title":"ggplot2 3.4.4","text":"CRAN release: 2023-10-12 hotfix release adapts change r-devel’s base::.atomic() upcoming retirement maptools. fortify() sp objects (e.g., SpatialPolygonsDataFrame) now deprecated removed soon support upcoming retirement rgdal, rgeos, maptools. advance whole removal, fortify(, region = ...) longer works version (@yutannihilation, #5244).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-343","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.3","title":"ggplot2 3.4.3","text":"CRAN release: 2023-08-14 hotfix release addresses version comparison change r-devel. user-facing breaking changes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-342","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.2","title":"ggplot2 3.4.2","text":"CRAN release: 2023-04-03 hotfix release anticipating changes r-devel, folds upkeep changes bug fixes well.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-3-4-2","dir":"Changelog","previous_headings":"","what":"Minor improvements","title":"ggplot2 3.4.2","text":"Various type checks messages standardised (@teunbrand, #4834). ggplot2 now uses scales::DiscreteRange scales::ContinuousRange, available write scale extensions scratch (@teunbrand, #2710). layer_data(), layer_scales() layer_grob() now default plot = last_plot() (@teunbrand, #5166). datetime_scale() scale constructor now exported use extension packages (@teunbrand, #4701).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-4-2","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.4.2","text":"update_geom_defaults() update_stat_defaults() now return properly classed objects updated docs (@dkahle, #5146). purposes checking required non-missing aesthetics, character vectors longer considered non-finite (@teunbrand, @4284). annotation_logticks() skips drawing ticks scale range non-finite instead throwing error (@teunbrand, #5229). Fixed spurious warnings weight used stat_bin_2d(), stat_boxplot(), stat_contour(), stat_bin_hex() stat_quantile() (@teunbrand, #5216). prevent changing plotting order, stat_sf() now computed per panel instead per group (@teunbrand, #4340). Fixed bug coord_sf() graticule lines didn’t obey panel.grid.major’s linewidth setting (@teunbrand, #5179). geom_text() drops observations angle = NA instead throwing error (@teunbrand, #2757).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-341","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.1","title":"ggplot2 3.4.1","text":"CRAN release: 2023-02-10 small release focusing fixing regressions 3.4.0 release minor polishes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-4-1","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.4.1","text":"computed variable y stat_ecdf() superseded ecdf prevent incorrect scale transformations (@teunbrand, #5113 #5112).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-4-1","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.4.1","text":"Added scale_linewidth_manual() scale_linewidth_identity() support linewidth aesthetic (@teunbrand, #5050). ggsave() warns multiple filenames given, writes first file (@teunbrand, #5114).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-4-1","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.4.1","text":"Fixed regression geom_hex() aesthetics replicated across bins (@thomasp85, #5037 #5044). Using two ordered factors facetting variables facet_grid(..., .table = FALSE) now throws warning instead error (@teunbrand, #5109). Fixed misbehaviour draw_key_boxplot() draw_key_crossbar() skewed key aspect ratio (@teunbrand, #5082). Fixed spurious warning weight aesthetic used stat_smooth() (@teunbrand based @clauswilke’s suggestion, #5053). lwd alias now correctly replaced linewidth instead size (@teunbrand based @clauswilke’s suggestion #5051). Fixed regression Coord$train_panel_guides() names guides dropped (@maxsutton, #5063). binned scales: Automatic breaks longer --bounds, automatic limits adjusted include breaks (@teunbrand, #5082). Zero-range limits longer throw error treated akin continuous scales zero-range limits (@teunbrand, #5066). trans = \"date\" trans = \"time\" transformations made compatible (@teunbrand, #4217).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-340","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.0","title":"ggplot2 3.4.0","text":"CRAN release: 2022-11-04 minor release focusing tightening internals ironing inconsistencies API. biggest change addition linewidth aesthetic takes sizing width line size. change, attempting non-breaking possible, potential change look plots. notable changes complete redo error warning messaging ggplot2 using cli package. Messaging now better contextualised easier identify layer error coming . Last, now made switch using vctrs package internally means support vctrs classes variables improve, along small gains rendering speed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-4-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.4.0","text":"linewidth aesthetic introduced supersedes size aesthetic scaling width lines line based geoms. size remain functioning deprecated geoms recommended update code reflect new aesthetic. geoms point sizing linewidth sizing (geom_pointrange() geom_sf) size now refers sizing points can leads visual change old code (@thomasp85, #3672) default line width polygons geom_sf() decreased 0.2 reflect usually used demarking borders thinner line better suited. change made since already induced visual change geom_sf() introduction linewidth aesthetic. dot-dot notation (..var..) stat(), superseded after_stat(), now formally deprecated (@yutannihilation, #3693). qplot() now formally deprecated (@yutannihilation, #3956). stage() now properly refers values without scale transformations stage after_stat. code requires scaled version values reason, apply transformation , e.g. sqrt() scale_{x,y}_sqrt() (@yutannihilation @teunbrand, #4155). Use rlang::hash() instead digest::digest(). update may lead changes automatic sorting legends. order enforce specific legend order use order argument guide. (@thomasp85, #4458) referring x backquoted expressions label_bquote() longer possible. ticks.linewidth frame.linewidth parameters guide_colourbar() now multiplied .pt like elsewhere ggplot2. can cause visual changes arguments defaults changes can restored previous behaviour adding / .pt (@teunbrand #4314). scale_*_viridis_b() now uses full range viridis scales (@gregleleu, #4737)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-4-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.4.0","text":"geom_col() geom_bar() gain new just argument. set 0.5 default; use just = 0/just = 1 place columns left/right axis breaks. (@wurli, #4899) geom_density() stat_density() now support bounds argument estimate density boundary correction (@echasnovski, #4013). ggplot now checks statistical transformations whether data columns dropped warns . stats intend drop data columns can declare new field dropped_aes. (@clauswilke, #3250) ... supports rlang::list2 dynamic dots public functions. (@mone27, #4764) theme() now strip.clip argument, can set \"\" prevent clipping strip text background borders (@teunbrand, #4118) geom_contour() now accepts function breaks argument (@eliocamp, #4652).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-bug-fixes-3-4-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and bug fixes","title":"ggplot2 3.4.0","text":"Fix bug position_jitter() infinity values dropped (@javlon, #4790). geom_linerange() now respects na.rm argument (#4927, @thomasp85) Improve support guide_axis() coord_trans() (@yutannihilation, #3959) Added stat_align() align data without common x-coordinates prior stacking. now default stat geom_area() (@thomasp85, #4850) Fix bug stat_contour_filled() break value differences certain number digits cause computations fail (@thomasp85, #4874) Secondary axis ticks now positioned precisely, removing small visual artefacts alignment grid ticks (@thomasp85, #3576) Improve stat_function documentation regarding xlim argument. (@92amartins, #4474) Fix various issues labels, breaks, limits, show.limits interact different binning guides (@thomasp85, #4831) Automatic break calculation now squishes scale limits domain transformation. allows scale_{x/y}_sqrt() find breaks 0 appropriate (@teunbrand, #980). Using multiple modified aesthetics correctly longer trigger warnings. used incorrectly, warning now report duplicated aesthetic instead NA (@teunbrand, #4707). aes() now supports !!! operator first two arguments (#2675). Thanks @yutannihilation @teunbrand draft implementations. Require rlang >= 1.0.0 (@billybarc, #4797) geom_violin() longer issues “collapsing unique ‘x’ values” warning (@bersbersbers, #4455) annotate() now documents unsupported geoms (geom_abline(), geom_hline() geom_vline()), warns requested (@mikmart, #4719) presidential dataset now includes Trump’s presidency (@bkmgit, #4703). position_stack() now works fully geom_text() (@thomasp85, #4367) geom_tile() now correctly recognises missing data xmin, xmax, ymin, ymax (@thomasp85 @sigmapi, #4495) geom_hex() now use binwidth stat_bin_hex() present, instead deriving (@thomasp85, #4580) geom_hex() now works non-linear coordinate systems (@thomasp85) Fixed bug throwing errors trying render empty plot secondary axes (@thomasp85, #4509) Axes now added correctly facet_wrap() .table = FALSE (@thomasp85, #4553) Better compatibility custom device functions ggsave() (@thomasp85, #4539) Binning scales now resilient calculated limits ends NaN transformations (@thomasp85, #4510) Strip padding facet_grid() now effect strip.placement = \"outside\" axis present strip panel (@thomasp85, #4610) Aesthetics length 1 now recycled 0 length data 0 (@thomasp85, #4588) Setting size = NA longer cause guide_legend() error (@thomasp85, #4559) Setting stroke NA geom_point() longer impair sizing points (@thomasp85, #4624) stat_bin_2d() now correctly recognises weight aesthetic (@thomasp85, #4646) geoms now consistent exposure linejoin lineend parameters, guide keys now respect settings (@thomasp85, #4653) geom_sf() now respects arrow parameter lines (@jakeruss, #4659) Updated documentation print.ggplot reflect returns original plot, result ggplot_build(). (@r2evans, #4390) scale_*_manual() longer displays extra legend keys, changes order, named values argument items data. display values legend instead, use scale_*_manual(values = vals, limits = names(vals)). (@teunbrand, @banfai, #4511, #4534) Updated documentation geom_contour() correctly reflect argument precedence bins binwidth. (@eliocamp, #4651) Dots geom_dotplot() now correctly aligned baseline stackratio != 1 stackdir != \"\" (@mjskay, #4614) Key glyphs geom_boxplot(), geom_crossbar(), geom_pointrange(), geom_linerange() now orientation-aware (@mjskay, #4732) Updated documentation geom_smooth() clearly describe effects fullrange parameter (@thoolihan, #4399).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-336","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.6","title":"ggplot2 3.3.6","text":"CRAN release: 2022-05-03 small release applying internal change comply R 4.2 deprecation default.stringsAsFactors(). user facing changes breaking changes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-335","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.5","title":"ggplot2 3.3.5","text":"CRAN release: 2021-06-25 small release focusing fixing couple untenable issues surfaced 3.3.4 release Revert changes made #4434 (apply transform intercept geom_abline()) introduced undesirable issues far worse bug fixed (@thomasp85, #4514) Fixes issue ggsave() producing emf/wmf files (@yutannihilation, #4521) Warn grDevices specific arguments passed ragg devices (@thomasp85, #4524) Fix issue coord_sf() reporting non-linear even data provided projected coordinates (@clauswilke, #4527)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-334","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.4","title":"ggplot2 3.3.4","text":"CRAN release: 2021-06-16 larger patch release fixing huge number bugs introduces small selection feature refinements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"features-3-3-4","dir":"Changelog","previous_headings":"","what":"Features","title":"ggplot2 3.3.4","text":"Alt-text can now added plot using alt label, .e + labs(alt = ...). Currently alt text automatically propagated, plan integrate Shiny, RMarkdown, tools future. (@thomasp85, #4477) Add support BrailleR package creating descriptions plot rendered (@thomasp85, #4459) coord_sf() now argument default_crs specifies coordinate reference system (CRS) non-sf layers scale/coord limits. argument defaults NULL, means non-sf layers assumed projected coordinates, prior ggplot2 versions. Setting default_crs = sf::st_crs(4326) provides simple way interpret x y positions longitude latitude, regardless CRS used coord_sf(). Authors extension packages implementing stat_sf()-like functionality encouraged look source code stat_sf()’s compute_group() function see provide scale-limit hints coord_sf() (@clauswilke, #3659). ggsave() now uses ragg render raster output ragg available. also handles custom devices sets default unit (e.g. ragg::agg_png) correctly (@thomasp85, #4388) ggsave() now returns saved file location invisibly (#3379, @eliocamp). Note , side effect, unofficial hack + ggsave() longer works (#4513). scale arguments limits, breaks, minor_breaks, labels, rescaler oob now accept purrr style lambda notation (@teunbrand, #4427). true as_labeller() (therefore also labeller()) (@netique, #4188). Manual scales now allow named vectors passed values contain fewer elements existing data. Elements present values set NA (@thomasp85, #3451) Date datetime position scales support --bounds (oob) arguments control limits affect data outside limits (@teunbrand, #4199).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"fixes-3-3-4","dir":"Changelog","previous_headings":"","what":"Fixes","title":"ggplot2 3.3.4","text":"Fix bug after_stat() after_scale() refer aesthetics ’s specified plot-global mapping (@yutannihilation, #4260). Fix bug annotate_logticks() cause error used together coord_flip() (@thomasp85, #3954) Fix bug geom_abline() resulted intercept subjected transformation y scale (@thomasp85, #3741) Extent range line created geom_abline() line ending visible large linewidths (@thomasp85, #4024) Fix bug geom_dotplot() dots positioned wrong stackgroups = TRUE (@thomasp85, #1745) Fix calculation confidence interval locfit smoothing geom_smooth() (@topepo, #3806) Fix bug geom_text() \"outward\" \"inward\" justification angle values reversed (@aphalo, #4169, #4447) ggsave() now sets default background match fill value plot.background theme element (@karawoo, #4057) now deprecated specify guides( = FALSE) scale_*(guide = FALSE) remove guide. Please use guides( = \"none\") scale_*(guide = \"none\") instead (@yutannihilation, #4097) Fix bug guide_bins() keys disappear guide reversed (@thomasp85, #4210) Fix bug guide_coloursteps() repeat terminal bins breaks coincided limits scale (@thomasp85, #4019) Make sure default labels default mappings doesn’t overwrite default labels explicit mappings (@thomasp85, #2406) Fix bug labeller() parsing turned .multiline = FALSE (@thomasp85, #4084) Make sure label_bquote() access calling environment evaluating labels (@thomasp85, #4141) Fix bug layer implementation introduced new state first render lead different look rendered second time (@thomasp85, #4204) Fix bug legend justification justification lost legend dimensions exceeded available size (@thomasp85, #3635) Fix bug position_dodge2() NA values thee data cause error (@thomasp85, #2905) Make sure position_jitter() creates jittering independent whether called name constructor (@thomasp85, #2507) Fix bug position_jitter() different jitters applied different position aesthetics axis (@thomasp85, #2941) Fix bug qplot() supplying c(NA, NA) axis limits (@thomasp85, #4027) Remove cross-inheritance default discrete colour/fill scales check type aesthetic function output type function (@thomasp85, #4149) Fix bug scale_[x|y]_date() custom breaks functions resulted fractional dates get misaligned (@thomasp85, #3965) Fix bug scale_[x|y]_datetime() specified timezone ignored scale (@thomasp85, #4007) Fix issue sec_axis() throw warnings absence secondary breaks (@thomasp85, #4368) stat_bin()’s computed variable width now documented (#3522). stat_count() now computes width based full dataset instead per group (@thomasp85, #2047) Extended stat_ecdf() calculate cdf either x y instead y (@jgjl, #4005) Fix bug stat_summary_bin() one requested number bins created (@thomasp85, #3824) drop groups stat_ydensity() fewer two data points throw warning (@andrewwbutler, #4111). Fixed bug strip assembly theme strip.text = element_blank() plots faceted multi-layered strips (@teunbrand, #4384). Using theme(aspect.ratio = ...) together free space facet_grid() now correctly throws error (@thomasp85, #3834) Fixed bug labeller() .default passed as_labeller() labellers specified naming faceting variables. (@waltersom, #4031) Updated style example code (@rjake, #4092) ggplot2 now requires R >= 3.3 (#4247). ggplot2 now uses rlang::check_installed() check suggested package installed, offer install package continuing (#4375, Improved error hint piping ggplot object facet function (#4379, @mitchelloharawild).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-333","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.3","title":"ggplot2 3.3.3","text":"CRAN release: 2020-12-30 small patch release mainly intended address changes R CRAN. changes licensing model ggplot2 MIT license. Update ggplot2 licence MIT license (#4231, #4232, #4233, #4281) Use vdiffr conditionally ggplot2 can tested systems without vdiffr Update tests work new .equal() defaults R >4.0.3 Fixed bug guide_bins() mistakenly ignore override.aes argument (@yutannihilation, #4085).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-332","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.2","title":"ggplot2 3.3.2","text":"CRAN release: 2020-06-19 small release focusing fixing regressions introduced 3.3.1. Added outside option annotation_logticks() places tick marks outside plot bounds. (#3783, @kbodwin) annotation_raster() adds support native rasters. large rasters, native rasters render significantly faster arrays (@kent37, #3388) Facet strips now dedicated position-dependent theme elements (strip.text.x.top, strip.text.x.bottom, strip.text.y.left, strip.text.y.right) inherit strip.text.x strip.text.y, respectively. consequence, theme stylings now need applied position-dependent elements rather parent elements. change already introduced ggplot2 3.3.0 listed changelog. (@thomasp85, #3683) Facets now handle layers containing data (@yutannihilation, #3853). newly added geom geom_density_2d_filled() associated stat stat_density_2d_filled() can draw filled density contours (@clauswilke, #3846). newly added geom_function() now recommended use conjunction /instead stat_function(). addition, stat_function() now works transformed y axes, e.g. scale_y_log10(), plots containing data layers (@clauswilke, #3611, #3905, #3983). Fixed bug geom_sf() caused problems legend-type autodetection (@clauswilke, #3963). Support graphics devices use file argument instead fileneame ggsave() (@bwiernik, #3810) Default discrete color scales now configurable options() ggplot2.discrete.colour ggplot2.discrete.fill. set character vector colour codes (list character vectors) sufficient length, colours used default scale. See help(scale_colour_discrete) details examples (@cpsievert, #3833). Default continuous colour scales (.e., options() ggplot2.continuous.colour ggplot2.continuous.fill, inform type argument scale_fill_continuous() scale_colour_continuous()) now accept function, allows control default continuous_scale()s (@cpsievert, #3827). bug fixed stat_contour() calculating breaks based bins argument (@clauswilke, #3879, #4004). Data columns can now contain Vector S4 objects, widely used Bioconductor project. (@teunbrand, #3837)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-331","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.1","title":"ggplot2 3.3.1","text":"CRAN release: 2020-05-28 small release code change. removes malicious links site got hijacked readme pkgdown site.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-330","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.0","title":"ggplot2 3.3.0","text":"CRAN release: 2020-03-05 minor release contain range substantial new features, along standard bug fixes. release contains visual breaking changes, along breaking changes extension developers due shift internal representation position scales axes. user breaking changes included. release also adds Dewey Dunnington (@paleolimbot) core team.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-3-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.3.0","text":"user-facing breaking changes, change internal representations extension developers may relied , along breaking visual changes may cause visual tests downstream packages fail. panel_params field Layout now contains list list ViewScale objects, describing trained coordinate system scales, instead list object used . extensions use field likely break, unit tests checks aspects . element_text() now issues warning vectorized arguments provided, colour = c(\"red\", \"green\", \"blue\"). use discouraged officially supported (@clauswilke, #3492). Changed theme_grey() setting legend key creates border (NA) rather drawing white one. (@annennenne, #3180) geom_ribbon() now draws separate lines upper lower intervals colour mapped. Similarly, geom_area() geom_density() now draw upper lines case default. want old-style full stroking, use outline.type = \"full\" (@yutannihilation, #3503 / @thomasp85, #3708).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-3-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.3.0","text":"evaluation time aesthetics can now controlled finer degree. after_stat() supersedes use stat() ..var..-notation, joined after_scale() allow mapping scaled aesthetic values. Remapping aesthetic now supported stage(), can map data variable stat aesthetic, remap aesthetic something else statistical transformation (@thomasp85, #3534) coord_*() functions xlim ylim arguments now accept vectors NA placeholder minimum maximum value (e.g., ylim = c(0, NA) zoom y-axis 0 maximum value observed data). mimics behaviour limits argument continuous scale functions (@paleolimbot, #2907). Allowed reversing discrete scales re-writing get_limits() (@AnneLyng, #3115) geoms stats direction (.e. x y axes different interpretation), can now freely choose direction, instead relying coord_flip(). direction deduced aesthetic mapping, can also specified directly new orientation argument (@thomasp85, #3506). Position guides can now customized using new guide_axis(), can passed position scale_*() functions via guides(). new axis guide (guide_axis()) comes arguments check.overlap (automatic removal overlapping labels), angle (easy rotation axis labels), n.dodge (dodge labels multiple rows/columns) (@paleolimbot, #3322). new scale type added, allows binning aesthetics scale level. versions position non-position aesthetics comes two new guides (guide_bins guide_coloursteps) (@thomasp85, #3096) scale_x_continuous() scale_y_continuous() gains n.breaks argument guiding number automatic generated breaks (@thomasp85, #3102) Added stat_contour_filled() geom_contour_filled(), compute draw filled contours gridded data (@paleolimbot, #3044). geom_contour() stat_contour() now use isoband package compute contour lines. complete parameter (undocumented unused least four years) removed (@paleolimbot, #3044). Themes gained two new parameters, plot.title.position plot.caption.position, can used customize plot title/subtitle plot caption positioned relative overall plot (@clauswilke, #3252).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensions-3-3-0","dir":"Changelog","previous_headings":"","what":"Extensions","title":"ggplot2 3.3.0","text":"Geom now gains setup_params() method line ggproto classes (@thomasp85, #3509) newly added function register_theme_elements() now allows developers extension packages define new theme elements place ggplot2 element tree (@clauswilke, #2540).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-bug-fixes-3-3-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and bug fixes","title":"ggplot2 3.3.0","text":"coord_trans() now draws second axes accepts xlim, ylim, expand arguments bring feature parity coord_cartesian(). xtrans ytrans arguments deprecated version 1.0.1 favour x y removed (@paleolimbot, #2990). coord_trans() now calculates breaks using expanded range (previously calculated using unexpanded range, resulted differences plots made coord_trans() made coord_cartesian()). expansion discrete axes coord_trans() also updated behaves identically coord_cartesian() (@paleolimbot, #3338). expand_scale() deprecated favour expansion() setting expand argument x y scales (@paleolimbot). geom_abline(), geom_hline(), geom_vline() now issue informative warnings supplied set aesthetics (.e., slope, intercept, yintercept, /xintercept) mapped aesthetics (.e., data /mapping). Fix bug geom_raster() squeezed image went outside scale limits (#3539, @thomasp85) geom_sf() now determines legend type automatically (@microly, #3646). geom_sf() now removes rows can’t plotted due NA aesthetics (#3546, @thomasp85) geom_sf() now applies alpha linestring geometries (#3589, @yutannihilation). gg_dep() deprecated (@perezp44, #3382). Added function ggplot_add.() lists created (), allowing lists added ggplot objects (#2734, @Maschette) ggplot2 longer depends reshape2, means longer (recursively) needs plyr, stringr, stringi packages. Increase default nbin guide_colourbar() place ticks precisely (#3508, @yutannihilation). manual_scale() now matches values order breaks whenever values unnamed vector. Previously, unnamed values match limits scale ignore order breaks provided. Note may change appearance plots previously relied unordered behaviour (#2429, @idno0001). scale_manual_*(limits = ...) now actually limits scale (#3262, @yutannihilation). Fix bug show.legend named logical vector (#3461, @yutannihilation). Added weight aesthetic option stat_density() made scaling weights default (@annennenne, #2902) stat_density2d() can now take adjust parameter scale default bandwidth. (#2860, @haleyjeppson) stat_smooth() uses REML default, method = \"gam\" gam’s method specified (@ikosmidis, #2630). stacking text calculating labels y axis stat_summary() now works (@ikosmidis, #2709) stat_summary() related functions now support rlang-style lambda functions (#3568, @dkahle). data mask pronoun, .data, now stripped default labels. Addition partial themes plots made predictable; stepwise addition individual partial themes now equivalent addition multple theme elements (@clauswilke, #3039). Facets now don’t fail even variable spec available layers (@yutannihilation, #2963).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-321","dir":"Changelog","previous_headings":"","what":"ggplot2 3.2.1","title":"ggplot2 3.2.1","text":"CRAN release: 2019-08-10 patch release fixing regressions introduced 3.2.0 well fixing unit tests broke due upstream changes. position_stack() longer changes order input data. Changes internal behaviour geom_ribbon() made reordering problematic ribbons spanned y = 0 (#3471) Using qplot() single positional aesthetic longer title non-specified scale \"NULL\" (#3473) Fixes unit tests sf graticule labels caused changes sf","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-320","dir":"Changelog","previous_headings":"","what":"ggplot2 3.2.0","title":"ggplot2 3.2.0","text":"CRAN release: 2019-06-16 minor release emphasis internal changes make ggplot2 faster consistent. interface changes affect aesthetics plot minor ways, potentially break code extension developers relied internals changed. release also sees addition Hiroaki Yutani (@yutannihilation) core developer team. release R 3.6, ggplot2 now requires R version least 3.2, tidyverse committed support 5 major versions R.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-2-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.2.0","text":"Two patches (#2996 #3050) fixed minor rendering problems. cases, visual changes subtle difficult see naked eye. However, changes detected vdiffr package, therefore package developers use vdiffr test visual correctness ggplot2 plots regenerate reference images. cases, ggplot2 now produces warning error code previously produced plot output. cases, previous plot output accidental, plotting code uses ggplot2 API way lead undefined behavior. Examples include missing group aesthetic geom_boxplot() (#3316), annotations across multiple facets (#3305), using aesthetic mappings drawing ribbons geom_ribbon() (#3318).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-2-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.2.0","text":"release includes range internal changes speeds plot generation. None changes user facing break code, general ggplot2 feel much faster. changes includes, limited : Caching ascent descent dimensions text avoid recalculating every title. Using faster data.frame constructor well faster indexing data.frames Removing plyr dependency, replacing plyr functions faster equivalents. geom_polygon() can now draw polygons holes using new subgroup aesthetic. functionality requires R 3.6.0 (@thomasp85, #3128) Aesthetic mappings now accept functions return NULL (@yutannihilation, #2997). stat_function() now accepts rlang/purrr style anonymous functions fun parameter (@dkahle, #3159). geom_rug() gains “outside” option allow moving rug tassels outside plot area (@njtierney, #3085) length option allow changing length rug lines (@daniel-wells, #3109). geoms now take key_glyph paramter allows users customize legend keys drawn (@clauswilke, #3145). addition, new key glyph timeseries provided draw nice legends time series (@mitchelloharawild, #3145).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensions-3-2-0","dir":"Changelog","previous_headings":"","what":"Extensions","title":"ggplot2 3.2.0","text":"Layers now new member function setup_layer() called beginning plot building process access original input data plot object built. function allows creation custom layers autogenerate aesthetic mappings based input data filter input data form. time , feature exported, enabled development new layer type, layer_sf() (see next item). special-purpose layer types may added future (@clauswilke, #2872). new layer type layer_sf() can auto-detect auto-map sf geometry columns data. used extension developers writing new sf-based geoms stats (@clauswilke, #3232). x0 y0 now recognized positional aesthetics get scaled used extension geoms stats (@thomasp85, #3168) Continuous scale limits now accept functions accept default limits return adjusted limits. makes possible write function e.g. ensures limits always multiple 100, regardless data (@econandrew, #2307).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-bug-fixes-3-2-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and bug fixes","title":"ggplot2 3.2.0","text":"cut_width() now accepts ... pass arguments base::cut.default() like cut_number() cut_interval() already (@cderv, #3055) coord_map() now can axes top right (@karawoo, #3042). coord_polar() now correctly rescales secondary axis (@linzi-sg, #3278) coord_sf(), coord_map(), coord_polar() now squash -Inf Inf min max plot (@yutannihilation, #2972). coord_sf() graticule lines now drawn thickness panel grid lines coord_cartesian(), seting panel grid lines element_blank() now also works coord_sf() (@clauswilke, #2991, #2525). economics data regenerated. leads changes values columns (especially psavert), importantly, strips grouping attributes economics_long. element_line() now fills closed arrows (@yutannihilation, #2924). Facet strips left side plots now clipping turned , preventing text running strip borders looking thicker strips (@karawoo, #2772 #3061). ggplot2 now works Turkish locale (@yutannihilation, #3011). Clearer error messages inappropriate aesthetics (@clairemcwhite, #3060). ggplot2 longer attaches external packages using functions depend packages suggested imported ggplot2. affected functions include geom_hex(), stat_binhex(), stat_summary_hex(), geom_quantile(), stat_quantile(), map_data() (@clauswilke, #3126). geom_area() geom_ribbon() now sort data along x-axis setup_data() method rather part draw_group() (@thomasp85, #3023) geom_hline(), geom_vline(), geom_abline() now throw warning user supplies xintercept, yintercept, slope value mapping (@RichardJActon, #2950). geom_rug() now works coord_flip() (@has2k1, #2987). geom_violin() longer throws error quantile lines fall outside violin polygon (@thomasp85, #3254). guide_legend() guide_colorbar() now use appropriate spacing legend key glyphs legend text even legend title missing (@clauswilke, #2943). Default labels now generated consistently; e.g., symbols longer get backticks, long expressions abbreviated ... (@yutannihilation, #2981). -Inf layers now ignored picking scale (@yutannihilation, #3184). Diverging Brewer colour palette now use correct mid-point colour (@dariyasydykova, #3072). scale_color_continuous() now points scale_colour_continuous() handle type = \"viridis\" documentation states (@hlendway, #3079). scale_shape_identity() now works correctly guide = \"legend\" (1, #3029) scale_continuous now draw axis line even length breaks 0 (@thomasp85, #3257) stat_bin() now error number bins exceeds 1e6 avoid accidentally freezing user session (@thomasp85). sec_axis() now places ticks accurately using nonlinear transformations (@dpseidel, #2978). facet_wrap() facet_grid() now automatically remove NULL facet specs, accept empty specs (@yutannihilation, #3070, #2986). stat_bin() now handles data one unique value (@yutannihilation #3047). sec_axis() now accepts functions well formulas (@yutannihilation, #3031). New theme elements allowing different ticks lengths axis. instance, can used inwards ticks x-axis (axis.ticks.length.x) outwards ticks y-axis (axis.ticks.length.y) (@pank, #2935). arguments Stat*$compute_layer() Position*$compute_layer() now renamed always match ones Stat$compute_layer() Position$compute_layer() (@yutannihilation, #3202). geom_*() stat_*() now accepts purrr-style lambda notation (@yutannihilation, #3138). geom_tile() geom_rect() now draw rectangles without notches corners. style corner can controlled linejoin parameters (@yutannihilation, #3050).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-310","dir":"Changelog","previous_headings":"","what":"ggplot2 3.1.0","title":"ggplot2 3.1.0","text":"CRAN release: 2018-10-25","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-1-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.1.0","text":"minor release breaking changes kept minimum. End users ggplot2 unlikely encounter issues. However, items developers ggplot2 extensions aware . additional details, see also discussion accompanying issue #2890. non-user-facing internal code (specifically aes() function aesthetics argument scale functions), ggplot2 now always uses British spelling aesthetics containing word “colour”. users specify “color” aesthetic automatically renamed “colour”. renaming also applied non-standard aesthetics contain word “color”. example, “point_color” renamed “point_colour”. convention makes easier support British American spelling novel, non-standard aesthetics, may require adjustment packages previously introduced non-standard color aesthetics using American spelling. new function standardise_aes_names() provided case extension writers need perform renaming code (@clauswilke, #2649). Functions generate functions (closures) now force arguments used generated functions, avoid hard--catch errors. may affect users manual scales (scale_colour_manual(), scale_fill_manual(), etc.) depend incorrect behavior (@krlmlr, #2807). Coord objects now function backtransform_range() returns panel range data coordinates. change may affect developers custom coords, now implement function. may also affect developers custom geoms use range() function. applications, backtransform_range() may appropriate (@clauswilke, #2821).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-1-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.1.0","text":"coord_sf() much improved customization axis tick labels. Labels can now set manually, two new parameters, label_graticule label_axes, can used specify graticules label side plot (@clauswilke, #2846, #2857, #2881). Two new geoms geom_sf_label() geom_sf_text() can draw labels text sf objects. hood, new stat_sf_coordinates() calculates x y coordinates coordinates sf geometries. can customize calculation method via fun.geometry argument (@yutannihilation, #2761).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-fixes-3-1-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and fixes","title":"ggplot2 3.1.0","text":"benchplot() now uses tidy evaluation (@dpseidel, #2699). error message compute_aesthetics() now provides names aesthetics mismatched lengths, rather aesthetics (@karawoo, #2853). faceted plots, data longer internally reordered. makes safer feed data columns aes() parameters geoms stats. However, remains discouraged (@clauswilke, #2694). coord_sf() now also understands clip argument, just like coords (@clauswilke, #2938). fortify() now displays informative error message grouped_df() objects dplyr installed (@jimhester, #2822). geom_*() now display informative error message required aesthetics missing (@dpseidel, #2637 #2706). geom_boxplot() now understands width parameter even used non-standard stat, stat_identity() (@clauswilke, #2893). geom_hex() now understands size linetype aesthetics (@mikmart, #2488). geom_hline(), geom_vline(), geom_abline() now work properly coord_trans() (@clauswilke, #2149, #2812). geom_text(..., parse = TRUE) now correctly renders expected number items instead silently dropping items empty expressions, e.g. empty string ““. expression spans multiple lines, take just first line drop rest. issue also fixed geom_label() axis labels geom_sf() (@slowkow, #2867). geom_sf() now respects lineend, linejoin, linemitre parameters lines polygons (@alistaire47, #2826). ggsave() now exits without creating new graphics device previously none open (@clauswilke, #2363). labs() now named arguments title, subtitle, caption, tag. Also, labs() now accepts tidyeval (@yutannihilation, #2669). position_nudge() now robust nudges direction requested. enables, example, horizontal nudging boxplots (@clauswilke, #2733). sec_axis() dup_axis() now return appropriate breaks secondary axis applied log transformed scales (@dpseidel, #2729). sec_axis() now works expected used combination tidy eval (@dpseidel, #2788). scale_*_date(), scale_*_time() scale_*_datetime() can now display secondary axis one--one transformation primary axis, implemented using sec.axis argument scale constructor (@dpseidel, #2244). stat_contour(), stat_density2d(), stat_bin2d(), stat_binhex() now calculate normalized statistics including nlevel, ndensity, ncount. Also, stat_density() now includes calculated statistic nlevel, alias scaled, better match syntax stat_bin() (@bjreisman, #2679).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-300","dir":"Changelog","previous_headings":"","what":"ggplot2 3.0.0","title":"ggplot2 3.0.0","text":"CRAN release: 2018-07-03","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-0-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.0.0","text":"ggplot2 now supports/uses tidy evaluation (described ). major change breaks number packages; made breaking change important make ggplot2 programmable, consistent rest tidyverse. best general (detailed) introduction tidy evaluation can found meta programming chapters Advanced R. primary developer facing change aes() now contains quosures (expression + environment pairs) rather symbols, ’ll need take different approach extracting information need. common symptom change errors “undefined columns selected” “invalid ‘type’ (list) argument” (#2610). previous version, constants (like aes(x = 1) aes(colour = \"smoothed\")) stored . version ggplot2, need describe mapping string, use quo_name() (generate single-line strings; longer expressions may abbreviated) quo_text() (generate non-abbreviated strings may span multiple lines). need extract value variable instead use rlang::eval_tidy(). may want condition (packageVersion(\"ggplot2\") <= \"2.2.1\") code can work released development versions ggplot2. recognise big change ’re already familiar rlang, ’s lot learn. stuck, need help, please reach https://forum.posit.co/. Error: Column y must 1d atomic vector list Internally, ggplot2 now uses .data.frame(tibble::as_tibble(x)) convert list data frame. improves ggplot2’s support list-columns (needed sf support), small cost: can longer use matrix-columns. Note unlike tibble still allow column vectors returned base::scale() widespread use. Error: one expression parsed Previously aes_string(x = c(\"\", \"b\", \"c\")) silently returned aes(x = ). Now clear error. Error: data must uniquely named duplicate columns layer data contains columns identical names error thrown. earlier versions first occurring column chosen silently, potentially masking wrong data chosen. Error: Aesthetics must either length 1 data Layers stricter columns combine single data frame. aesthetic now must either length data frame single value. makes silent recycling errors much less likely. Error: coord_* doesn’t support free scales Free scales work selected coordinate systems; previously ’d get incorrect plot. Error f(…) : unused argument (range = c(0, 1)) oob argument scale set function takes single argument; needs take two arguments (x, range). Error: unused argument (output) function guide_train() now optional parameter aesthetic allows override aesthetic setting scale. make code work released development versions ggplot2 appropriate, add aesthetic = NULL guide_train() method signature. , inside function, replace scale$aesthetics[1], aesthetic %||% scale$aesthetics[1]. (%||% operator defined rlang package). long-deprecated subset argument layer() removed.","code":"# old guide_train.legend <- function(guide, scale) {...} # new guide_train.legend <- function(guide, scale, aesthetic = NULL) {...} # old setNames(list(scale$map(breaks)), scale$aesthetics[1]) # new setNames(list(scale$map(breaks)), aesthetic %||% scale$aesthetics[1])"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"tidy-evaluation-3-0-0","dir":"Changelog","previous_headings":"","what":"Tidy evaluation","title":"ggplot2 3.0.0","text":"aes() now supports quasiquotation can use !!, !!!, :=. replaces aes_() aes_string() now soft-deprecated (remain around long time). facet_wrap() facet_grid() now support vars() inputs. Like dplyr::vars(), helper quotes inputs supports quasiquotation. instance, can now supply faceting variables like : facet_wrap(vars(, cyl)) instead facet_wrap(~+ cyl). Note formula interface going away deprecated. vars() simply meant make easier create functions around facet_wrap() facet_grid(). first two arguments facet_grid() become rows cols now support vars() inputs. Note however took special care ensure complete backward compatibility. change facet_grid(vars(cyl), vars(, vs)) equivalent facet_grid(cyl ~ + vs), facet_grid(cols = vars(, vs)) equivalent facet_grid(. ~ + vs). One nice aspect new interface can now easily supply names: facet_grid(vars(Cylinder = cyl), labeller = label_both) give nice label titles facets. course, names can unquoted usual tidy eval syntax.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"sf-3-0-0","dir":"Changelog","previous_headings":"Tidy evaluation","what":"sf","title":"ggplot2 3.0.0","text":"ggplot2 now full support sf geom_sf() coord_sf(): supports simple features, automatically aligns CRS across layers, sets correct aspect ratio, draws graticule.","code":"nc <- sf::st_read(system.file(\"shape/nc.shp\", package = \"sf\"), quiet = TRUE) ggplot(nc) + geom_sf(aes(fill = AREA))"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-0-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.0.0","text":"ggplot2 now works R 3.1 onwards, uses vdiffr package visual testing. cases, accidentally using %>% instead + generate informative error (#2400). New syntax calculated aesthetics. Instead using aes(y = ..count..) can (!) use aes(y = stat(count)). stat() real function documentation hopefully make part ggplot2 less confusing (#2059). stat() particularly nice complex calculations need specify : aes(y = stat(count / max(count))), rather aes(y = ..count.. / max(..count..)) New tag label adding identification tags plots, typically used labelling subplot letter. Add tag labs(tag = \"\"), style plot.tag theme element, control position plot.tag.position theme setting (@thomasp85).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"layers-geoms-stats-and-position-adjustments-3-0-0","dir":"Changelog","previous_headings":"New features","what":"Layers: geoms, stats, and position adjustments","title":"ggplot2 3.0.0","text":"geom_segment() geom_curve() new arrow.fill parameter allows specify separate fill colour closed arrowheads (@hrbrmstr @clauswilke, #2375). geom_point() friends can now take shapes strings instead integers, e.g. geom_point(shape = \"diamond\") (@daniel-barnett, #2075). position_dodge() gains preserve argument allows control whether total width x value preserved (current default), ensure width single element preserved (many people want) (#1935). New position_dodge2() provides enhanced dodging boxplots. Compared position_dodge(), position_dodge2() compares xmin xmax values determine elements overlap, spreads overlapping elements evenly within region overlap. position_dodge2() now default position adjustment geom_boxplot(), handles varwidth = TRUE, considered geoms future. padding parameter adds small amount padding elements (@karawoo, #2143) reverse parameter allows reverse order placement (@karawoo, #2171). New stat_qq_line() makes easy add simple line Q-Q plot, makes easier judge fit theoretical distribution (@nicksolomon).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"scales-and-guides-3-0-0","dir":"Changelog","previous_headings":"New features","what":"Scales and guides","title":"ggplot2 3.0.0","text":"Improved support mapping date/time variables alpha, size, colour, fill aesthetics, including date_breaks date_labels arguments (@karawoo, #1526), new scale_alpha() variants (@karawoo, #1526). Improved support ordered factors. Ordered factors throw warning mapped shape (unordered factors ), throw warnings mapped size alpha (unordered factors ). Viridis used default colour fill scale ordered factors (@karawoo, #1526). expand argument scale_*_continuous() scale_*_discrete() now accepts separate expansion values lower upper range limits. expansion limits can specified using convenience function expand_scale(). Separate expansion limits may useful bar charts, e.g. one wants bottom bars flush x axis still leave (automatically calculated amount ) space : can also useful line charts, e.g. counts time, one wants ’hard’ lower limit y = 0 leave upper limit unspecified (perhaps differing panels), extra space highest point line (symmetrical limits, extra space highest point cases cause lower limit negative). old syntax expand argument , course, continue work (@huftis, #1669). scale_colour_continuous() scale_colour_gradient() now controlled global options ggplot2.continuous.colour ggplot2.continuous.fill. can set \"gradient\" (default) \"viridis\" (@karawoo). New scale_colour_viridis_c()/scale_fill_viridis_c() (continuous) scale_colour_viridis_d()/scale_fill_viridis_d() (discrete) make easy use Viridis colour scales (@karawoo, #1526). Guides geom_text() now accept custom labels guide_legend(override.aes = list(label = \"foo\")) (@brianwdavis, #2458).","code":"ggplot(mtcars) + geom_bar(aes(x = factor(cyl))) + scale_y_continuous(expand = expand_scale(mult = c(0, .1)))"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"margins-3-0-0","dir":"Changelog","previous_headings":"New features","what":"Margins","title":"ggplot2 3.0.0","text":"Strips gain margins sides default. means fully justify text edge strip, need also set margins 0 (@karawoo). Rotated strip labels now correctly understand hjust vjust parameters angles (@karawoo). Strip labels now understand justification relative direction text, meaning y facets, strip text can placed either end strip using hjust (@karawoo). Legend titles labels get little extra space around , prevents legend titles overlapping legend large font sizes (@karawoo, #1881).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extension-points-3-0-0","dir":"Changelog","previous_headings":"","what":"Extension points","title":"ggplot2 3.0.0","text":"New autolayer() S3 generic (@mitchelloharawild, #1974). similar autoplot() produces layers rather complete plots. Custom objects can now added using + ggplot_add method defined class object (@thomasp85). Theme elements can now subclassed. Add merge_element method control properties inherited parent element. Add element_grob method define elements rendered grobs (@thomasp85, #1981). Coords gained new extension mechanisms. existing coord extension, need revise specification train() method. now called setup_panel_params() (better reflecting actually ) now arguments scale_x, scale_y (x y scales respectively) param, list plot specific parameters generated setup_params(). formerly called scale_details (coords), panel_ranges (layout) panel_scales (geoms) now consistently called panel_params (#1311). parameters coord vary panel panel. ggplot_build() ggplot_gtable() now generics, ggplot-subclasses can define additional behavior build stage. guide_train(), guide_merge(), guide_geom(), guide_gengrob() now exported needed want design guide. currently documented; use risk (#2528). scale_type() generic now exported documented. Use want extend ggplot2 work new type vector.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"faceting-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Faceting","title":"ggplot2 3.0.0","text":"facet_grid() gives informative error message try use variable rows cols (#1928). facet_grid() facet_wrap() give better error messages attempt use unsupported coord free scales (#2049). label_parsed() works (#2279). can now style background horizontal vertical strips independently strip.background.x strip.background.y theme settings (#2249).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"scales-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Scales","title":"ggplot2 3.0.0","text":"discrete_scale() documentation now inherits shared definitions continuous_scale() (@alistaire47, #2052). guide_colorbar() shows colours scale (@has2k1, #2343). scale_identity() produces legends default (#2112). Tick marks secondary axes strong transformations accurately placed (@thomasp85, #1992). Missing line types now reliably generate missing lines (standard warning) (#2206). Legends now ignore set aesthetics length one (#1932). colour fill scales now aesthetics argument can used set aesthetic(s) scale works . makes possible apply colour scale colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\") (@clauswilke). Three new generic scales work aesthetic set aesthetics: scale_continuous_identity(), scale_discrete_identity(), scale_discrete_manual() (@clauswilke). scale_*_gradient2() now consistently omits points outside limits rescaling limits enforced (@foo-bar-baz-qux, #2230).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"layers-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Layers","title":"ggplot2 3.0.0","text":"geom_label() now correctly produces unbordered labels label.size 0, even saving PDF (@bfgray3, #2407). layer() gives considerably better error messages incorrectly specified geom, stat, position (#2401). layers use , linemitre now defaults 10 (instead 1) better match base R. geom_boxplot() now supplies default value x aesthetic present (@foo-bar-baz-qux, #2110). geom_density() drops groups fewer two data points throws warning. groups two data points, density values now calculated stats::density (@karawoo, #2127). geom_segment() now also takes linejoin parameter. allows control appearance segments, especially useful plotting thick arrows (@Ax3man, #774). geom_smooth() now reports formula used method = \"auto\" (@davharris #1951). geom_smooth() now orders x aesthetic, making easier pass pre-computed values without manual ordering (@izahn, #2028). also now knows ymin ymax aesthetics (#1939). legend correctly reflects status se argument used stats default (@clauswilke, #1546). geom_tile() now interprets width height correctly (1, #2510). position_jitter() position_jitterdodge() gain seed argument allows specification random seed reproducible jittering (@krlmlr, #1996 @slowkow, #2445). stat_density() better behaviour groups dropped small (#2282). stat_summary_bin() now understands breaks parameter (@karawoo, #2214). stat_bin() now accepts functions binwidth. allows better binning faceting along variables different ranges (@botanize). stat_bin() geom_histogram() now sum correctly using weight aesthetic (@jiho, #1921). stat_bin() uses correct scaling computed variable ndensity (@timgoodman, #2324). stat_bin() stat_bin_2d() now properly handle breaks parameter scales transformed (@has2k1, #2366). update_geom_defaults() update_stat_defaults() allow American spelling aesthetic parameters (@foo-bar-baz-qux, #2299). show.legend parameter now accepts named logical vector hide/show aesthetics legend (@tutuchan, #1798). Layers now silently ignore unknown aesthetics value NULL (#1909).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"coords-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Coords","title":"ggplot2 3.0.0","text":"Clipping plot panel now configurable, clip argument coordinate systems, e.g. coord_cartesian(clip = \"\") (@clauswilke, #2536). Like scales, coordinate systems now give message ’re replacing existing coordinate system (#2264). coord_polar() now draws secondary axis ticks labels (@dylan-stark, #2072), can draw radius axis right (@thomasp85, #2005). coord_trans() now generates warning transformation generates non-finite values (@foo-bar-baz-qux, #2147).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"themes-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Themes","title":"ggplot2 3.0.0","text":"Complete themes now always override elements default theme (@has2k1, #2058, #2079). Themes now set default grid colour panel.grid rather individually panel.grid.major panel.grid.minor individually. makes slightly easier customise theme (#2352). Fixed bug setting strips element_blank() (@thomasp85). Axes positioned top right can now customize ticks lines separately (@thomasp85, #1899). Built-themes gain parameters base_line_size base_rect_size control default sizes line rectangle elements (@karawoo, #2176). Default themes use rel() set line widths (@baptiste). Themes tweaked visual consistency graceful behavior changing base font size. absolute heights widths replaced heights widths proportional base font size. One relative font size eliminated (@clauswilke). height descenders now calculated solely font metrics doesn’t change specific letters string. fixes minor alignment issues plot titles, subtitles, legend titles (#2288, @clauswilke).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"guides-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Guides","title":"ggplot2 3.0.0","text":"guide_colorbar() configurable: tick marks color bar frame can now styled arguments ticks.colour, ticks.linewidth, frame.colour, frame.linewidth, frame.linetype (@clauswilke). guide_colorbar() now uses legend.spacing.x legend.spacing.y correctly, can handle multi-line titles. Minor tweaks made guide_legend() make sure two legend functions behave similarly possible (@clauswilke, #2397 #2398). theme elements legend.title legend.text now respect settings margin, hjust, vjust (@clauswilke, #2465, #1502). Non-angle parameters label.theme title.theme can now set guide_legend() guide_colorbar() (@clauswilke, #2544).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"other-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Other","title":"ggplot2 3.0.0","text":"fortify() gains method tbls (@karawoo, #2218). ggplot gains method grouped_dfs adds .group variable, computes unique value group. Use aes(group = .group) (#2351). ggproto() produces objects class c(\"ggproto\", \"gg\"), allowing informative error message adding layers, scales, ggproto objects (@jrnold, #2056). ggsave()’s DPI argument now supports 3 string options: “retina” (320 DPI), “print” (300 DPI), “screen” (72 DPI) (@foo-bar-baz-qux, #2156). ggsave() now uses full argument names avoid partial match warnings (#2355), correctly restores previous graphics device several graphics devices open (#2363). print.ggplot() now returns original ggplot object, instead output ggplot_build(). Also, object returned ggplot_build() now class \"ggplot_built\" (#2034). map_data() now works even purrr loaded (tidyverse#66). New functions summarise_layout(), summarise_coord(), summarise_layers() summarise layout, coordinate systems, layers built ggplot object (#2034, @wch). provides tested API (e.g.) shiny can depend . Updated startup messages reflect new resources (#2410, @mine-cetinkaya-rundel).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-221","dir":"Changelog","previous_headings":"","what":"ggplot2 2.2.1","title":"ggplot2 2.2.1","text":"CRAN release: 2016-12-30 Fix usage structure(NULL) R-devel compatibility (#1968).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-220","dir":"Changelog","previous_headings":"","what":"ggplot2 2.2.0","title":"ggplot2 2.2.0","text":"CRAN release: 2016-11-11","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"subtitle-and-caption-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Subtitle and caption","title":"ggplot2 2.2.0","text":"Thanks @hrbrmstr plots now subtitles captions, can set subtitle caption arguments ggtitle() labs(). can control appearance theme settings plot.caption plot.subtitle. main plot title now left-aligned better work better subtitle. caption right-aligned (@hrbrmstr).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"stacking-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Stacking","title":"ggplot2 2.2.0","text":"position_stack() position_fill() now sort stacking order match grouping order. allows control order grouping, ensures default legend matches plot (#1552, #1593). want opposite order (useful horizontal bars horizontal legend), can request reverse stacking using position = position_stack(reverse = TRUE) (#1837). position_stack() position_fill() now accepts negative values create stacks extending x-axis (#1691). position_stack() position_fill() gain vjust argument makes easy (e.g.) display labels middle stacked bars (#1821).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"layers-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Layers","title":"ggplot2 2.2.0","text":"geom_col() added complement geom_bar() (@hrbrmstr). uses stat=\"identity\" default, making y aesthetic mandatory. support stat_() provide fallback support binwidth parameter. Examples references functions updated demonstrate geom_col() usage. creating layer, ggplot2 warn use unknown aesthetic unknown parameter. Compared previous version, stricter aesthetics (previously message), less strict parameters (previously threw error) (#1585).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"facetting-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Facetting","title":"ggplot2 2.2.0","text":"facet system, well internal panel class, rewritten ggproto. Facets now extendable manner geoms stats, described vignette(\"extending-ggplot2\"). also added following new features. facet_grid() facet_wrap() now allow expressions faceting formulas (@DanRuderman, #1596). facet_wrap() results uneven number panels, axes now drawn underneath hanging panels (fixes #1607) Strips can now freely positioned facet_wrap() using strip.position argument (deprecates switch). relative order panel, strip, axis can now controlled theme setting strip.placement takes either inside (strip panel axis) outside (strip axis). theme option panel.margin deprecated favour panel.spacing clearly communicate intent.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensions-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Extensions","title":"ggplot2 2.2.0","text":"Unfortunately major oversight construction ggproto lead extensions capturing super object package build time, instead package run time (#1826). problem fixed, requires re-installation extension packages.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"scales-2-2-0","dir":"Changelog","previous_headings":"","what":"Scales","title":"ggplot2 2.2.0","text":"position x y axes can now changed using position argument scale_x_*scale_y_* can take top bottom, left right respectively. themes top right axes can modified using .top .right modifiers axis.text.* axis.title.*.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"continuous-scales-2-2-0","dir":"Changelog","previous_headings":"Scales","what":"Continuous scales","title":"ggplot2 2.2.0","text":"scale_x_continuous() scale_y_continuous() can now display secondary axis one--one transformation primary axis (e.g. degrees Celcius degrees Fahrenheit). secondary axis positioned opposite primary axis can controlled sec.axis argument scale constructor. Scales worry less breaks. breaks can computed, plot work instead throwing uninformative error (#791). particularly helpful facets free scales, panels contain data. Scales now warn transformation introduces infinite values (#1696).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"date-time-2-2-0","dir":"Changelog","previous_headings":"Scales","what":"Date time","title":"ggplot2 2.2.0","text":"scale_*_datetime() now supports time zones. use timezone attached variable default, can overridden timezone argument. New scale_x_time() scale_y_time() generate reasonable default breaks labels hms vectors (#1752).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"discrete-scales-2-2-0","dir":"Changelog","previous_headings":"Scales","what":"Discrete scales","title":"ggplot2 2.2.0","text":"treatment missing values discrete scales thoroughly overhauled (#1584). underlying principle can naturally represent missing values discrete variables (treating just like another level), default . principle applies : character vectors factors implicit NA factors explicit NA scales (position non-position.) Compared previous version ggplot2, three main changes: scale_x_discrete() scale_y_discrete() always show discrete NA, regardless source present, NAs shown discrete legends. discrete scales gain na.translate argument allows control whether NAs translated something can visualised, left missing. Note don’t translate (.e.  na.translate = FALSE) missing values passed layer, warning ’s dropping missing values. suppress warnings, ’ll also need add na.rm = TRUE layer call. also number smaller changes Correctly use scale expansion factors. Don’t preserve space dropped levels (#1638). issue one warning asking many levels (#1674). Unicode labels work better Windows (#1827). Warn used continuous data (#1589)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"themes-2-2-0","dir":"Changelog","previous_headings":"","what":"Themes","title":"ggplot2 2.2.0","text":"theme() constructor now named arguments rather ellipses. make autocomplete substantially useful. documentation (including examples) considerably improved. Built-themes visually homogeneous, match theme_grey better. (@jiho, #1679) computing height titles, ggplot2 now includes height descenders (.e. bits g y hang beneath baseline). improves margins around titles, particularly y axis label (#1712). also slightly increased inner margins axis titles, removed outer margins. Theme element inheritance now easier work modification now overrides default element_blank elements (#1555, #1557, #1565, #1567) Horizontal legends (.e. legends top bottom) horizontally aligned default (#1842). Use legend.box = \"vertical\" switch back previous behaviour. element_line() now takes arrow argument specify arrows end lines (#1740) number tweaks theme elements control legends: legend.justification now controls appearance plotting legend outside plot area. example, can use theme(legend.justification = \"top\") make legend align top plot. panel.margin legend.margin renamed panel.spacing legend.spacing respectively, better communicate intent (affect spacing legends panels, margins around ) legend.margin now controls margin around individual legends. New legend.box.background, legend.box.spacing, legend.box.margin control background, spacing, margin legend box (region contains legends).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-and-minor-improvements-2-2-0","dir":"Changelog","previous_headings":"","what":"Bug fixes and minor improvements","title":"ggplot2 2.2.0","text":"ggplot2 now imports tibble. ensures built-datasets print compactly even haven’t explicitly loaded tibble dplyr (#1677). Class aesthetic mapping preserved adding aes() objects (#1624). +.gg now works lists include data frames. annotation_x() now works absense global data (#1655) geom_*(show.legend = FALSE) now works guide_colorbar. geom_boxplot() gains new outlier.alpha (@jonathan-g) outlier.fill (@schloerke, #1787) parameters control alpha/fill outlier points independently alpha boxes. position_jitter() (hence geom_jitter()) now correctly computes jitter width/jitter supplied user (#1775, @has2k1). geom_contour() clearly describes inputs needs (#1577). geom_curve() respects lineend parameter (#1852). geom_histogram() stat_bin() understand breaks parameter . (#1665). floating point adjustment histogram bins now actually used - previously inadvertently ignored (#1651). geom_violin() longer transforms quantile lines alpha aesthetic (@mnbram, #1714). longer errors quantiles requested data zero range (#1687). trim = FALSE nice range allows density reach zero (extending range 3 bandwidths either side data) (#1700). geom_dotplot() works better faceting binning y-axis. (#1618, @has2k1). geom_hexbin() supports ..density.. (@mikebirdgeneau, #1688). geom_step() gives useful warning one data point layer (#1645). layer() gains new check.aes check.param arguments. allow geom/stat authors optional suppress checks known aesthetics/parameters. Currently used geom_blank() powers expand_limits() (#1795). stat_*() display better error message required aesthetics missing. stat_bin() stat_summary_hex() now accept length 1 binwidth (#1610) stat_density() gains new argument n, passed underlying function stats::density (“number equally spaced points density estimated”). (@hbuschme) stat_binhex() now returns count rather value (#1747) stat_ecdf() respects pad argument (#1646). stat_smooth() informs method chosen. also correctly calculates size largest group within facets. x y scales now symmetric regarding list aesthetics accept: xmin_final, xmax_final, xlower, xmiddle xupper now valid x aesthetics. Scale extensions can now override make_title make_sec_title methods let scale modify axis/legend titles. random stream now reset calling .onAttach() (#2409).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-210","dir":"Changelog","previous_headings":"","what":"ggplot2 2.1.0","title":"ggplot2 2.1.0","text":"CRAN release: 2016-03-01","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-2-1-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 2.1.0","text":"mapping aesthetic constant (e.g.  geom_smooth(aes(colour = \"loess\")))), default guide title name aesthetic (.e. “colour”), value (.e. “loess”) (#1431). layer() now accepts function data argument. function applied data passed ggplot() function must return data.frame (#1527, @thomasp85). general version deprecated subset argument. theme_update() now uses + operator instead %+replace%, unspecified values longer NULLed . theme_replace() preserves old behaviour desired (@oneillkza, #1519). stat_bin() overhauled use algorithm ggvis, considerably improved thanks advice Randy Prium (@rpruim). includes: Better arguments better algorithm determining origin. can now specify either boundary center bin. origin deprecated favour arguments. drop deprecated favour pad, adds extra 0-count bins either end (needed frequency polygons). geom_histogram() defaults pad = FALSE considerably improves default limits histogram, especially bins big (#1477). default algorithm (somewhat) better job picking nice widths origins across wider range input data. bins = n now gives histogram n bins, n + 1 (#1487).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-2-1-0","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 2.1.0","text":"\\donttest{} examples run. geom_() stat_() functions now consistent argument order: data + mapping, geom/stat/position, ..., specific arguments, arguments common layers (#1305). may break code previously relying partial name matching, long-term make ggplot2 easier use. particular, can now set n parameter geom_density2d() without partially matching na.rm (#1485). geoms colour fill, alpha affects fill (Reverts #1371, #1523). causing problems people. facet_wrap()/facet_grid() works multiple empty panels data (#1445). facet_wrap() correctly swaps nrow ncol faceting vertically (#1417). ggsave(\"x.svg\") now uses svglite produce svg (#1432). geom_boxplot() now understands outlier.color (#1455). geom_path() knows “solid” (just 1) represents solid line (#1534). geom_ribbon() preserves missing values correctly generate gap ribbon (#1549). geom_tile() accepts width height parameters (#1513). uses draw_key_polygon() better legend, including coloured outline (#1484). layer() now automatically adds na.rm parameter none explicitly supplied. position_jitterdodge() now works possible dodge aesthetics, e.g. color, linetype etc. instead based fill (@bleutner) position = \"nudge\" now works (although doesn’t anything useful) (#1428). default scale columns class “AsIs” now “identity” (#1518). scale_*_discrete() better defaults used purely continuous data (#1542). scale_size() warns used categorical data. scale_size(), scale_colour(), scale_fill() gain date date-time variants (#1526). stat_bin_hex() stat_bin_summary() now use underlying algorithm results consistent (#1383). stat_bin_hex() now accepts weight aesthetic. consistent related stats, output variable stat_bin_hex() now value instead count. stat_density() gains bw parameter makes easy get consistent smoothing facets (@jiho) stat-density-2d() longer ignores h parameter, now accepts bins binwidth parameters control number contours (#1448, @has2k1). stat_ecdf() better job adding padding -Inf/Inf, gains argument pad suppress padding needed (#1467). stat_function() gains xlim parameter (#1528). works discrete x values (#1509). stat_summary() preserves sorted x order avoids artefacts display results geom_smooth() (#1520). elements now inherit correctly themes except theme_void(). (@Katiedaisey, #1555) theme_void() completely void text facets legends still need labels. now visible (@jiho). can set legend key height width unit arithmetic objects (like 2 * unit(1, \"cm\")) (#1437). Eliminate spurious warning layer data aesthetics (#1451). Removed superfluous comma theme-defaults.r code (@jschoeley) Fixed compatibility issue ggproto R versions prior 3.1.2. (#1444) Fixed issue coord_map() fails given explicit parameters argument (@tdmcarthur, #1729) Fixed issue geom_errorbarh() required x aesthetic (#1933)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-200","dir":"Changelog","previous_headings":"","what":"ggplot2 2.0.0","title":"ggplot2 2.0.0","text":"CRAN release: 2015-12-18","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"major-changes-2-0-0","dir":"Changelog","previous_headings":"","what":"Major changes","title":"ggplot2 2.0.0","text":"ggplot longer throws error plot layers. Instead automatically adds geom_blank() (#1246). New cut_width() convenient replacement verbose plyr::round_any(), additional benefit offering finer control. New geom_count() convenient alias stat_sum(). Use overlapping points scatterplot. stat_sum() now defaults using counts instead proportions. New geom_curve() adds curved lines, similar specification geom_segment() (@veraanadi, #1088). Date datetime scales now date_breaks, date_minor_breaks date_labels arguments never need use long scales::date_breaks() scales::date_format(). geom_bar() now ’s stat, distinct stat_bin() also used geom_histogram(). geom_bar() now uses stat_count() counts values distinct value x (.e. bin data first). can useful want show exactly values used continuous variable. geom_point() gains stroke aesthetic controls border width shapes 21-25 (#1133, @SeySayux). size stroke additive point size = 5 stroke = 5 diameter 10mm. (#1142) New position_nudge() allows slightly offset labels (geoms) corresponding points (#1109). scale_size() now maps values area, radius. Use scale_radius() want old behaviour (recommended, except perhaps lines). New stat_summary_bin() works like stat_summary() binned data. ’s generalisation stat_bin() can compute aggregate, just counts (#1274). default mean_se() aggregation functions supplied (#1386). Layers now much stricter arguments - get error ’ve supplied argument isn’t aesthetic parameter. likely cause short-term pain long-term make much easier spot spelling mistakes errors (#1293). change break handful geoms/stats used ... pass additional arguments underlying computation. Now geom_smooth()/stat_smooth() geom_quantile()/stat_quantile() use method.args instead (#1245, #1289); stat_summary() (#1242), stat_summary_hex(), stat_summary2d() use fun.args.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensibility-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Extensibility","title":"ggplot2 2.0.0","text":"now official mechanism defining Stats, Geoms, Positions packages. See vignette(\"extending-ggplot2\") details. Geoms, Stats Positions now exported, can inherit making objects (#989). ggplot2 longer uses proto reference classes. Instead, now use ggproto, new OO system designed specifically ggplot2. Unlike proto RC, ggproto supports clean cross-package inheritance. Creating new OO system isn’t usually right way solve problem, ’m pretty sure necessary . Read vignette. aes_() replaces aes_q(). also supports formulas, concise SE version aes(carat, price) now aes_(~carat, ~price). may want use form packages, avoid spurious R CMD check warnings undefined global variables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"text-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Text","title":"ggplot2 2.0.0","text":"geom_text() overhauled make labelling data little easier. : nudge_x nudge_y arguments let offset labels corresponding points (#1120). check_overlap = TRUE provides simple way avoid overplotting labels: labels otherwise overlap omitted (#1039). hjust vjust can now character vectors: “left”, “center”, “right”, “bottom”, “middle”, “top”. New options include “inward” “outward” align text towards away center plot respectively. geom_label() works like geom_text() draws rounded rectangle underneath label (#1039). useful want label plots dense data.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"deprecated-features-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Deprecated features","title":"ggplot2 2.0.0","text":"little used aes_auto() deprecated. aes_q() replaced aes_() consistent SE versions NSE functions packages. order aesthetic officially deprecated. never really worked, poorly documented. stat position arguments qplot() deprecated. qplot() designed quick plots - need specify position stat, use ggplot() instead. theme setting axis.ticks.margin deprecated: now use margin property axis.text. stat_abline(), stat_hline() stat_vline() removed: never suitable use geom_abline() etc documented. show_guide renamed show.legend: accurately reflects (controls appearance layer legend), uses convention ggplot2 arguments (.e. . names). (Yes, know ’s inconsistent function names use _, ’s late change now.) number geoms renamed internally consistent: stat_binhex() stat_bin2d() renamed stat_bin_hex() stat_bin_2d() (#1274). stat_summary2d() renamed stat_summary_2d(), geom_density2d()/stat_density2d() renamed geom_density_2d()/stat_density_2d(). stat_spoke() now geom_spoke() since realised ’s reparameterisation geom_segment(). stat_bindot() removed ’s tightly coupled geom_dotplot(). happened use stat_bindot(), just change geom_dotplot() (#1194). defunct functions removed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"default-appearance-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Default appearance","title":"ggplot2 2.0.0","text":"default theme_grey() background colour changed “grey90” “grey92”: makes background little less visually prominent. Labels titles tweaked readability: Axes labels darker. Legend axis titles given visual treatment. default font size dropped 12 11. might surprised ’ve made default text size smaller already hard many people read. turns bug RStudio (fixed 0.99.724), shrunk text grid based graphics. resolved defaults seemed big eyes. spacing titles borders. Default margins scale theme font size, appearance larger font sizes considerably improved (#1228). alpha now affects fill colour aesthetics (#1371). element_text() gains margins argument allows add additional padding around text elements. help see ’s going use debug = TRUE display text region anchors. default font size geom_text() decreased 5mm (14 pts) 3.8 mm (11 pts) match new default theme sizes. diagonal line longer drawn bar rectangle legends. Instead, border tweaked visible, closely match size line drawn plot. geom_pointrange() geom_linerange() get vertical (horizontal) lines legend (#1389). default line size geom_smooth() increased 0.5 1 make easier see overlaid data. geom_bar() geom_rect() use slightly paler shade grey aren’t visually heavy. geom_boxplot() now colours outliers way boxes. geom_point() now uses shape 19 instead 16. looks much better default Linux graphics device. (’s slightly smaller old point, shouldn’t affect graphics significantly) Sizes ggplot2 measured mm. Previously converted pts (use grid) multiplying 72 / 25.4. However, grid uses printer’s points, Adobe (big pts), sizes now correctly multiplied 72.27 / 25.4. unlikely noticeably affect display, ’s technically correct (https://youtu./hou0lU8WMgo). default legend now allocate multiple rows (vertical) columns (horizontal) order make legend likely fit screen. can override nrow/ncol arguments guide_legend()","code":"p <- ggplot(mpg, aes(displ,hwy, colour = model)) + geom_point() p p + theme(legend.position = \"bottom\") # Previous behaviour p + guides(colour = guide_legend(ncol = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-and-updated-themes-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"New and updated themes","title":"ggplot2 2.0.0","text":"New theme_void() completely empty. ’s useful plots non- standard coordinates drawings (@jiho, #976). New theme_dark() dark background designed make colours pop (@jiho, #1018) theme_minimal() became slightly minimal removing axis ticks: labels now line directly beneath grid lines (@tomschloss, #1084) New theme setting panel.ontop (logical) make possible place background elements (.e., gridlines) top data. Best used transparent panel.background (@noamross. #551).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"labelling-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Labelling","title":"ggplot2 2.0.0","text":"facet labelling system updated many new features flexible interface (@lionel-). now works consistently across grid wrap facets. important user visible changes : facet_wrap() gains labeller option (#25). facet_grid() facet_wrap() gain switch argument display facet titles near axes. switched, labels become axes subtitles. switch can set “x”, “y” “” (latter grids) control margin switched. labellers (label_value() label_both()) also get new features: now offer multi_line argument control whether display composite facets (specified ~var1 + var2) one multiple lines. label_bquote() now refer directly names variables. change, can create math expressions depend one variable. math expression can specified either rows columns can also provide different expressions margin. consequence changes, referring x backquoted expressions deprecated. Similarly label_bquote(), labeller() now take .rows .cols arguments. addition, also takes .default. labeller() useful customise particular variables labelled. three additional arguments specify label variables specifically mentioned, respectively rows, columns . makes especially easy set project-wide labeller dispatcher can reused across plots. See documentation example. new labeller label_context() adapts number factors facetted . single factor, displays values, just . multiple factors composite margin (e.g. ~cyl + ), labels passed label_both(). way variables names displayed values help identifying . programming side, labeller API rewritten order offer control faceting multiple factors (e.g. formulae ~cyl + ). also means written custom labellers, need update version ggplot. Previously, labeller function take variable value arguments return character vector. Now, take data frame character vectors return list. input data frame one column per factor facetted column returned list becomes one line strip label. See documentation details. labels received labeller now contain metadata: margin (“type” attribute) whether come wrap grid facet (“facet” attribute). Note new as_labeller() function operator provides easy way transform existing function labeller function. existing function just needs take return character vector.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"documentation-2-0-0","dir":"Changelog","previous_headings":"","what":"Documentation","title":"ggplot2 2.0.0","text":"Improved documentation aes(), layer() much much . ’ve tried reduce use ... can see documentation one place rather integrate multiple pages. cases involved adding additional arguments geoms make clear can : geom_smooth() gains explicit method, se formula arguments. geom_histogram() gains binwidth, bins, origin right arguments. geom_jitter() gains width height arguments make easier control amount jittering without using lengthy position_jitter() function (#1116) Use qplot() examples minimised (#1123, @hrbrmstr). inline 2nd edition ggplot2 box, minimises use qplot() favour ggplot(). Tightly linked geoms stats (e.g. geom_boxplot() stat_boxplot()) now documented file can see arguments one place. Variations idea (e.g. geom_path(), geom_line(), geom_step()) also documented together. ’s now obvious can set binwidth parameter stat_bin_hex(), stat_summary_hex(), stat_bin_2d(), stat_summary_2d(). internals positions cleaned considerably. ’re unlikely notice external changes, although documentation little less confusing since positions now don’t list parameters never use.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"data-2-0-0","dir":"Changelog","previous_headings":"","what":"Data","title":"ggplot2 2.0.0","text":"datasets class tbl_df also use dplyr, get better print method. economics brought date 2015-04-01. New economics_long economics data long form. New txhousing dataset containing information Texas housing market. Useful examples need multiple time series, demonstrating model+vis methods. New luv_colours dataset contains locations built-colors() Luv space. movies moved package, ggplot2movies, large terribly useful. ’ve used movies dataset, ’ll now need explicitly load package library(ggplot2movies).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-and-minor-improvements-2-0-0","dir":"Changelog","previous_headings":"","what":"Bug fixes and minor improvements","title":"ggplot2 2.0.0","text":"partially matched arguments $ replaced full matches (@jimhester, #1134). ggplot2 now exports alpha() scales package (#1107), arrow() unit() grid (#1225). means don’t need attach scales/grid scales::/grid:: commonly used functions. aes_string() now parses character inputs. fixes bugs using numbers non default OutDec settings (#1045). annotation_custom() automatically adds unique id grob name, making easier plot multiple grobs name (e.g. grobs ggplot2 graphics) plot (#1256). borders() now accepts xlim ylim arguments specifying geographical region interest (@markpayneatwork, #1392). coord_cartesian() applies expansion factor limits scales. can suppress expand = FALSE (#1207). coord_trans() now works breaks suppressed (#1422). cut_number() gives error message number requested bins can created two unique values (#1046). Character labels facet_grid() longer (incorrectly) coerced factors. caused problems custom label functions (#1070). facet_wrap() facet_grid() now allow use non-standard variable names surrounding backticks (#1067). facet_wrap() carefully checks nrow ncol arguments ensure ’re specified correctly (@richierocks, #962) facet_wrap() gains dir argument control direction panels wrapped . default “h” horizontal. Use “v” vertical layout (#1260). geom_abline(), geom_hline() geom_vline() rewritten simpler behaviour consistent: stat_abline(), stat_hline() stat_vline() removed: never suitable use geom_abline() etc documented. geom_abline(), geom_vline() geom_hline() bound stat_identity() position_identity() Intercept parameters can longer set function. documented one file, since closely related. geom_bin2d() now let specify one dimension’s breaks exactly, without touching dimension’s default breaks (#1126). geom_crossbar() sets grouping correctly can display multiple crossbars one plot. also makes default fatten argument little bigger make middle line obvious (#1125). geom_histogram() geom_smooth() now inform default values per layer, rather per panel (#1220). geom_pointrange() gains fatten argument can control size point relative size line. geom_segment() annotations transforming scales (@BrianDiggs, #859). geom_smooth() longer chatty. want know default smoothing method , look documentation! (#1247) geom_violin() now ability draw quantile lines (@DanRuderman). ggplot() now captures parent frame use evaluation, rather always defaulting global environment. make ggplot suitable use situations (e.g. knitr) ggsave() simplified little make easier maintain. longer checks ’re printing ggplot2 object (now also works grid grob) (#970), always requires filename. Parameter device now supports character argument specify supported device use (‘pdf’, ‘png’, ‘jpeg’, etc.), correctly inferred file extension (example temporary filename supplied server side shiny apps) (@sebkopf, #939). longer opens graphics device one isn’t already open - annoying ’re running script (#1326). guide_colorbar() creates correct legend one color (@krlmlr, #943). guide_colorbar() longer fails legend empty - previously often masked misspecifications elsewhere plot (#967). New layer_data() function extracts data used plotting given layer. ’s mostly useful testing. User supplied minor_breaks can now supplied scale data, automatically transformed scale (#1385). can now suppress appearance axis/legend title (space allocated ) NULL scale_ function. use default label, use waiver() (#1145). Position adjustments longer warn potentially varying ranges problem rarely occurs practice currently lot false positives since don’t understand exactly FP criteria testing. scale_fill_grey() now uses red missing values. matches scale_colour_grey() makes obvious missing values lie. Override na.value. scale_*_gradient2() defaults using Lab colour space. scale_*_gradientn() now allows colours colors (#1290) scale_y_continuous() now also transforms lower, middle upper aesthetics used geom_boxplot(): affects geom_boxplot(stat = \"identity\") (#1020). Legends longer inherit aesthetics inherit.aes FALSE (#1267). lims() makes easy set limits axis (#1138). labels = NULL now works guide_legend() guide_colorbar(). (#1175, #1183). override.aes now works American aesthetic spelling, e.g. color Scales longer round data points improve performance colour palettes. Instead scales package now uses much faster colour interpolation algorithm (#1022). scale_*_brewer() scale_*_distiller() add new direction argument scales::brewer_pal, making easier change order colours (@jiho, #1139). scale_x_date() now clips dates outside limits way scale_x_continuous() (#1090). stat_bin() gains bins arguments, denotes number bins. Now can set bins=100 instead binwidth=0.5. Note breaks binwidth override (@tmshn, #1158, #102). stat_boxplot() warns continuous variable used x aesthetic without also supplying group aesthetic (#992, @krlmlr). stat_summary_2d() stat_bin_2d() now share exactly code determining breaks bins, binwidth, origin. stat_summary_2d() stat_bin_2d() now output tile/raster compatible form instead rect compatible form. Automatically computed breaks lead error transformations like “probit” inverse can map infinity (#871, @krlmlr) stat_function() now always evaluates function original scale. Previously computed function transformed scales, giving incorrect values (@BrianDiggs, #1011). strip_dots works anonymous functions within calculated aesthetics (e.g. aes(sapply(..density.., function(x) mean(x)))) (#1154, @NikNakk) theme() gains validate = FALSE parameter turn validation, hence store arbitrary additional data themes. (@tdhock, #1121) Improved calculation segments needed draw curve representing line plotted polar coordinates. cases, last segment multi-segment line drawn (@BrianDiggs, #952)","code":""}] +[{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"our-pledge","dir":"","previous_headings":"","what":"Our Pledge","title":"Contributor Covenant Code of Conduct","text":"members, contributors, leaders pledge make participation community harassment-free experience everyone, regardless age, body size, visible invisible disability, ethnicity, sex characteristics, gender identity expression, level experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, sexual identity orientation. pledge act interact ways contribute open, welcoming, diverse, inclusive, healthy community.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"our-standards","dir":"","previous_headings":"","what":"Our Standards","title":"Contributor Covenant Code of Conduct","text":"Examples behavior contributes positive environment community include: Demonstrating empathy kindness toward people respectful differing opinions, viewpoints, experiences Giving gracefully accepting constructive feedback Accepting responsibility apologizing affected mistakes, learning experience Focusing best just us individuals, overall community Examples unacceptable behavior include: use sexualized language imagery, sexual attention advances kind Trolling, insulting derogatory comments, personal political attacks Public private harassment Publishing others’ private information, physical email address, without explicit permission conduct reasonably considered inappropriate professional setting","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"enforcement-responsibilities","dir":"","previous_headings":"","what":"Enforcement Responsibilities","title":"Contributor Covenant Code of Conduct","text":"Community leaders responsible clarifying enforcing standards acceptable behavior take appropriate fair corrective action response behavior deem inappropriate, threatening, offensive, harmful. Community leaders right responsibility remove, edit, reject comments, commits, code, wiki edits, issues, contributions aligned Code Conduct, communicate reasons moderation decisions appropriate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"scope","dir":"","previous_headings":"","what":"Scope","title":"Contributor Covenant Code of Conduct","text":"Code Conduct applies within community spaces, also applies individual officially representing community public spaces. Examples representing community include using official e-mail address, posting via official social media account, acting appointed representative online offline event.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"enforcement","dir":"","previous_headings":"","what":"Enforcement","title":"Contributor Covenant Code of Conduct","text":"Instances abusive, harassing, otherwise unacceptable behavior may reported community leaders responsible enforcement codeofconduct@posit.co. complaints reviewed investigated promptly fairly. community leaders obligated respect privacy security reporter incident.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"enforcement-guidelines","dir":"","previous_headings":"","what":"Enforcement Guidelines","title":"Contributor Covenant Code of Conduct","text":"Community leaders follow Community Impact Guidelines determining consequences action deem violation Code Conduct:","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_1-correction","dir":"","previous_headings":"Enforcement Guidelines","what":"1. Correction","title":"Contributor Covenant Code of Conduct","text":"Community Impact: Use inappropriate language behavior deemed unprofessional unwelcome community. Consequence: private, written warning community leaders, providing clarity around nature violation explanation behavior inappropriate. public apology may requested.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_2-warning","dir":"","previous_headings":"Enforcement Guidelines","what":"2. Warning","title":"Contributor Covenant Code of Conduct","text":"Community Impact: violation single incident series actions. Consequence: warning consequences continued behavior. interaction people involved, including unsolicited interaction enforcing Code Conduct, specified period time. includes avoiding interactions community spaces well external channels like social media. Violating terms may lead temporary permanent ban.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_3-temporary-ban","dir":"","previous_headings":"Enforcement Guidelines","what":"3. Temporary Ban","title":"Contributor Covenant Code of Conduct","text":"Community Impact: serious violation community standards, including sustained inappropriate behavior. Consequence: temporary ban sort interaction public communication community specified period time. public private interaction people involved, including unsolicited interaction enforcing Code Conduct, allowed period. Violating terms may lead permanent ban.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"id_4-permanent-ban","dir":"","previous_headings":"Enforcement Guidelines","what":"4. Permanent Ban","title":"Contributor Covenant Code of Conduct","text":"Community Impact: Demonstrating pattern violation community standards, including sustained inappropriate behavior, harassment individual, aggression toward disparagement classes individuals. Consequence: permanent ban sort public interaction within community.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CODE_OF_CONDUCT.html","id":"attribution","dir":"","previous_headings":"","what":"Attribution","title":"Contributor Covenant Code of Conduct","text":"Code Conduct adapted Contributor Covenant, version 2.1, available https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. Community Impact Guidelines inspired [Mozilla’s code conduct enforcement ladder][https://github.com/mozilla/inclusion]. answers common questions code conduct, see FAQ https://www.contributor-covenant.org/faq. Translations available https://www.contributor-covenant.org/translations.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CONTRIBUTING.html","id":null,"dir":"","previous_headings":"","what":"Contributing to ggplot2 development","title":"Contributing to ggplot2 development","text":"goal guide help get contributing ggplot2 quickly possible. guide divided two main pieces: Filing bug report feature request issue. Suggesting change via pull request. Please note ggplot2 released Contributor Code Conduct. contributing project, agree abide terms.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CONTRIBUTING.html","id":"issues","dir":"","previous_headings":"","what":"Issues","title":"Contributing to ggplot2 development","text":"filing issue, important thing include minimal reproducible example can quickly verify problem, figure fix . three things need include make example reproducible: required packages, data, code. Packages loaded top script, ’s easy see ones example needs. easiest way include data use dput() generate R code recreate . example, recreate mtcars dataset R, ’d perform following steps: Run dput(mtcars) R Copy output reproducible script, type mtcars <- paste. even better can create data.frame() just handful rows columns still illustrates problem. Spend little bit time ensuring code easy others read: make sure ’ve used spaces variable names concise, informative use comments indicate problem lies best remove everything related problem. shorter code , easier understand. can check actually made reproducible example starting fresh R session pasting script . (Unless ’ve specifically asked , please don’t include output sessionInfo().)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/CONTRIBUTING.html","id":"pull-requests","dir":"","previous_headings":"","what":"Pull requests","title":"Contributing to ggplot2 development","text":"contribute change ggplot2, follow steps: Create branch git make changes. Push branch github issue pull request (PR). Discuss pull request. Iterate either accept PR decide ’s good fit ggplot2. steps described detail . might feel overwhelming first time get set , gets easier practice. get stuck point, please reach help ggplot2-dev mailing list. ’re familiar git github, please start reading https://r-pkgs.org/software-development-practices.html Pull requests evaluated seven point checklist: Motivation. pull request clearly concisely motivate need change. Unfortunately neither Winston much time work ggplot2 days, need describe problem show pull request solves concisely possible. Also include motivation NEWS new release ggplot2 comes ’s easy users see ’s changed. Add item top file use markdown formatting. news item end (@yourGithubUsername, #the_issue_number). related changes. submit pull request, please check make sure haven’t accidentally included unrelated changes. make harder see exactly ’s changed, evaluate unexpected side effects. PR corresponds git branch, expect submit multiple changes make sure create multiple branches. multiple changes depend , start first one don’t submit others first one processed. Use ggplot2 coding style. Please follow official tidyverse style. Maintaining consistent style across whole code base makes much easier jump code. ’re modifying existing ggplot2 code doesn’t follow style guide, separate pull request fix style greatly appreciated. ’re adding new parameters new function, ’ll also need document roxygen2. Make sure re-run devtools::document() code submitting. fixing bug adding new feature non-graphical function, please add testthat unit test. fixing bug visual output, please add visual test. (Instructions follow soon) ’re adding new graphical feature, please add short example appropriate function. seems like lot work don’t worry pull request isn’t perfect. ’s learning process members ggplot2 team hand help . pull request (“PR”) process, unless ’ve submitted past ’s unlikely pull request accepted . PRs require review approval least one member ggplot2 development team merge. Finally, remember ggplot2 mature package used thousands people. means ’s extremely difficult (.e. impossible) change existing functionality without breaking someone’s code (another package CRAN). Please don’t submit pull requests change existing behaviour. Instead, think can add new feature minimally invasive way.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":null,"dir":"","previous_headings":"","what":"Roles and responsibilities","title":"Roles and responsibilities","text":"project large community users contributors, team core developers, project lead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"users","dir":"","previous_headings":"","what":"Users","title":"Roles and responsibilities","text":"People create visualizations ggplot2 important members community; without users, project purpose. Users encouraged participate life project community much possible. User contributions help ensure project satisfying users’ needs. Common user activities include (limited ): evangelising project asking answering community forums providing moral support (‘thank ’ goes long way) Users continue engage project community often find becoming involved. users may go become contributors, described .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"contributors","dir":"","previous_headings":"","what":"Contributors","title":"Roles and responsibilities","text":"Contributors interact project GitHub filing new issues, improving existing issues, submitting pull requests. Anyone can become contributor: expectation commitment project, required set skills, selection process. obligation follow code conduct. Specific advice contributing project can found CONTRIBUTING.md.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"core-developers","dir":"","previous_headings":"","what":"Core developers","title":"Roles and responsibilities","text":"Core developers collectively responsible day--day development package, including responding issues reviewing pull requests. GitHub administrators package authors, means ability make changes project code, receive credit others cite package. core developers can modify code directly, ability rarely used. Instead, changes proposed pull requests, merged reviewed least one core developer. Changes API (especially breaking changes) must also approved project lead. Core developers recruited contributors. invitation join core team can extended anyone made major contribution, either small number large changes, consistent pattern smaller contributions. existing core developer can propose contributor invited core team emailing project lead. project lead confirm invitation core developers. core developers ggplot2 : Winston Chang Lionel Henry Thomas Lin Pedersen Kohske Takahashi Claus Wilke Kara Woo Hiroaki Yutani Dewey Dunnington Teun van den Brand core developers bound code conduct.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"project-lead","dir":"","previous_headings":"","what":"Project lead","title":"Roles and responsibilities","text":"project lead, Hadley Wickham, responsible : Setting, clearly communication strategic objectives project. Mediating conflicts amongst core developers. Ensuring project survives long term. project lead bound code conduct.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/GOVERNANCE.html","id":"decision-making-process","dir":"","previous_headings":"","what":"Decision-making process","title":"Roles and responsibilities","text":"project makes decisions according consensus model suggestions considered discussed community core developers, typically GitHub issues. consensus reached, project lead’s word final. community questions decision, project lead may review either uphold reverse .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/LICENSE.html","id":null,"dir":"","previous_headings":"","what":"MIT License","title":"MIT License","text":"Copyright (c) 2020 ggplot2 authors Permission hereby granted, free charge, person obtaining copy software associated documentation files (“Software”), deal Software without restriction, including without limitation rights use, copy, modify, merge, publish, distribute, sublicense, /sell copies Software, permit persons Software furnished , subject following conditions: copyright notice permission notice shall included copies substantial portions Software. SOFTWARE PROVIDED “”, WITHOUT WARRANTY KIND, EXPRESS IMPLIED, INCLUDING LIMITED WARRANTIES MERCHANTABILITY, FITNESS PARTICULAR PURPOSE NONINFRINGEMENT. EVENT SHALL AUTHORS COPYRIGHT HOLDERS LIABLE CLAIM, DAMAGES LIABILITY, WHETHER ACTION CONTRACT, TORT OTHERWISE, ARISING , CONNECTION SOFTWARE USE DEALINGS SOFTWARE.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"ggproto","dir":"Articles","previous_headings":"","what":"ggproto","title":"Extending ggplot2","text":"ggplot2 objects built using ggproto system object oriented programming. OO system used one place: ggplot2. mostly historical accident: ggplot2 started using proto needed mutable objects. well creation (briefly lived) mutatr, reference classes R6: proto game town. ggproto? Well turned add official extension mechanism ggplot2, found major problem caused problems proto objects extended different package (methods evaluated ggplot2, package extension added). tried converting R6, poor fit needs ggplot2. ’ve modified proto, ’ve first involved understanding exactly proto worked, secondly making sure changes didn’t affect users proto. ’s strange say, case inventing new OO system actually right answer problem! Fortunately Winston now good creating OO systems, took day come ggproto: maintains features proto ggplot2 needs, allowing cross package inheritance work. ’s quick demo ggproto action: majority ggplot2 classes immutable static: methods neither use modify state class. ’re mostly used convenient way bundling related methods together. create new geom stat, just create new ggproto inherits Stat, Geom override methods described .","code":"A <- ggproto(\"A\", NULL, x = 1, inc = function(self) { self$x <- self$x + 1 } ) A$x #> [1] 1 A$inc() A$x #> [1] 2 A$inc() A$inc() A$x #> [1] 4"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"the-simplest-stat","dir":"Articles","previous_headings":"Creating a new stat","what":"The simplest stat","title":"Extending ggplot2","text":"’ll start creating simple stat: one gives convex hull (c hull) set points. First create new ggproto object inherits Stat: two important components compute_group() method (computation), required_aes field, lists aesthetics must present order stat work. Next write layer function. Unfortunately, due early design mistake called either stat_() geom_(). better decision call layer_() functions: ’s accurate description every layer involves stat geom. layer functions follow form - specify defaults function arguments call layer() function, sending ... params argument. arguments ... either arguments geom (’re making stat wrapper), arguments stat (’re making geom wrapper), aesthetics set. layer() takes care teasing different parameters apart making sure ’re stored right place: (Note ’re writing package, ’ll either need call ggplot2::layer() explicitly, import layer() function package namespace.) layer function can try new stat: (’ll see later change defaults geom don’t need specify fill = NA every time.) ’ve written basic object, ggplot2 gives lot free. example, ggplot2 automatically preserves aesthetics constant within group: can also override default geom display convex hull different way:","code":"StatChull <- ggproto(\"StatChull\", Stat, compute_group = function(data, scales) { data[chull(data$x, data$y), , drop = FALSE] }, required_aes = c(\"x\", \"y\") ) stat_chull <- function(mapping = NULL, data = NULL, geom = \"polygon\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatChull, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + stat_chull(fill = NA, colour = \"black\") ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + stat_chull(fill = NA) ggplot(mpg, aes(displ, hwy)) + stat_chull(geom = \"point\", size = 4, colour = \"red\") + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"stat-parameters","dir":"Articles","previous_headings":"Creating a new stat","what":"Stat parameters","title":"Extending ggplot2","text":"complex stat computation. Let’s implement simple version geom_smooth() adds line best fit plot. create StatLm inherits Stat layer function, stat_lm(): StatLm inflexible parameters. might want allow user control model formula number points used generate grid. , add arguments compute_group() method wrapper function: Note don’t explicitly include new parameters arguments layer, ... get passed right place anyway. ’ll need document somewhere user knows . ’s brief example. Note @inheritParams ggplot2::stat_identity: automatically inherit documentation parameters also defined stat_identity(). stat_lm() must exported want people use . also consider exporting StatLm want people extend underlying object; done care.","code":"StatLm <- ggproto(\"StatLm\", Stat, required_aes = c(\"x\", \"y\"), compute_group = function(data, scales) { rng <- range(data$x, na.rm = TRUE) grid <- data.frame(x = rng) mod <- lm(y ~ x, data = data) grid$y <- predict(mod, newdata = grid) grid } ) stat_lm <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatLm, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + stat_lm() StatLm <- ggproto(\"StatLm\", Stat, required_aes = c(\"x\", \"y\"), compute_group = function(data, scales, params, n = 100, formula = y ~ x) { rng <- range(data$x, na.rm = TRUE) grid <- data.frame(x = seq(rng[1], rng[2], length = n)) mod <- lm(formula, data = data) grid$y <- predict(mod, newdata = grid) grid } ) stat_lm <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, n = 50, formula = y ~ x, ...) { layer( stat = StatLm, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(n = n, formula = formula, na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + stat_lm(formula = y ~ poly(x, 10)) + stat_lm(formula = y ~ poly(x, 10), geom = \"point\", colour = \"red\", n = 20) #' @export #' @inheritParams ggplot2::stat_identity #' @param formula The modelling formula passed to \\code{lm}. Should only #' involve \\code{y} and \\code{x} #' @param n Number of points used for interpolation. stat_lm <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, n = 50, formula = y ~ x, ...) { layer( stat = StatLm, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(n = n, formula = formula, na.rm = na.rm, ...) ) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"picking-defaults","dir":"Articles","previous_headings":"Creating a new stat","what":"Picking defaults","title":"Extending ggplot2","text":"Sometimes calculations performed complete dataset, group. useful picking sensible default values. example, want density estimate, ’s reasonable pick one bandwidth whole plot. following Stat creates variation stat_density() picks one bandwidth groups choosing mean “best” bandwidth group (theoretical justification , doesn’t seem unreasonable). override setup_params() method. ’s passed data list params, returns updated list. recommend using NULL default value. pick important parameters automatically, ’s good idea message() user (printing floating point parameter, using signif() show significant digits).","code":"StatDensityCommon <- ggproto(\"StatDensityCommon\", Stat, required_aes = \"x\", setup_params = function(data, params) { if (!is.null(params$bandwidth)) return(params) xs <- split(data$x, data$group) bws <- vapply(xs, bw.nrd0, numeric(1)) bw <- mean(bws) message(\"Picking bandwidth of \", signif(bw, 3)) params$bandwidth <- bw params }, compute_group = function(data, scales, bandwidth = 1) { d <- density(data$x, bw = bandwidth) data.frame(x = d$x, y = d$y) } ) stat_density_common <- function(mapping = NULL, data = NULL, geom = \"line\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, bandwidth = NULL, ...) { layer( stat = StatDensityCommon, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(bandwidth = bandwidth, na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, colour = drv)) + stat_density_common() #> Picking bandwidth of 0.345 ggplot(mpg, aes(displ, colour = drv)) + stat_density_common(bandwidth = 0.5)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"variable-names-and-default-aesthetics","dir":"Articles","previous_headings":"Creating a new stat","what":"Variable names and default aesthetics","title":"Extending ggplot2","text":"stat illustrates another important point. want make stat usable geoms, return variable called density instead y. can set default_aes automatically map density y, allows user override use different geoms: However, using stat area geom doesn’t work quite right. areas don’t stack top : density computed independently, estimated xs don’t line . can resolve issue computing range data setup_params().","code":"StatDensityCommon <- ggproto(\"StatDensity2\", Stat, required_aes = \"x\", default_aes = aes(y = after_stat(density)), compute_group = function(data, scales, bandwidth = 1) { d <- density(data$x, bw = bandwidth) data.frame(x = d$x, density = d$y) } ) ggplot(mpg, aes(displ, drv, colour = after_stat(density))) + stat_density_common(bandwidth = 1, geom = \"point\") ggplot(mpg, aes(displ, fill = drv)) + stat_density_common(bandwidth = 1, geom = \"area\", position = \"stack\") StatDensityCommon <- ggproto(\"StatDensityCommon\", Stat, required_aes = \"x\", default_aes = aes(y = after_stat(density)), setup_params = function(data, params) { min <- min(data$x) - 3 * params$bandwidth max <- max(data$x) + 3 * params$bandwidth list( bandwidth = params$bandwidth, min = min, max = max, na.rm = params$na.rm ) }, compute_group = function(data, scales, min, max, bandwidth = 1) { d <- density(data$x, bw = bandwidth, from = min, to = max) data.frame(x = d$x, density = d$y) } ) ggplot(mpg, aes(displ, fill = drv)) + stat_density_common(bandwidth = 1, geom = \"area\", position = \"stack\") ggplot(mpg, aes(displ, drv, fill = after_stat(density))) + stat_density_common(bandwidth = 1, geom = \"raster\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises","dir":"Articles","previous_headings":"Creating a new stat","what":"Exercises","title":"Extending ggplot2","text":"Extend stat_chull compute alpha hull, alphahull package. new stat take alpha argument. Modify final version StatDensityCommon allow user specify min max parameters. ’ll need modify layer function compute_group() method. Note: careful adding parameters layer function. following names col, color, pch, cex, lty, lwd, srt, adj, bg, fg, min, max intentionally renamed accommodate base graphical parameter names. example, value passed min layer appears ymin setup_params list params. recommended avoid using names layer parameters. Compare contrast StatLm ggplot2::StatSmooth. key differences make StatSmooth complex StatLm?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-a-new-geom","dir":"Articles","previous_headings":"","what":"Creating a new geom","title":"Extending ggplot2","text":"’s harder create new geom new stat also need know grid. ggplot2 built top grid, ’ll need know basics drawing grid. ’re serious adding new geom, ’d recommend buying R graphics Paul Murrell. tells everything need know drawing grid.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"a-simple-geom","dir":"Articles","previous_headings":"Creating a new geom","what":"A simple geom","title":"Extending ggplot2","text":"’s easiest start simple example. code simplified version geom_point(): similar defining new stat. always need provide fields/methods four pieces shown : required_aes character vector lists aesthetics user must provide. default_aes lists aesthetics default values. draw_key provides function used draw key legend. can see list build key functions ?draw_key draw_panel() magic happens. function takes three arguments returns grid grob. called panel. ’s complicated part described detail . draw_panel() three arguments: data: data frame one column aesthetic. panel_params: list per-panel parameters generated coord. consider opaque data structure: don’t look inside , just pass along coord methods. coord: object describing coordinate system. need use panel_params coord together transform data coords <- coord$transform(data, panel_params). creates data frame position variables scaled range 0–1. take data call grid grob function. (Transforming non-Cartesian coordinate systems quite complex - ’re best transforming data form accepted existing ggplot2 geom passing .)","code":"GeomSimplePoint <- ggproto(\"GeomSimplePoint\", Geom, required_aes = c(\"x\", \"y\"), default_aes = aes(shape = 19, colour = \"black\"), draw_key = draw_key_point, draw_panel = function(data, panel_params, coord) { coords <- coord$transform(data, panel_params) grid::pointsGrob( coords$x, coords$y, pch = coords$shape, gp = grid::gpar(col = coords$colour) ) } ) geom_simple_point <- function(mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( geom = GeomSimplePoint, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_simple_point()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"collective-geoms","dir":"Articles","previous_headings":"Creating a new geom","what":"Collective geoms","title":"Extending ggplot2","text":"Overriding draw_panel() appropriate one graphic element per row. cases, want graphic element per group. example, take polygons: row gives one vertex polygon. case, instead override draw_group(). following code makes simplified version GeomPolygon: things note : override draw_group() instead draw_panel() want one polygon per group, one polygon per row. data contains two fewer points, ’s point trying draw polygon, return nullGrob(). graphical equivalent NULL: ’s grob doesn’t draw anything doesn’t take space. Note units: x y always drawn “native” units. (default units pointGrob() native, didn’t need change ). lwd measured points, ggplot2 uses mm, need multiply adjustment factor .pt. might want compare real GeomPolygon. ’ll see overrides draw_panel() uses tricks make polygonGrob() produce multiple polygons one call. considerably complicated, gives better performance.","code":"GeomSimplePolygon <- ggproto(\"GeomPolygon\", Geom, required_aes = c(\"x\", \"y\"), default_aes = aes( colour = NA, fill = \"grey20\", linewidth = 0.5, linetype = 1, alpha = 1 ), draw_key = draw_key_polygon, draw_group = function(data, panel_params, coord) { n <- nrow(data) if (n <= 2) return(grid::nullGrob()) coords <- coord$transform(data, panel_params) # A polygon can only have a single colour, fill, etc, so take from first row first_row <- coords[1, , drop = FALSE] grid::polygonGrob( coords$x, coords$y, default.units = \"native\", gp = grid::gpar( col = first_row$colour, fill = scales::alpha(first_row$fill, first_row$alpha), lwd = first_row$linewidth * .pt, lty = first_row$linetype ) ) } ) geom_simple_polygon <- function(mapping = NULL, data = NULL, stat = \"chull\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( geom = GeomSimplePolygon, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_simple_polygon(aes(colour = class), fill = NA)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"inheriting-from-an-existing-geom","dir":"Articles","previous_headings":"Creating a new geom","what":"Inheriting from an existing Geom","title":"Extending ggplot2","text":"Sometimes just want make small modification existing geom. case, rather inheriting Geom can inherit existing subclass. example, might want change defaults GeomPolygon work better StatChull: doesn’t allow use different geoms stat, seems appropriate since convex hull primarily polygonal feature.","code":"GeomPolygonHollow <- ggproto(\"GeomPolygonHollow\", GeomPolygon, default_aes = aes(colour = \"black\", fill = NA, linewidth = 0.5, linetype = 1, alpha = NA) ) geom_chull <- function(mapping = NULL, data = NULL, position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatChull, geom = GeomPolygonHollow, data = data, mapping = mapping, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_chull()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises-1","dir":"Articles","previous_headings":"Creating a new geom","what":"Exercises","title":"Extending ggplot2","text":"Compare contrast GeomPoint GeomSimplePoint. Compare contrast GeomPolygon GeomSimplePolygon.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"geoms-and-stats-with-multiple-orientation","dir":"Articles","previous_headings":"","what":"Geoms and Stats with multiple orientation","title":"Extending ggplot2","text":"layers specific orientation. geom_bar() e.g. bars along one axis, geom_line() sort input one axis, etc. original approach using geoms orientation add coord_flip() plot switch position x y axes. Following ggplot2 v3.3 geoms natively work orientations without coord_flip(). mechanism layer try guess orientation mapped data, take direction user using orientation parameter. replicate functionality new stats geoms ’s steps take. look boxplot layer example instead creating new one scratch.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"omnidirectional-stats","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Omnidirectional stats","title":"Extending ggplot2","text":"actual guessing orientation happen setup_params() using has_flipped_aes() helper: Following call flip_data() make sure data horizontal orientation. rest code can simply assume data specific orientation. thing happens setup_data(): data flipped (needed), manipulated, flipped back returned. computation, sandwiching flip_data() used well, right data returned also get flipped_aes column denoting data flipped . allows stat communicate geom orientation already determined.","code":"StatBoxplot$setup_params #> #> #> function (...) #> setup_params(..., self = self) #> #> #> function (self, data, params) #> { #> params$flipped_aes <- has_flipped_aes(data, params, main_is_orthogonal = TRUE, #> group_has_equal = TRUE, main_is_optional = TRUE) #> data <- flip_data(data, params$flipped_aes) #> has_x <- !(is.null(data$x) && is.null(params$x)) #> has_y <- !(is.null(data$y) && is.null(params$y)) #> if (!has_x && !has_y) { #> cli::cli_abort(\"{.fn {snake_class(self)}} requires an {.field x} or {.field y} aesthetic.\") #> } #> params$width <- params$width %||% (resolution(data$x %||% #> 0, discrete = TRUE) * 0.75) #> if (!is_mapped_discrete(data$x) && is.double(data$x) && !has_groups(data) && #> any(data$x != data$x[1L])) { #> cli::cli_warn(c(\"Continuous {.field {flipped_names(params$flipped_aes)$x}} aesthetic\", #> i = \"did you forget {.code aes(group = ...)}?\")) #> } #> params #> } StatBoxplot$setup_data #> #> #> function (...) #> setup_data(..., self = self) #> #> #> function (self, data, params) #> { #> data <- flip_data(data, params$flipped_aes) #> data$x <- data$x %||% 0 #> data <- remove_missing(data, na.rm = params$na.rm, vars = \"x\", #> name = \"stat_boxplot\") #> flip_data(data, params$flipped_aes) #> }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"omnidirecitonal-geoms","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Omnidirecitonal geoms","title":"Extending ggplot2","text":"setup geoms pretty much , twists. has_flipped_aes() also used setup_params(), usually picked flipped_aes column given stat. setup_data() often see flipped_aes reassigned, make sure exist prior position adjustment. needed geom used together stat doesn’t handle orientation (often stat_identity()): draw_*() method sandwich data manipulation flip_data() calls. important make sure data flipped back prior creating grob calling draw methods geoms.","code":"GeomBoxplot$setup_data #> #> #> function (...) #> setup_data(...) #> #> #> function (data, params) #> { #> data$flipped_aes <- params$flipped_aes #> data <- flip_data(data, params$flipped_aes) #> data$width <- data$width %||% params$width %||% (resolution(data$x, #> FALSE, TRUE) * 0.9) #> if (isFALSE(params$outliers)) { #> data$outliers <- NULL #> } #> if (!is.null(data$outliers)) { #> suppressWarnings({ #> out_min <- vapply(data$outliers, min, numeric(1)) #> out_max <- vapply(data$outliers, max, numeric(1)) #> }) #> data$ymin_final <- pmin(out_min, data$ymin) #> data$ymax_final <- pmax(out_max, data$ymax) #> } #> if (is.null(params) || is.null(params$varwidth) || !params$varwidth || #> is.null(data$relvarwidth)) { #> data$xmin <- data$x - data$width/2 #> data$xmax <- data$x + data$width/2 #> } #> else { #> data$relvarwidth <- data$relvarwidth/max(data$relvarwidth) #> data$xmin <- data$x - data$relvarwidth * data$width/2 #> data$xmax <- data$x + data$relvarwidth * data$width/2 #> } #> data$width <- NULL #> if (!is.null(data$relvarwidth)) #> data$relvarwidth <- NULL #> flip_data(data, params$flipped_aes) #> }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"dealing-with-required-aesthetics","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Dealing with required aesthetics","title":"Extending ggplot2","text":"Omnidirectional layers usually two different sets required aesthetics. set used often knows orientation. handle gracefully required_aes field Stat Geom classes understands | () operator. Looking GeomBoxplot can see used: tells ggplot2 either aesthetics | required aesthetics required.","code":"GeomBoxplot$required_aes #> [1] \"x|y\" \"lower|xlower\" \"upper|xupper\" \"middle|xmiddle\" #> [5] \"ymin|xmin\" \"ymax|xmax\""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"ambiguous-layers","dir":"Articles","previous_headings":"Geoms and Stats with multiple orientation","what":"Ambiguous layers","title":"Extending ggplot2","text":"layers clear interpretation data terms orientation. classic example geom_line() just convention runs along x-axis. nothing data indicates . geoms user must indicate flipped orientation setting orientation = \"y\". stat geom call has_flipped_aes() ambiguous = TRUE cancel guessing based data format. example can see setup_params() method GeomLine:","code":"GeomLine$setup_params #> #> #> function (...) #> setup_params(...) #> #> #> function (data, params) #> { #> params$flipped_aes <- has_flipped_aes(data, params, ambiguous = TRUE) #> params #> }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-your-own-theme","dir":"Articles","previous_headings":"","what":"Creating your own theme","title":"Extending ggplot2","text":"’re going create complete theme, things need know: Overriding existing elements, rather modifying four global elements affect (almost) every theme element Complete vs. incomplete elements","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"overriding-elements","dir":"Articles","previous_headings":"Creating your own theme","what":"Overriding elements","title":"Extending ggplot2","text":"default, add new theme element, inherits values existing theme. example, following code sets key colour red, inherits existing fill colour: override completely, use %+replace% instead +:","code":"theme_grey()$legend.key #> NULL new_theme <- theme_grey() + theme(legend.key = element_rect(colour = \"red\")) new_theme$legend.key #> List of 5 #> $ fill : NULL #> $ colour : chr \"red\" #> $ linewidth : NULL #> $ linetype : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\" new_theme <- theme_grey() %+replace% theme(legend.key = element_rect(colour = \"red\")) new_theme$legend.key #> List of 5 #> $ fill : NULL #> $ colour : chr \"red\" #> $ linewidth : NULL #> $ linetype : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"global-elements","dir":"Articles","previous_headings":"Creating your own theme","what":"Global elements","title":"Extending ggplot2","text":"four elements affect global appearance plot: set default properties inherited specific settings. useful setting overall “background” colour overall font settings (e.g. family size). generally start creating theme modifying values.","code":"df <- data.frame(x = 1:3, y = 1:3) base <- ggplot(df, aes(x, y)) + geom_point() + theme_minimal() base base + theme(text = element_text(colour = \"red\"))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"complete-vs-incomplete","dir":"Articles","previous_headings":"Creating your own theme","what":"Complete vs incomplete","title":"Extending ggplot2","text":"useful understand difference complete incomplete theme objects. complete theme object one produced calling theme function attribute complete = TRUE. Theme functions theme_grey() theme_bw() examples complete theme functions. Calls theme() produce incomplete theme objects, since represent (local) modifications theme object rather returning complete theme object per se. adding incomplete theme complete one, result complete theme. Complete incomplete themes behave somewhat differently added ggplot object: Adding incomplete theme augments current theme object, replacing properties elements defined call theme(). Adding complete theme wipes away existing theme applies new theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-a-new-faceting","dir":"Articles","previous_headings":"","what":"Creating a new faceting","title":"Extending ggplot2","text":"One daunting exercises ggplot2 extensions create new faceting system. reason creating new facetings take responsibility (almost) everything drawn screen, many experience directly using gtable grid upon ggplot2 rendering built. decide venture faceting extensions, highly recommended gain proficiency -mentioned packages. Facet class ggplot2 powerful takes responsibility wide range tasks. main tasks Facet object : Define layout; , partitioning data different plot areas (panels) well panels share position scales. Map plot data correct panels, potentially duplicating data exist multiple panels (e.g. margins facet_grid()). Assemble panels final gtable, adding axes, strips decorations process. Apart three tasks, functionality must implemented, couple additional extension points sensible defaults provided. can generally ignored, adventurous developers can override even control: Initialization training positional scales panel. Decoration front behind panel. Drawing axis labels show new faceting class created start simple go required methods turn build facet_duplicate() simply duplicate plot two panels. tinker bit show powerful possibilities.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-a-layout-specification","dir":"Articles","previous_headings":"Creating a new faceting","what":"Creating a layout specification","title":"Extending ggplot2","text":"layout context facets data.frame defines mapping data panels reside well positional scales used. output least contain columns PANEL, SCALE_X, SCALE_Y, often contain help assign data correct panel (facet_grid() e.g. also return faceting variables associated panel). Let’s make function defines duplicate layout: quite simple faceting just define two panels irrespectively input data parameters.","code":"layout <- function(data, params) { data.frame(PANEL = c(1L, 2L), SCALE_X = 1L, SCALE_Y = 1L) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"mapping-data-into-panels","dir":"Articles","previous_headings":"Creating a new faceting","what":"Mapping data into panels","title":"Extending ggplot2","text":"order ggplot2 know data go needs data assigned panel. purpose mapping step assign PANEL column layer data identifying panel belongs . first investigate whether gotten empty data.frame duplicate data assign original data first panel new data second panel.","code":"mapping <- function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } rbind( cbind(data, PANEL = 1L), cbind(data, PANEL = 2L) ) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"laying-out-the-panels","dir":"Articles","previous_headings":"Creating a new faceting","what":"Laying out the panels","title":"Extending ggplot2","text":"two functions deceivingly simple, last one going take work. goal draw two panels beside () axes etc.","code":"render <- function(panels, layout, x_scales, y_scales, ranges, coord, data, theme, params) { # Place panels according to settings if (params$horizontal) { # Put panels in matrix and convert to a gtable panels <- matrix(panels, ncol = 2) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(c(1, 1), \"null\"), heights = unit(1, \"null\"), clip = \"on\") # Add spacing according to theme panel_spacing <- calc_element(\"panel.spacing.x\", theme) panel_table <- gtable::gtable_add_col_space(panel_table, panel_spacing) } else { panels <- matrix(panels, ncol = 1) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(1, \"null\"), heights = unit(c(1, 1), \"null\"), clip = \"on\") panel_spacing <- if (is.null(theme$panel.spacing.y)) { theme$panel.spacing } else { theme$panel.spacing.y } panel_table <- gtable::gtable_add_row_space(panel_table, panel_spacing) } # Name panel grobs so they can be found later panel_table$layout$name <- paste0(\"panel-\", c(1, 2)) # Construct the axes axes <- render_axes(ranges[1], ranges[1], coord, theme, transpose = TRUE) # Add axes around each panel panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_width_l <- unit(grid::convertWidth( grid::grobWidth(axes$y$left[[1]]), \"cm\", TRUE), \"cm\") axis_width_r <- unit(grid::convertWidth( grid::grobWidth(axes$y$right[[1]]), \"cm\", TRUE), \"cm\") ## We do it reverse so we don't change the position of panels when we add axes for (i in rev(panel_pos_h)) { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r, i) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$y$right, length(panel_pos_v)), t = panel_pos_v, l = i + 1, clip = \"off\") panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l, i - 1) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$y$left, length(panel_pos_v)), t = panel_pos_v, l = i, clip = \"off\") } ## Recalculate as gtable has changed panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_height_t <- unit(grid::convertHeight( grid::grobHeight(axes$x$top[[1]]), \"cm\", TRUE), \"cm\") axis_height_b <- unit(grid::convertHeight( grid::grobHeight(axes$x$bottom[[1]]), \"cm\", TRUE), \"cm\") for (i in rev(panel_pos_v)) { panel_table <- gtable::gtable_add_rows(panel_table, axis_height_b, i) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$bottom, length(panel_pos_h)), t = i + 1, l = panel_pos_h, clip = \"off\") panel_table <- gtable::gtable_add_rows(panel_table, axis_height_t, i - 1) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$top, length(panel_pos_h)), t = i, l = panel_pos_h, clip = \"off\") } panel_table }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"assembling-the-facet-class","dir":"Articles","previous_headings":"Creating a new faceting","what":"Assembling the Facet class","title":"Extending ggplot2","text":"Usually methods defined within class definition way done Geom Stat. split go turn. remains assign functions correct methods well making constructor Now everything assembled, lets test :","code":"# Constructor: shrink is required to govern whether scales are trained on # Stat-transformed data or not. facet_duplicate <- function(horizontal = TRUE, shrink = TRUE) { ggproto(NULL, FacetDuplicate, shrink = shrink, params = list( horizontal = horizontal ) ) } FacetDuplicate <- ggproto(\"FacetDuplicate\", Facet, compute_layout = layout, map_data = mapping, draw_panels = render ) p <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() p p + facet_duplicate()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"doing-more-with-facets","dir":"Articles","previous_headings":"Creating a new faceting","what":"Doing more with facets","title":"Extending ggplot2","text":"example pretty useless ’ll now try expand add actual usability. going make faceting adds panels y-transformed axes: apparent, draw_panel method can become unwieldy begins take multiple possibilities account. fact want support horizontal vertical layout leads lot /else blocks code. general, big challenge writing facet extensions prepared meticulous writing methods. Enough talk - lets see new powerful faceting extension works:","code":"library(scales) facet_trans <- function(trans, horizontal = TRUE, shrink = TRUE) { ggproto(NULL, FacetTrans, shrink = shrink, params = list( trans = scales::as.transform(trans), horizontal = horizontal ) ) } FacetTrans <- ggproto(\"FacetTrans\", Facet, # Almost as before but we want different y-scales for each panel compute_layout = function(data, params) { data.frame(PANEL = c(1L, 2L), SCALE_X = 1L, SCALE_Y = c(1L, 2L)) }, # Same as before map_data = function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } rbind( cbind(data, PANEL = 1L), cbind(data, PANEL = 2L) ) }, # This is new. We create a new scale with the defined transformation init_scales = function(layout, x_scale = NULL, y_scale = NULL, params) { scales <- list() if (!is.null(x_scale)) { scales$x <- lapply(seq_len(max(layout$SCALE_X)), function(i) x_scale$clone()) } if (!is.null(y_scale)) { y_scale_orig <- y_scale$clone() y_scale_new <- y_scale$clone() y_scale_new$trans <- params$trans # Make sure that oob values are kept y_scale_new$oob <- function(x, ...) x scales$y <- list(y_scale_orig, y_scale_new) } scales }, # We must make sure that the second scale is trained on transformed data train_scales = function(x_scales, y_scales, layout, data, params) { # Transform data for second panel prior to scale training if (!is.null(y_scales)) { data <- lapply(data, function(layer_data) { match_id <- match(layer_data$PANEL, layout$PANEL) y_vars <- intersect(y_scales[[1]]$aesthetics, names(layer_data)) trans_scale <- layer_data$PANEL == 2L for (i in y_vars) { layer_data[trans_scale, i] <- y_scales[[2]]$transform(layer_data[trans_scale, i]) } layer_data }) } Facet$train_scales(x_scales, y_scales, layout, data, params) }, # this is where we actually modify the data. It cannot be done in $map_data as that function # doesn't have access to the scales finish_data = function(data, layout, x_scales, y_scales, params) { match_id <- match(data$PANEL, layout$PANEL) y_vars <- intersect(y_scales[[1]]$aesthetics, names(data)) trans_scale <- data$PANEL == 2L for (i in y_vars) { data[trans_scale, i] <- y_scales[[2]]$transform(data[trans_scale, i]) } data }, # A few changes from before to accommodate that axes are now not duplicate of each other # We also add a panel strip to annotate the different panels draw_panels = function(panels, layout, x_scales, y_scales, ranges, coord, data, theme, params) { # Place panels according to settings if (params$horizontal) { # Put panels in matrix and convert to a gtable panels <- matrix(panels, ncol = 2) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(c(1, 1), \"null\"), heights = unit(1, \"null\"), clip = \"on\") # Add spacing according to theme panel_spacing <- calc_element(\"panel.spacing.x\", theme) panel_table <- gtable::gtable_add_col_space(panel_table, panel_spacing) } else { panels <- matrix(panels, ncol = 1) panel_table <- gtable::gtable_matrix(\"layout\", panels, widths = unit(1, \"null\"), heights = unit(c(1, 1), \"null\"), clip = \"on\") panel_spacing <- calc_element(\"panel.spacing.y\", theme) panel_table <- gtable::gtable_add_row_space(panel_table, panel_spacing) } # Name panel grobs so they can be found later panel_table$layout$name <- paste0(\"panel-\", c(1, 2)) # Construct the axes axes <- render_axes(ranges[1], ranges, coord, theme, transpose = TRUE) # Add axes around each panel grobWidths <- function(x) { unit(vapply(x, function(x) { grid::convertWidth( grid::grobWidth(x), \"cm\", TRUE) }, numeric(1)), \"cm\") } panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_width_l <- grobWidths(axes$y$left) axis_width_r <- grobWidths(axes$y$right) ## We do it reverse so we don't change the position of panels when we add axes if (params$horizontal) { for (i in rev(seq_along(panel_pos_h))) { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[i], panel_pos_h[i]) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$right[i], t = panel_pos_v, l = panel_pos_h[i] + 1, clip = \"off\") panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[i], panel_pos_h[i] - 1) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$left[i], t = panel_pos_v, l = panel_pos_h[i], clip = \"off\") } } else { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[1], panel_pos_h) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$right, t = panel_pos_v, l = panel_pos_h + 1, clip = \"off\") panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[1], panel_pos_h - 1) panel_table <- gtable::gtable_add_grob(panel_table, axes$y$left, t = panel_pos_v, l = panel_pos_h, clip = \"off\") } ## Recalculate as gtable has changed panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_height_t <- unit(grid::convertHeight( grid::grobHeight(axes$x$top[[1]]), \"cm\", TRUE), \"cm\") axis_height_b <- unit(grid::convertHeight( grid::grobHeight(axes$x$bottom[[1]]), \"cm\", TRUE), \"cm\") for (i in rev(panel_pos_v)) { panel_table <- gtable::gtable_add_rows(panel_table, axis_height_b, i) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$bottom, length(panel_pos_h)), t = i + 1, l = panel_pos_h, clip = \"off\") panel_table <- gtable::gtable_add_rows(panel_table, axis_height_t, i - 1) panel_table <- gtable::gtable_add_grob(panel_table, rep(axes$x$top, length(panel_pos_h)), t = i, l = panel_pos_h, clip = \"off\") } # Add strips strips <- render_strips( x = data.frame(name = c(\"Original\", paste0(\"Transformed (\", params$trans$name, \")\"))), labeller = label_value, theme = theme) panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t strip_height <- unit(grid::convertHeight( grid::grobHeight(strips$x$top[[1]]), \"cm\", TRUE), \"cm\") for (i in rev(seq_along(panel_pos_v))) { panel_table <- gtable::gtable_add_rows(panel_table, strip_height, panel_pos_v[i] - 1) if (params$horizontal) { panel_table <- gtable::gtable_add_grob(panel_table, strips$x$top, t = panel_pos_v[i], l = panel_pos_h, clip = \"off\") } else { panel_table <- gtable::gtable_add_grob(panel_table, strips$x$top[i], t = panel_pos_v[i], l = panel_pos_h, clip = \"off\") } } panel_table } ) ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_trans('sqrt')"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"extending-existing-facet-function","dir":"Articles","previous_headings":"","what":"Extending existing facet function","title":"Extending ggplot2","text":"rendering part facet class often difficult development step, possible piggyback existing faceting classes achieve range new facetings. subclass facet_wrap() make facet_bootstrap() class splits input data number panels random. intercept compute_layout map_data methods instead dividing data variable randomly assigns rows panel based sampling parameters (n determines number panels, prop determines proportion data panel). important layout returned compute_layout valid layout FacetWrap counting draw_panel method FacetWrap work us. Thus want subclass FacetWrap FacetGrid, make sure understand nature layout specification.","code":"facet_bootstrap <- function(n = 9, prop = 0.2, nrow = NULL, ncol = NULL, scales = \"fixed\", shrink = TRUE, strip.position = \"top\") { facet <- facet_wrap(~.bootstrap, nrow = nrow, ncol = ncol, scales = scales, shrink = shrink, strip.position = strip.position) facet$params$n <- n facet$params$prop <- prop ggproto(NULL, FacetBootstrap, shrink = shrink, params = facet$params ) } FacetBootstrap <- ggproto(\"FacetBootstrap\", FacetWrap, compute_layout = function(data, params) { id <- seq_len(params$n) dims <- wrap_dims(params$n, params$nrow, params$ncol) layout <- data.frame(PANEL = factor(id)) layout$ROW <- as.integer((id - 1L) %/% dims[2] + 1L) layout$COL <- as.integer((id - 1L) %% dims[2] + 1L) layout <- layout[order(layout$PANEL), , drop = FALSE] rownames(layout) <- NULL # Add scale identification layout$SCALE_X <- if (params$free$x) id else 1L layout$SCALE_Y <- if (params$free$y) id else 1L cbind(layout, .bootstrap = id) }, map_data = function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } n_samples <- round(nrow(data) * params$prop) new_data <- lapply(seq_len(params$n), function(i) { cbind(data[sample(nrow(data), n_samples), , drop = FALSE], PANEL = i) }) do.call(rbind, new_data) } ) ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 0.1) + facet_bootstrap(n = 9, prop = 0.05)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises-2","dir":"Articles","previous_headings":"Extending existing facet function","what":"Exercises","title":"Extending ggplot2","text":"Rewrite FacetTrans take vector transformations create additional panel transformation. Based FacetWrap implementation rewrite FacetTrans take strip.placement theme setting account. Think caveats FacetBootstrap specifically related adding multiple layers data.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"creating-new-guides","dir":"Articles","previous_headings":"","what":"Creating new guides","title":"Extending ggplot2","text":"Guides closely related scales aesthetics, important part guides taking information scale translating graphic. information passed around inside guides key dataframe. existing guides, can glance key contains using get_guide_data() function. Typical variables may see guides aesthetic mapped scale, hexadecimal colours example , aesthetic represent .value column labelled .label column. Sometimes, aesthetic used computations. avoid interpreting values labels aesthetics, customary prefix ..","code":"p <- ggplot(mpg, aes(displ, hwy, colour = drv)) + geom_point() + scale_colour_discrete( labels = c(\"4-wheel drive\", \"front wheel drive\", \"rear wheel drive\") ) get_guide_data(p, \"colour\") #> colour .value .label #> 1 #F8766D 4 4-wheel drive #> 2 #00BA38 f front wheel drive #> 3 #619CFF r rear wheel drive"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"overriding-scale-extraction","dir":"Articles","previous_headings":"Creating new guides","what":"Overriding scale extraction","title":"Extending ggplot2","text":"Let’s now make first guide extension adjusting guide’s key. Axes straightforward extend, least complicated. ’ll build axis accepts custom values guide’s key. can begin making custom ggproto class inherits axis guide. important extension point extract_key() method, determines break information transferred scale guide. class, reject scale’s reality substitute .","code":"GuideKey <- ggproto( \"Guide\", GuideAxis, # Some parameters are required, so it is easiest to copy the base Guide's # parameters into our new parameters. # We add a new 'key' parameter for our own guide. params = c(GuideAxis$params, list(key = NULL)), # It is important for guides to have a mapped aesthetic with the correct name extract_key = function(scale, aesthetic, key, ...) { key$aesthetic <- scale$map(key$aesthetic) names(key)[names(key) == \"aesthetic\"] <- aesthetic key } )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"guide-constructors","dir":"Articles","previous_headings":"Creating new guides","what":"Guide constructors","title":"Extending ggplot2","text":"Now can make guide constructor creates custom key pass along . new_guide() function instantiates new guide given parameters. function automatically rejects parameters class’ params field, important declare . new guide can now used inside guides() function guide argument position scale.","code":"guide_key <- function( aesthetic, value = aesthetic, label = as.character(aesthetic), ..., # Standard guide arguments theme = NULL, title = waiver(), order = 0, position = waiver() ) { key <- data.frame(aesthetic, .value = value, .label = label, ...) new_guide( # Arguments passed on to the GuideKey$params field key = key, theme = theme, title = title, order = order, position = position, # Declare which aesthetics are supported available_aes = c(\"x\", \"y\"), # Set the guide class super = GuideKey ) } ggplot(mpg, aes(displ, hwy)) + geom_point() + scale_x_continuous( guide = guide_key(aesthetic = 2:6 + 0.5) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"custom-drawings","dir":"Articles","previous_headings":"Creating new guides","what":"Custom drawings","title":"Extending ggplot2","text":"feeling adventurous, can also alter way guides drawn. majority drawing code Guide$build_*() methods, orchestrated Guide$draw() method. derived guides, custom key guide ’re extending , overriding Guide$build_*() method sufficient. writing completely novel guide resemble structure existing guide, overriding Guide$draw() method might wise. example, changing way labels drawn, edit Guide$build_labels() method. ’ll edit method labels drawn colour set key. addition key params variable ’ve seen , now also elements variable, list precomputed theme elements. can use elements$text element draw graphical object (grob) style axis text. Perhaps finicky thing drawing guides lot settings depend guide’s position parameter. incorporating ... argument guide_key() key, adding colour column key straightforward. can check guide looks correct different positions around panel.","code":"# Same as before GuideKey <- ggproto( \"Guide\", GuideAxis, params = c(GuideAxis$params, list(key = NULL)), extract_key = function(scale, aesthetic, key, ...) { key$aesthetic <- scale$map(key$aesthetic) names(key)[names(key) == \"aesthetic\"] <- aesthetic key }, # New method to draw labels build_labels = function(key, elements, params) { position <- params$position # Downstream code expects a list of labels list(element_grob( elements$text, label = key$.label, x = switch(position, left = 1, right = 0, key$x), y = switch(position, top = 0, bottom = 1, key$y), margin_x = position %in% c(\"left\", \"right\"), margin_y = position %in% c(\"top\", \"bottom\"), colour = key$colour )) } ) ggplot(mpg, aes(displ, hwy)) + geom_point() + guides( x = guide_key( aesthetic = 2:6 + 0.5, colour = c(\"red\", \"grey\", \"red\", \"grey\", \"red\") ), x.sec = guide_key( aesthetic = c(2, 4, 6), colour = c(\"tomato\", \"limegreen\", \"dodgerblue\") ) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/extending-ggplot2.html","id":"exercises-3","dir":"Articles","previous_headings":"Creating new guides","what":"Exercises","title":"Extending ggplot2","text":"Extend guide_key() also pass family, face size aesthetics key labels. Override GuideKey$build_ticks() method also pass colour linewidth settings tick marks. Looking Guide$build_ticks() good starting point. Compare GuideKey$extract_key() Guide$extract_key(). steps skimmed example?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"why-is-annotation-created-with-geom_text-pixellated-how-can-i-make-it-more-crisp","dir":"Articles","previous_headings":"","what":"Why is annotation created with geom_text() pixellated? How can I make it more crisp?","title":"FAQ: Annotation","text":"use annotate(geom = \"text\") instead geom_text() annotation. following visualisation annotated histogram red line red text mark mean. Note line text appears pixellated/fuzzy. geom_text() draws geom per row data frame, plotting top . annotation (opposed plotting data using text geometric objects represent observation) use annotate() instead.","code":"mean_hwy <- round(mean(mpg$hwy), 2) ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 2) + geom_segment( x = mean_hwy, xend = mean_hwy, y = 0, yend = 35, color = \"red\" ) + geom_text( x = mean_hwy, y = 40, label = paste(\"mean\\n\", mean_hwy), color = \"red\" ) ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 2) + annotate(\"segment\", x = mean_hwy, xend = mean_hwy, y = 0, yend = 35, color = \"red\" ) + annotate(\"text\", x = mean_hwy, y = 40, label = paste(\"mean =\", mean_hwy), color = \"red\" )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-make-sure-all-annotation-created-with-geom_text-fits-in-the-bounds-of-the-plot","dir":"Articles","previous_headings":"","what":"How can I make sure all annotation created with geom_text() fits in the bounds of the plot?","title":"FAQ: Annotation","text":"Set vjust = \"inward\" hjust = \"inward\" geom_text(). Suppose following data frame visualization. labels edges plot cut slightly. manually extend axis limits avoid , straightforward approach set vjust = \"inward\" hjust = \"inward\" geom_text().","code":"df <- tibble::tribble( ~x, ~y, ~name, 2, 2, \"two\", 3, 3, \"three\", 4, 4, \"four\" ) ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 10) ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 10, vjust = \"inward\", hjust = \"inward\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-annotate-my-bar-plot-to-display-counts-for-each-bar","dir":"Articles","previous_headings":"","what":"How can I annotate my bar plot to display counts for each bar?","title":"FAQ: Annotation","text":"Either calculate counts ahead time place bars using geom_text() let ggplot() calculate add plot using stat_count() geom = \"text\". Suppose following bar plot want add number cars fall drv level respective bars. One option calculate counts dplyr::count() pass label mapping geom_text(). Note expanded y axis limit get numbers fit plot. Another option let ggplot() counting , access counts after_stat(count) mapped labels placed plot stat_count().","code":"ggplot(mpg, aes(x = drv)) + geom_bar() mpg %>% dplyr::count(drv) %>% ggplot(aes(x = drv, y = n)) + geom_col() + geom_text(aes(label = n), vjust = -0.5) + coord_cartesian(ylim = c(0, 110)) ggplot(mpg, aes(x = drv)) + geom_bar() + stat_count(geom = \"text\", aes(label = ..count..), vjust = -0.5) + coord_cartesian(ylim = c(0, 110)) #> Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0. #> ℹ Please use `after_stat(count)` instead. #> This warning is displayed once every 8 hours. #> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was #> generated."},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-annotate-my-stacked-bar-plot-to-display-counts-for-each-segment","dir":"Articles","previous_headings":"","what":"How can I annotate my stacked bar plot to display counts for each segment?","title":"FAQ: Annotation","text":"First calculate counts segment (e.g. dplyr::count()) place bars geom_text() using position_stack(vjust = 0.5) position argument place values middle segments. Suppose following stacked bar plot. can first calculate counts segment dplyr::count(), place values column called n. can pass result directly ggplot(), draw segments appropriate heights y = n aesthetic mapping geom_col() draw bars, finally place counts plot geom_text().","code":"ggplot(mpg, aes(x = class, fill = drv)) + geom_bar() mpg %>% count(class, drv) #> # A tibble: 12 × 3 #> class drv n #> #> 1 2seater r 5 #> 2 compact 4 12 #> 3 compact f 35 #> 4 midsize 4 3 #> 5 midsize f 38 #> 6 minivan f 11 #> 7 pickup 4 33 #> 8 subcompact 4 4 #> 9 subcompact f 22 #> 10 subcompact r 9 #> 11 suv 4 51 #> 12 suv r 11 mpg %>% count(class, drv) %>% ggplot(aes(x = class, fill = drv, y = n)) + geom_col() + geom_text(aes(label = n), size = 3, position = position_stack(vjust = 0.5))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-annotation.html","id":"how-can-i-display-proportions-relative-frequencies-instead-of-counts-on-a-bar-plot","dir":"Articles","previous_headings":"","what":"How can I display proportions (relative frequencies) instead of counts on a bar plot?","title":"FAQ: Annotation","text":"Either calculate proportions ahead time place bars using geom_text() let ggplot() calculate add plot using stat_coun() geom = \"text\". Suppose following bar plot want display proportion cars fall drv level, instead count. One option calculate proportions dplyr::count() use geom_col() draw bars Another option let ggplot() calculation proportions , access counts ..prop... Note also need group = 1 mapping option.","code":"ggplot(mpg, aes(x = drv)) + geom_bar() mpg %>% dplyr::count(drv) %>% mutate(prop = n / sum(n)) %>% ggplot(aes(x = drv, y = prop)) + geom_col() ggplot(mpg, aes(x = drv, y = ..prop.., group = 1)) + geom_bar()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-rotate-the-axis-tick-labels-in-ggplot2-so-that-tick-labels-that-are-long-character-strings-dont-overlap","dir":"Articles","previous_headings":"Label placement","what":"How can I rotate the axis tick labels in ggplot2 so that tick labels that are long character strings don’t overlap?","title":"FAQ: Axes","text":"Set angle text axis.text.x axis.text.y components theme(), e.g. theme(axis.text.x = element_text(angle = 90)). following plot labels x-axis overlapping. Rotate axis labels: can components theme(), specifically axis.text.x component. Applying vertical horizontal justification labels centers axis ticks. angle can set desired within 0 360 degree range, set 90 degrees. Flip axes: Use y-axis long labels. Dodge axis labels: Add scale_*() layer, e.g. scale_x_continuous(), scale_y_discrete(), etc., customise guide argument guide_axis() function. case want customise x-axis, variable x-axis discrete, ’ll use scale_x_continuous(). guide argument use guide_axis() specify many rows dodge labels n.dodge. likely trial--error exercise, depending lengths labels width plot. case ’ve settled 3 rows render labels. Omit overlapping labels: Alternatively, can set guide_axis(check.overlap = TRUE) omit axis labels overlap. ggplot2 prioritize first, last, middle labels. Note option might preferable axes representing variables inherent ordering obvious audience plot, ’s trivial guess missing labels . (case following plot.)","code":"ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) ggplot(msleep, aes(y = order, x = sleep_total)) + geom_boxplot() ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + scale_x_discrete(guide = guide_axis(n.dodge = 3)) ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + scale_x_discrete(guide = guide_axis(check.overlap = TRUE))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-remove-axis-labels-in-ggplot2","dir":"Articles","previous_headings":"Label placement","what":"How can I remove axis labels in ggplot2?","title":"FAQ: Axes","text":"Add theme() layer set relevant arguments, e.g. axis.title.x, axis.text.x, etc. element_blank(). Suppose want remove axis labels entirely. Remove x y axis labels: want modify just one axes, can modifying components theme(), setting elements want remove element_blank(). replace x y applying update y-axis. Note distinction axis.title axis.ticks – axis.title name variable axis.text text accompanying ticks. Remove axis labels: can use theme_void() remove theming elements. Note might remove features like. finer control theme, see .","code":"ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + theme( axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank() ) ggplot(msleep, aes(x = order, y = sleep_total)) + geom_boxplot() + theme_void()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-add-multi-row-axis-labels-with-a-grouping-variable","dir":"Articles","previous_headings":"Label placement","what":"How can I add multi-row axis labels with a grouping variable?","title":"FAQ: Axes","text":"can either using interaction() map interaction variable ’re plotting grouping variable x y aesthetic. Suppose following data sales quarter across two years. can create line plot data facet year group quarters year together. However might preferable plot points single plot indicate x-axis first Q1 Q4 2020 second 2021. achieve , map interaction() quarter year x aesthetic. achieves desired result line, however labeling x-axis busy difficult read. clean (1) clip plotting area coord_cartesian(), (2) remove axis labels add wider margin bottom plot theme(), (3) place axis labels indicating quarters underneath plot, (4) underneath labels, place annotation indicating years. Note x-coordinates year labels manually assigned , many years, might write logic calculate placement. approach works geoms well. example, might can create bar plot representing data using following. ’s undesirable bars flush edges plot, similar result can achieved leveraging faceting removing space facets create appearance single plot. However note space bars 2020 Q4 2021 Q1 greater space bars.","code":"library(tibble) sales <- tribble( ~value, ~quarter, ~year, 10, \"Q1\", 2020, 15, \"Q2\", 2020, 15, \"Q3\", 2020, 20, \"Q4\", 2020, 10, \"Q1\", 2021, 25, \"Q2\", 2021, 30, \"Q3\", 2021, 30, \"Q4\", 2021 ) ggplot(sales, aes(x = quarter, y = value, group = 1)) + geom_line() + facet_wrap(~year) ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + geom_line() ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + geom_line() + coord_cartesian(ylim = c(9, 32), expand = FALSE, clip = \"off\") + theme( plot.margin = margin(1, 1, 3, 1, \"lines\"), axis.title.x = element_blank(), axis.text.x = element_blank() ) + annotate(geom = \"text\", x = seq_len(nrow(sales)), y = 8, label = sales$quarter, size = 3) + annotate(geom = \"text\", x = c(2.5, 6.5), y = 6, label = unique(sales$year), size = 4) ggplot(sales, aes(x = interaction(quarter, year), y = value)) + geom_col() + coord_cartesian(ylim = c(0, 32), expand = FALSE, clip = \"off\") + annotate(geom = \"text\", x = seq_len(nrow(sales)), y = -1, label = sales$quarter, size = 3) + annotate(geom = \"text\", x = c(2.5, 6.5), y = -3, label = unique(sales$year), size = 4) + theme( plot.margin = margin(1, 1, 3, 1, \"lines\"), axis.title.x = element_blank(), axis.text.x = element_blank() ) ggplot(sales, aes(x = quarter, y = value)) + geom_col() + facet_wrap(~year, strip.position = \"bottom\") + theme( panel.spacing = unit(0, \"lines\"), strip.background = element_blank(), strip.placement = \"outside\" ) + labs(x = NULL)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-customize-the-text-shown-on-the-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I customize the text shown on the axis labels?","title":"FAQ: Axes","text":"Add scale_*() layer, e.g. scale_x_continuous(), scale_y_discrete(), etc., add custom labels labels argument. Suppose want give informative labels type drive train. Use labels argument appropriate scale_*() function. can find list functions . Type drive train (drv) discrete variable y-axis, ’ll adjust labels scale_y_discrete(). One option list labels order levels. Note start bottom go , just like variable numeric/continuous. Another approach use named list. approach makes relabelling explicit, also means don’t need worry order levels.","code":"ggplot(mpg, aes(y = drv)) + geom_bar() ggplot(mpg, aes(y = drv)) + geom_bar() + scale_y_discrete( labels = c(\"Four wheel drive\", \"Front wheel drive\", \"Rear wheel drive\") ) ggplot(mpg, aes(y = drv)) + geom_bar() + scale_y_discrete( labels = c( \"f\" = \"Front wheel drive\", \"r\" = \"Rear wheel drive\", \"4\" = \"Four wheel drive\" ) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-stop-r-from-using-scientific-notation-on-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I stop R from using scientific notation on axis labels?","title":"FAQ: Axes","text":"Use scales::label_number() force decimal display numbers. first need add scale_*() layer (e.g. scale_x_continuous(), scale_y_discrete(), etc.) customise labels argument within layer function. default, large numbers axis labels following plot shown scientific notation. scales package offers large number functions control formatting axis labels legend keys. Use scales::label_number() force decimal display numbers rather using scientific notation use scales::label_comma() insert comma every three digits.","code":"ggplot(txhousing, aes(x = median, y = volume)) + geom_point() #> Warning: Removed 617 rows containing missing values or values outside the scale #> range (`geom_point()`). library(scales) ggplot(txhousing, aes(x = median, y = volume)) + geom_point() + scale_x_continuous(labels = label_number()) + scale_y_continuous(labels = label_comma()) #> Warning: Removed 617 rows containing missing values or values outside the scale #> range (`geom_point()`)."},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-change-the-number-of-decimal-places-on-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I change the number of decimal places on axis labels?","title":"FAQ: Axes","text":"Set accuracy scales::label_number() desired level decimal places, e.g. 0.1 show 1 decimal place, 0.0001 show 4 decimal places, etc. first need add scale_*() layer (e.g. scale_x_continuous(), scale_y_discrete(), etc.) customise labels argument within layer function. Suppose want increase/decrease number decimal spaces shown axis text following plot. scales package offers large number functions control formatting axis labels legend keys. Use scales::label_number() accuracy argument indicates number round , e.g. 0.1 show 1 decimal place, 0.0001 show 4 decimal places, etc.","code":"ggplot(seals, aes(x = delta_long, y = delta_lat)) + geom_point() library(scales) ggplot(seals, aes(x = delta_long, y = delta_lat)) + geom_point() + scale_x_continuous(labels = label_number(accuracy = 0.1)) + scale_y_continuous(labels = label_number(accuracy = 0.0001))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-add-percentage-symbols-to-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I add percentage symbols (%) to axis labels?","title":"FAQ: Axes","text":"Use scales::label_percent(), place % number, default. can customise % placed using prefix suffix arguments, also scale numbers needed. first need add scale_*() layer (e.g. scale_x_continuous(), scale_y_discrete(), etc.) customise labels argument within layer function. variable y-axis following line plot (psavert) indicates personal savings rate, percentages. scales::label_percent() can add %s numbers shown axis make units clear. accuracy argument indicates number round , e.g. 0.1 show 1 decimal place, 0.0001 show 4 decimal places, etc.","code":"ggplot(economics, aes(x = date, y = psavert, group = 1)) + geom_line() ggplot(economics, aes(x = date, y = psavert, group = 1)) + geom_line() + scale_y_continuous(labels = scales::label_percent(scale = 1, accuracy = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-add-superscripts-and-subscripts-to-axis-labels","dir":"Articles","previous_headings":"Label formatting and customization","what":"How can I add superscripts and subscripts to axis labels?","title":"FAQ: Axes","text":"can either use bquote() parse mathematical expressions use ggtext package write expression using Markdown HTML syntax. following plot cty squared hwy log transformed. Use bquote() function parse mathematical expressions. ’re already familiar Markdown HTML, might prefer using ggtext package instead. Markdown can write axis labels cty2<\/sup> log10<\/sub>(hwy) x y axes, respectively. , tell ggplot2 interpret axis labels Markdown plain text setting axis.title.x axis.title.y ggtext::element_markdown().","code":"ggplot(mpg, aes(x = cty^2, y = log(hwy))) + geom_point() ggplot(mpg, aes(x = cty^2, y = log(hwy, base = 10))) + geom_point() + labs( x = bquote(cty^2), y = bquote(paste(log[10], \"(hwy)\")) ) ggplot(mpg, aes(x = cty^2, y = log(hwy, base = 10))) + geom_point() + labs( x = \"cty2<\/sup>\", y = \"log10<\/sub>(hwy)\" ) + theme( axis.title.x = ggtext::element_markdown(), axis.title.y = ggtext::element_markdown() )"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-increase-decrease-the-number-of-axis-ticks","dir":"Articles","previous_headings":"Custom breaks","what":"How can I increase / decrease the number of axis ticks?","title":"FAQ: Axes","text":"Customise breaks minor_breaks scale_x_continuous(), scale_y_continuous(), etc. Suppose want customise major minor grid lines x y axes following plot. can set breaks minor_breaks scale_x_continuous() scale_y_continuous() desired. example, x-axis major minor grid breaks defined sequence y-axis explicitly stated major breaks appear vector (value stated randomly selected illustrative purposes , don’t follow best practice) completely turned minor grid lines setting minor_breaks NULL.","code":"ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + scale_x_continuous( breaks = seq(9, 35, 3), minor_breaks = seq(8.5, 35.5, 1) ) + scale_y_continuous( breaks = c(12, 23, 36, 41), minor_breaks = NULL )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-control-the-number-of-major-and-minor-grid-lines-shown-on-the-plot","dir":"Articles","previous_headings":"Custom breaks","what":"How can I control the number of major and minor grid lines shown on the plot?","title":"FAQ: Axes","text":"Customise breaks minor_breaks scale_x_continuous(), scale_y_continuous()`, etc. See can increase / decrease number axis ticks? detail. Note question grid lines answered using breaks. ggplot2 place major grid lines break supplied breaks minor grid lines break supplied minor_breaks.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-axes.html","id":"how-can-i-remove-the-space-between-the-plot-and-the-axis","dir":"Articles","previous_headings":"Custom breaks","what":"How can I remove the space between the plot and the axis?","title":"FAQ: Axes","text":"Remove padding around data entirely using setting expand = c(0, 0) within scale_x_continuous(), scale_y_discrete(), etc. layers. Remove padding: Suppose want remove padding around heat map ’s flush axes. Since x y variables continuous, set expand = c(0, 0) scale_x_continuous() scale_y_continuous(). Remove padding: Suppose want remove padding bars x-axis . make adjustment scale_y_continuous() since padding vertical direction. However note removes padding bottom bars well top. default, ggplot2 expands scale 5% side continuous variables 0.6 units side discrete variables. keep default expansion top removing bottom, can use following. mult argument expansion() takes multiplicative range expansion factors. Given vector length 2, lower limit expanded mult[1] (case 0) upper limit expanded mult[2] (case 0.05).","code":"ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) ggplot(mpg, aes(drv)) + geom_bar() ggplot(mpg, aes(drv)) + geom_bar() + scale_y_continuous(expand = c(0, 0)) ggplot(mpg, aes(drv)) + geom_bar() + scale_y_continuous(expand = expansion(mult = c(0, 0.05)))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-change-the-color-of-the-bars-in-my-bar-plot","dir":"Articles","previous_headings":"Colors","what":"How can I change the color of the bars in my bar plot?","title":"FAQ: Barplots","text":"using color bars, define fill argument geom_bar() (geom_col()). assigning color based another variable, map variable fill aesthetic, needed, use one scale_fill_*() functions set colors. can set bars given color fill argument geom_bar(). Alternatively, colors based variable, happen aes() mapping. want customize colors, one option scale_fill_manual(), allows manually assign colors bar. See scale_fill_*() functions options color choices.","code":"ggplot(mpg, aes(x = drv)) + geom_bar(fill = \"blue\") ggplot(mpg, aes(x = drv, fill = drv)) + geom_bar() ggplot(mpg, aes(x = drv, fill = drv)) + geom_bar() + scale_fill_manual(values = c(\"purple\", \"orange\", \"darkblue\"))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-increase-the-space-between-the-bars-in-my-bar-plot","dir":"Articles","previous_headings":"Spacing and widths","what":"How can I increase the space between the bars in my bar plot?","title":"FAQ: Barplots","text":"Set width geom_bar() small value obtain narrower bars space . default, width bars 0.9 (90% resolution data). can set argument lower value get bars narrower space .","code":"ggplot(mpg, aes(x = drv)) + geom_bar(width = 0.5) ggplot(mpg, aes(x = drv)) + geom_bar(width = 0.1)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-remove-the-space-between-the-bars-and-the-x-axis","dir":"Articles","previous_headings":"Spacing and widths","what":"How can I remove the space between the bars and the x-axis?","title":"FAQ: Barplots","text":"Adjust expand argument scale_y_continuous(), e.g. add scale_y_continuous(expand = expansion(mult = c(0, 0.05))) remove expansion lower end y-axis keep expansion upper end y-axis 0.05 (default expansion continuous scales). default ggplot2 expands axes geoms aren’t flush edges plot. remove spacing bars x-axis, keep spacing bars top plot, use following. achieve opposite, switch values mult. Note tallest bar now flush top plot. adjust spacing around x-axis, adjust expand argument scale_x_discrete(). Note places bars flush left side leaves space right side. default look bar plot can achieved following.","code":"ggplot(mpg, aes(x = drv)) + geom_bar() ggplot(mpg, aes(x = drv)) + geom_bar() + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) ggplot(mpg, aes(x = drv)) + geom_bar() + scale_y_continuous(expand = expansion(mult = c(0.05, 0))) ggplot(mpg, aes(x = drv)) + geom_bar() + scale_x_discrete(expand = expansion(add = c(0, 0.6))) ggplot(mpg, aes(x = drv)) + geom_bar() + scale_x_discrete(expand = expansion(add = 0.6)) + scale_y_continuous(expand = expansion(mult = 0.05))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-do-i-ensure-that-bars-on-a-dodged-bar-plot-have-the-same-width","dir":"Articles","previous_headings":"Spacing and widths","what":"How do I ensure that bars on a dodged bar plot have the same width?","title":"FAQ: Barplots","text":"Set position = position_dodge2(preserve = \"single\") geom_bar(). following plot bars differing widths within level drv differing levels class represented. can use position_dodge2() preserve = \"single\" address .","code":"ggplot(mpg, aes(x = drv, fill = class)) + geom_bar(position = \"dodge\") ggplot(mpg, aes(x = drv, fill = class)) + geom_bar(position = position_dodge2(preserve = \"single\"))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-create-a-stacked-bar-plot-displaying-a-conditional-distribution-where-each-stack-is-scaled-to-sum-to-100","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I create a stacked bar plot displaying a conditional distribution where each stack is scaled to sum to 100%?","title":"FAQ: Barplots","text":"Use position = \"fill\" geom_bar() geom_col(). also want show percentages axis, use scales::label_percent(). following plot useful comparing counts useful comparing proportions, need want able make statements like “sample, ’s likely two-seater car rear-wheel drive SUV rear-wheel drive”. position = \"fill\" generate bar plot bars equal length stacks bar show proportion drv particular class. want show percentages instead proportions x-axis, can define scale_x_continuous() scales::label_percent().","code":"ggplot(mpg, aes(y = class, fill = drv)) + geom_bar() ggplot(mpg, aes(y = class, fill = drv)) + geom_bar(position = \"fill\") ggplot(mpg, aes(y = class, fill = drv)) + geom_bar(position = \"fill\") + scale_x_continuous(name = \"percentage\", labels = scales::label_percent(accuracy = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-create-a-stacked-bar-plot-based-on-data-from-a-contingency-table-of-to-categorical-variables","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I create a stacked bar plot based on data from a contingency table of to categorical variables?","title":"FAQ: Barplots","text":"First reshape data (e.g. tidyr::pivot_longer()) one row per combination levels categorical variables, use geom_col() draw bars. Suppose following data opinion poll, numbers cells represent number responses party/opinion combination. can first pivot data longer obtain data frame one row per party/opinion combination new column, n, number responses fall category. , can pass result ggplot() create bar party y (x, prefer vertical bars) axis fill bars number responses opinion. plot proportions (relative frequencies) instead counts, use position = \"fill\" geom_col().","code":"poll <- tribble( ~party, ~agree, ~disagree, ~no_opinion, \"Democrat\", 20, 30, 20, \"Republican\", 15, 20, 10, \"Independent\", 10, 5, 0 ) poll_longer <- poll %>% pivot_longer( cols = -party, names_to = \"opinion\", values_to = \"n\" ) poll_longer #> # A tibble: 9 × 3 #> party opinion n #> #> 1 Democrat agree 20 #> 2 Democrat disagree 30 #> 3 Democrat no_opinion 20 #> 4 Republican agree 15 #> 5 Republican disagree 20 #> 6 Republican no_opinion 10 #> 7 Independent agree 10 #> 8 Independent disagree 5 #> 9 Independent no_opinion 0 ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + geom_col() ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + geom_col(position = \"fill\") + xlab(\"proportion\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-make-a-grouped-bar-plot","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I make a grouped bar plot?","title":"FAQ: Barplots","text":"Map variable want group x y aesthetic, map variable want color vars fill aesthetic, set position = \"dodge\" geom_bar(). Suppose data survey three questions, respondents select “Agree” “Disagree” question. ’ll first want reshape data row represents respondent / question pair. can tidyr::pivot_longer(). , pass resulting longer data frame ggplot() group responses question together.","code":"survey <- tibble::tribble( ~respondent, ~q1, ~q2, ~q3, 1, \"Agree\", \"Agree\", \"Disagree\", 2, \"Disagree\", \"Agree\", \"Disagree\", 3, \"Agree\", \"Agree\", \"Disagree\", 4, \"Disagree\", \"Disagree\", \"Agree\" ) survey %>% tidyr::pivot_longer( cols = -respondent, names_to = \"question\", values_to = \"response\" ) %>% ggplot(aes(x = question, fill = response)) + geom_bar(position = \"dodge\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"how-can-i-make-a-bar-plot-of-group-means","dir":"Articles","previous_headings":"Stacked bar plots","what":"How can I make a bar plot of group means?","title":"FAQ: Barplots","text":"Either calculate group means first use geom_col() draw bars let ggplot2 calculate means stat_summary() fun = \"mean\" geom = \"bar\". One option calculating group means using dplyr::group_by() followed dplyr::summarise(). , can pass resulting data frame ggplot() plot bars using geom_col(). Alternatively, can use stat_summary() let ggplot2 calculate plot means.","code":"mpg %>% group_by(drv) %>% summarise(mean_hwy = mean(hwy)) %>% ggplot(aes(x = drv, y = mean_hwy)) + geom_col() ggplot(mpg, aes(x = drv, y = hwy)) + stat_summary(fun = \"mean\", geom = \"bar\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-bars.html","id":"why-do-the-bars-on-my-plot-disappear-when-i-specify-an-axis-range-with-ylim-how-can-i-get-the-bars-to-show-up-within-a-given-axis-range","dir":"Articles","previous_headings":"Axes and axis limits","what":"Why do the bars on my plot disappear when I specify an axis range with ylim()? How can I get the bars to show up within a given axis range?","title":"FAQ: Barplots","text":"ylim() shortcut supplying limits argument individual scales. either set, values outside limits specified replaced NA. Since bars naturally start y = 0, replacing part bars NAs results bars entirely disappearing plot. changing axis limits without dropping data observations, set limits coord_cartesian() instead. Also note result deceiving bar plot, avoided general. following plot y-axis limited 20 120, hence bars showing . order obtain bar plot limited y-axis, need instead set limits coord_cartesian(). , indeed, deceiving plot. ’re using bar plot display values take value 0, might choose different geom instead. example, following data plot. Also suppose want cut bars y = 1000 since know variable ’re plotting take value less 1000, might use geom_point() instead.","code":"ggplot(mpg, aes(x = drv)) + geom_bar() + ylim(c(20, 120)) #> Warning: Removed 3 rows containing missing values or values outside the scale #> range (`geom_bar()`). ggplot(mpg, aes(x = drv)) + geom_bar() + coord_cartesian(ylim = c(20,110)) df <- tibble::tribble( ~x, ~y, \"A\", 1050, \"B\", 1100, \"C\", 1150 ) ggplot(df, aes(x = x, y = y)) + geom_col() # don't do this ggplot(df, aes(x = x, y = y)) + geom_col() + coord_cartesian(ylim = c(1000, 1150)) # do this ggplot(df, aes(x = x, y = y)) + geom_point(size = 3)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-legend-title","dir":"Articles","previous_headings":"Legends","what":"How can I change the legend title?","title":"FAQ: Customising","text":"Change label aesthetic legend drawn labs(). default legend label name variable mapped aesthetic legend drawn . can change title legend using labs(). legend drawn multiple aesthetics, ’ll want update title .","code":"ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + labs(color = \"Drive train\") # not this ggplot(mpg, aes(x = hwy, y = cty, color = drv, shape = drv)) + geom_point() + labs(color = \"Drive train\") # but this ggplot(mpg, aes(x = hwy, y = cty, color = drv, shape = drv)) + geom_point() + labs(color = \"Drive train\", shape = \"Drive train\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-increase-the-spacing-between-legend-keys","dir":"Articles","previous_headings":"Legends","what":"How can I increase the spacing between legend keys?","title":"FAQ: Customising","text":"Increase horizontal space legend keys legend.spacing.x theme(). argument takes unit object created grid::unit(). horizontal legend, generally placed top bottom plot legend.position = \"top\" \"bottom\", can change spacing legend keys legend.spacing.x. can supply unit object argument, e.g. unit(1.0, \"cm\") 1 cm space legend keys. See documentation grid::unit() options units. vertical legends changing legend.spacing.y changes space legend title keys, keys, e.g. see large space legend title keys. order change space legend keys, can first make key size bigger legend.key.size remove grey background color legend.key. Note legend title longer aligned keys approach. can also shift hjust setting legend.title.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme( legend.position = \"bottom\", legend.spacing.x = unit(1.0, \"cm\") ) ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme(legend.spacing.y = unit(3.0, \"cm\")) ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme( legend.key.size = unit(1.5, \"cm\"), legend.key = element_rect(color = NA, fill = NA) ) ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + theme( legend.key.size = unit(1.5, \"cm\"), legend.key = element_rect(color = NA, fill = NA), legend.title = element_text(hjust = 0.5) )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-key-labels-in-the-legend","dir":"Articles","previous_headings":"Legends","what":"How can I change the key labels in the legend?","title":"FAQ: Customising","text":"don’t want change levels variable legend drawn , can change key labels time drawing plot using labels argument appropriate scale_*() function, e.g. scale_colour_discrete() legend discrete variable mapped fill aesthetic. labels argument scale_* functions takes named vectors, recommend using relabeling keys legend. Using named lists allows declare explicitly label assigned level, without keep track level order.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + geom_point() + scale_color_discrete( labels = c(\"4\" = \"4-wheel drive\", \"f\" = \"Front-wheel drive\", \"r\" = \"Rear-wheel drive\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-font-sizes-in-the-legend","dir":"Articles","previous_headings":"Legends","what":"How can I change the font sizes in the legend?","title":"FAQ: Customising","text":"Set preference legend.text key labels legend.title theme(). cases, set font size size argument element_text(), e.g. legend.text = element_text(size = 14). Font characteristics legend can controlled legend.text legend.title elements theme(). can use following 14 pts text legend key labels 10 pts text legend title. (Note doesn’t result visually pleasing legend, default ggplot2 uses larger font size legend title legend text.) customization legend text, see documentation element_text(), e.g. can change font colors font face well.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = class)) + geom_point() + theme( legend.text = element_text(size = 14), legend.title = element_text(size = 10) ) ggplot(mpg, aes(x = hwy, y = cty, color = class)) + geom_point() + theme( legend.text = element_text(size = 14, color = \"red\"), legend.title = element_text(size = 10, face = \"bold.italic\") )"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-background-colour-of-plot","dir":"Articles","previous_headings":"Colours","what":"How can I change the background colour of plot?","title":"FAQ: Customising","text":"Set color panel.background element theme() element_rect(), takes arguments like fill (background fill color) colour (background border color. can set background colour plot panel.background theme(). following example border made thicker linewidth = 3 want change colour plotting area panel panel, can thing plot.background. Note ggplot2 variety complete themes might already ’re hoping accomplish. example, prefer minimal look plots, without grey background, might try theme_minimal(). can continue customization based one themes. might also find thematic package useful simplified theming plots.","code":"ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme(panel.background = element_rect(fill = \"lightblue\", colour = \"red\", linewidth = 3)) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme(plot.background = element_rect(fill = \"lightblue\", colour = \"red\", linewidth = 3)) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme_minimal() ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + theme_minimal() + theme(plot.background = element_rect(colour = \"red\", linewidth = 3))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-colour-nas-are-represented-with-in-a-plot","dir":"Articles","previous_headings":"Colours","what":"How can I change the colour NAs are represented with in a plot?","title":"FAQ: Customising","text":"can set color NA na.value argument appropriate scale_*() function, e.g. scale_fill_discrete(na.value = \"purple\") make NAs purple. Suppose following data frame two discrete variables, one NA. default, ggplot2 uses grey represent NAs. can change color NA scale_fill_discrete() case, e.g. make purple. can also set color \"transparent\". plot shown theme_minimal() demonstrate looks plot transparent background. Note possible, setting colour transparent wouldn’t recommended particular case gives appearance floating bar.","code":"df <- tibble::tribble( ~group, ~outcome, 1, \"yes\", 1, \"no\", 2, \"yes\", 2, \"no\", 2, \"no\", 2, NA ) ggplot(df, aes(x = group, fill = outcome)) + geom_bar() ggplot(df, aes(x = group, fill = outcome)) + geom_bar() + scale_fill_discrete(na.value = \"purple\") ggplot(df, aes(x = group, fill = outcome)) + geom_bar() + scale_fill_discrete(na.value = \"transparent\") + theme_minimal()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-default-font-size-in-ggplot2","dir":"Articles","previous_headings":"Fonts","what":"How can I change the default font size in ggplot2?","title":"FAQ: Customising","text":"Set base_size theme ’re using, theme_gray() default. base font size 11 pts default. can change base_size argument theme ’re using. See complete theme documentation high level options can set. like plots within session/document use particular base size, can set set_theme(). Run following beginning session include top R Markdown document.","code":"ggplot(mpg, aes(x = hwy, y = cty, color = class)) + geom_point() + theme_gray(base_size = 18) set_theme(theme_gray(base_size = 18))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-font-size-of-the-plot-title-and-subtitle","dir":"Articles","previous_headings":"Fonts","what":"How can I change the font size of the plot title and subtitle?","title":"FAQ: Customising","text":"Set preference plot.title plot.subtitle theme(). cases, set font size size argument element_text(), e.g. plot.title = element_text(size = 20). Font characteristics plot titles subtitles can controlled plot.title plot.subtitle elements theme(). can use following 20 pts text plot title 15 pts text plot subtitle. customization plot title subtitle, see documentation element_text(), e.g. can change font colors font face well.","code":"ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( title = \"This is the plot title\", subtitle = \"And this is the subtitle\" ) + theme( plot.title = element_text(size = 20), plot.subtitle = element_text(size = 15) ) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( title = \"This is the plot title\", subtitle = \"And this is the subtitle\" ) + theme( plot.title = element_text(size = 20, color = \"red\"), plot.subtitle = element_text(size = 15, face = \"bold.italic\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"how-can-i-change-the-font-size-of-axis-labels","dir":"Articles","previous_headings":"Fonts","what":"How can I change the font size of axis labels?","title":"FAQ: Customising","text":"Set preference axis.title. axis.title.x, axis.title.y theme(). cases, set font size size argument element_text(), e.g. axis.text = element_text(size = 14). Font characteristics axis labels can controlled axis.title.x axis.title.y (axis.title settings axes). customization plot title subtitle, see documentation element_text(), e.g. can change font colors font face well. can also change size axis text (e.g. numbers axis ticks) using axis.text (axis.text.x axis.text.y want set different sizes).","code":"ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( x = \"This is HUGE\", y = \"This is small\" ) + theme( axis.title.x = element_text(size = 20), axis.title.y = element_text(size = 10) ) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( x = \"This is HUGE\", y = \"This is tiny\" ) + theme( axis.title.x = element_text(size = 20, color = \"red\"), axis.title.y = element_text(size = 10, face = \"bold.italic\") ) ggplot(mpg, aes(x = hwy, y = cty)) + geom_point() + labs( x = \"The axis labels are the same size\", y = \"The axis labels are the same size\" ) + theme( axis.title = element_text(size = 16), axis.text = element_text(size = 20, color = \"blue\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-customising.html","id":"what-is-the-default-size-of-geom_text-and-how-can-i-change-the-font-size-of-geom_text","dir":"Articles","previous_headings":"Fonts","what":"What is the default size of geom_text() and how can I change the font size of geom_text()?","title":"FAQ: Customising","text":"default font size geom_text() 3.88. can change size using size argument geom_text() single plot. want use updated size, can set update_geom_defaults(), e.g. update_geom_defaults(\"text\", list(size = 6)). One tricky thing size mm size element_text() pt. want match geom_text()’s font size theme’s size, specify size.unit = \"pt\" geom_text() single plot, divide number .pt constant variable update_geom_defaults(). Please refer “Font size” section aesthetic specifications details. Suppose following data frame visualization. can set size text following. can map size aesthetic. following size determined x value scale_size_identity(). want use updated size geom_text() series plots session/R Markdown document, can set use update_geom_defaults() update default size, e.g. want size geom_text() 6, use update_geom_defaults(\"text\", list(size = 6)).","code":"GeomLabel$default_aes$size #> #> expr: ^from_theme(fontsize) #> env: namespace:ggplot2 df <- tibble::tribble( ~x, ~y, ~name, 2, 2, \"two\", 3, 3, \"three\", 4, 4, \"four\" ) ggplot(df, aes(x = x, y = y, label = name)) + geom_text() ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 6) ggplot(df, aes(x = x, y = y, label = name)) + geom_text(aes(size = x)) + scale_size_identity()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"what-is-the-difference-between-facet_wrap-and-facet_grid","dir":"Articles","previous_headings":"Panes","what":"What is the difference between facet_wrap() and facet_grid()?","title":"FAQ: Faceting","text":"simplest answer use facet_wrap() faceting single variable facet_grid() faceting two variables want create grid panes. facet_wrap() commonly used facet plot single categorical variable. facet_grid() commonly used facet plot two categorical variables. Notice results empty panes (e.g. 4-wheel drive 5 cylinders) cars mpg dataset fall categories. can also use facet_wrap() facet two categorical variables. create facets combinations levels variables data exists. facet_wrap() can control number rows /columns resulting plot layout using nrow ncol arguments, respectively. facet_grid() values determined number levels variables ’re faceting . Similarly, can also use facet_grid() facet single categorical variable well. formula notation, use . indicate faceting done along axis, .e. cyl ~ . facets across y-axis (within column) . ~ cyl facets across x-axis (within row).","code":"ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_wrap(~ drv) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(cyl ~ drv) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_wrap(cyl ~ drv) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(cyl ~ .) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(. ~ cyl) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`."},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-place-a-vertical-lines-geom_vline-in-each-pane-of-a-faceted-plot","dir":"Articles","previous_headings":"Panes","what":"How can I place a vertical lines (geom_vline()) in each pane of a faceted plot?","title":"FAQ: Faceting","text":"First, calculate lines placed save information separate data frame. , add geom_vline() layer plot uses summarized data. Suppose following plot, want add vertical line mean value hwy (highway mileage) pane. First, calculate means save new data frame. , add geom_vline() layer plot uses summary data.","code":"ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 5) + facet_wrap(~ drv) library(dplyr) #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union mpg_summary <- mpg %>% group_by(drv) %>% summarise(hwy_mean = mean(hwy)) mpg_summary #> # A tibble: 3 × 2 #> drv hwy_mean #> #> 1 4 19.2 #> 2 f 28.2 #> 3 r 21 ggplot(mpg, aes(x = hwy)) + geom_histogram(binwidth = 5) + facet_wrap(~ drv) + geom_vline(data = mpg_summary, aes(xintercept = hwy_mean))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-set-individual-axis-limits-for-facets","dir":"Articles","previous_headings":"Axes","what":"How can I set individual axis limits for facets?","title":"FAQ: Faceting","text":"Either let ggplot2 determine custom axis limits facets based range data ’re plotting using scales argument facet_wrap() facet_grid() , sufficient, use expand_limits() ensure limits include single value range values. Suppose following faceted plot. default, x y scales shared across facets. can control behaviour scales argument faceting functions: varying scales across rows (\"free_x\"), columns (\"free_y\"), rows columns (\"free\"), e.g. also want make sure particular value range included facets, can set expand_limits(), e.g. ensure 10 included x-axis values 20 25 included y-axis:","code":"ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv) ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv, scales = \"free\") ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv, scales = \"free\") + expand_limits(x = 10, y = c(20, 25))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-remove-the-facet-labels-entirely","dir":"Articles","previous_headings":"Facet labels","what":"How can I remove the facet labels entirely?","title":"FAQ: Faceting","text":"Set strip.text element theme() element_blank(). Setting strip.text element_blank() remove facet labels. can also remove labels across rows strip.x.text across columns strip.y.text.","code":"ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv) + theme(strip.text = element_blank()) ggplot(mpg, aes(x = cty, y = hwy)) + geom_point() + facet_grid(cyl ~ drv) + theme(strip.text.x = element_blank())"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"the-facet-labels-in-my-plot-are-too-long-so-they-get-cut-off--how-can-i-wrap-facet-label-text-so-that-long-labels-are-spread-across-two-rows","dir":"Articles","previous_headings":"Facet labels","what":"The facet labels in my plot are too long so they get cut off. How can I wrap facet label text so that long labels are spread across two rows?","title":"FAQ: Faceting","text":"Use label_wrap_gen() labeller argument faceting function set width (number characters) maximum number characters wrapping strip. data frame 100 observations, 50 come one group 50 another. groups long names, facet ploy group, facet labels (strips) get cut . can control maximum width facet label setting width label_wrap_gen() function, passed labeller argument faceting function.","code":"df <- data.frame( x = rnorm(100), group = c(rep(\"A long group name for the first group\", 50), rep(\"A muuuuuuuuuuuuuch longer group name for the second group\", 50)) ) ggplot(df, aes(x = x)) + geom_histogram(binwidth = 0.5) + facet_wrap(~ group) ggplot(df, aes(x = x)) + geom_histogram(binwidth = 0.5) + facet_wrap(~ group, labeller = labeller(group = label_wrap_gen(width = 25)))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-faceting.html","id":"how-can-i-set-different-axis-labels-for-facets","dir":"Articles","previous_headings":"Facet labels","what":"How can I set different axis labels for facets?","title":"FAQ: Faceting","text":"Use as_labeller() labeller argument faceting function set strip.background strip.placement elements theme() place facet labels axis labels go. particularly useful solution plotting data different scales without use double y-axes. Suppose data price data given item years two countries different currency scales. can plot price versus time facet country, resulting plot can bit difficult read due shared y-axis label. following can customize facet labels first as_labeller(), turn default y-axis label, place facet labels y-axis label goes (\"outside\" \"left\").","code":"df <- data.frame( year = rep(2016:2021, 2), price = c(10, 10, 13, 12, 14, 15, 1000, 1010, 1200, 1050, 1105, 1300), country = c(rep(\"US\", 6), rep(\"Japan\", 6)) ) df #> year price country #> 1 2016 10 US #> 2 2017 10 US #> 3 2018 13 US #> 4 2019 12 US #> 5 2020 14 US #> 6 2021 15 US #> 7 2016 1000 Japan #> 8 2017 1010 Japan #> 9 2018 1200 Japan #> 10 2019 1050 Japan #> 11 2020 1105 Japan #> 12 2021 1300 Japan ggplot(df, aes(x = year, y = price)) + geom_smooth() + facet_wrap(~ country, ncol = 1, scales = \"free_y\") + scale_x_continuous(breaks = 2011:2020) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(df, aes(x = year, y = price)) + geom_smooth() + facet_wrap(~ country, ncol = 1, scales = \"free_y\", labeller = as_labeller( c(US = \"US Dollars (USD)\", Japan = \"Japanese Yens (JPY)\")), strip.position = \"left\" ) + scale_x_continuous(breaks = 2011:2020) + labs(y = NULL) + theme(strip.background = element_blank(), strip.placement = \"outside\") #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' #> Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; #> returning -Inf #> Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; #> returning -Inf"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-reorder-the-bars-in-a-bar-plot-by-their-value","dir":"Articles","previous_headings":"Bar plots","what":"How can I reorder the bars in a bar plot by their value?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re creating bar plot aesthetic mapping. forcats package offers variety options , forcats::fct_infreq() ordering number observations within level. following bar plot shows number cars fall class category. Classes ordered alphabetically. might prefer ordered number cars class. , can use forcats::fct_infreq(). ’d like plot highest value first, can also reverse order forcats::fct_rev(). might also want simplify axis label.","code":"ggplot(mpg, aes(y = class)) + geom_bar() ggplot(mpg, aes(y = forcats::fct_infreq(class))) + geom_bar() ggplot(mpg, aes(y = forcats::fct_rev(forcats::fct_infreq(class)))) + geom_bar() + labs(y = \"class\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-reorder-the-stacks-in-a-stacked-bar-plot","dir":"Articles","previous_headings":"Bar plots","what":"How can I reorder the stacks in a stacked bar plot?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re creating stacks aesthetic mapping. forcats package offers variety options , forcats::fct_reorder() reorder levels forcats::fct_rev() reverse order. Suppose following stacked bar plot clarity diamonds cut. can reverse order clarity levels displayed bars forcats::fct_rev(). also change order ’re presented legend two orders match.","code":"ggplot(diamonds, aes(x = cut, fill = clarity)) + geom_bar() ggplot(diamonds, aes(x = cut, fill = forcats::fct_rev(clarity))) + geom_bar() + labs(fill = \"clarity\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-control-the-order-of-boxes-in-a-side-by-side-box-plot","dir":"Articles","previous_headings":"Box plots","what":"How can I control the order of boxes in a side-by-side box plot?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re faceting . forcats package offers variety options , forcats::fct_relevel() manual reordering forcats::fct_reorder() ordering particular value, e.g. group median. order boxes determined order levels variable ’re grouping . faceting variable character, order alphabetical default. Suppose ’d like boxes ordered ascending order medians. can data transformation step prior plotting (e.g. dplyr::mutate()) can directly plotting code shown . might want customize x-axis label well.","code":"ggplot(mpg, aes(x = class, y = hwy)) + geom_boxplot() ggplot(mpg, aes(x = forcats::fct_reorder(class, hwy, .fun = median), y = hwy)) + geom_boxplot() + labs(x = \"class\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-control-the-order-of-panes-created-with-facet_wrap-or-facet_grid","dir":"Articles","previous_headings":"Facets","what":"How can I control the order of panes created with facet_wrap() or facet_grid()?","title":"FAQ: Reordering","text":"Change order levels factor variable ’re faceting . forcats package offers variety options , forcats::fct_relevel(). order panes determined order levels variable ’re faceting . faceting variable character, order alphabetical default. Suppose ’d like panes order \"r\", \"f\" , \"4\". can use forcats::fct_relevel() reorder levels drv. can data transformation step prior plotting (e.g. dplyr::mutate()) can directly plotting code shown .","code":"ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_wrap(~drv) ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + facet_wrap(~forcats::fct_relevel(drv, \"r\", \"f\", \"4\"))"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/faq-reordering.html","id":"how-can-i-control-the-order-of-the-points-plotted","dir":"Articles","previous_headings":"Overplotting","what":"How can I control the order of the points plotted?","title":"FAQ: Reordering","text":"specific point (group points) want make sure plotted top others, subset data observations add new layer plot. Suppose following data frame. default, scatterplot looks. Note blue circle partially covered yellow triangle since observation comes later dataset. Similarly black asterisk appears top red square. Suppose arranged data ascending order x-coordinates plotted . Now blue circle yellow triangle since 0.01 comes 0 similarly red square black asterisk since 1 comes 0.99. wanted make sure observation identified asterisk always plotted top, regardless data arranged data frame, can create additional layer observation.","code":"df <- tibble::tribble( ~id, ~x, ~y, ~shape, ~fill, 1, 0.01, 0, \"circle filled\", \"blue\", 2, 1, 0, \"square filled\", \"red\", 3, 0.99, 0, \"asterisk\", \"black\", 4, 0, 0, \"triangle filled\", \"yellow\" ) ggplot(df, aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(size = 8) + scale_shape_identity() + scale_fill_identity() df_arranged <- df %>% dplyr::arrange(x) df_arranged %>% ggplot(aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(size = 8) + scale_shape_identity() + scale_fill_identity() ggplot(mapping = aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(data = df %>% filter(shape != \"asterisk\"), size = 8) + geom_point(data = df %>% filter(shape == \"asterisk\"), size = 8) + scale_shape_identity() + scale_fill_identity() ggplot(mapping = aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(data = df_arranged %>% filter(shape != \"asterisk\"), size = 8) + geom_point(data = df_arranged %>% filter(shape == \"asterisk\"), size = 8) + scale_shape_identity() + scale_fill_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"referring-to-ggplot2-functions","dir":"Articles","previous_headings":"","what":"Referring to ggplot2 functions","title":"Using ggplot2 in packages","text":"function another package, list ggplot2 DESCRIPTION Imports refer functions using :: (e.g., ggplot2::function_name): use ggplot2 functions frequently, may wish import one functions ggplot2 NAMESPACE. use roxygen2, can include #' @importFrom ggplot2 roxygen comment block (work datasets like mpg). Even use many ggplot2 functions package, unwise use ggplot2 Depends import entire package NAMESPACE (e.g. #' @import ggplot2). Using ggplot2 Depends attach ggplot2 package attached, includes package tested. makes difficult ensure others can use functions package without attaching (.e., using ::). Similarly, importing 450 ggplot2’s exported objects namespace makes difficult separate responsibility package responsibility ggplot2, addition making difficult readers code figure functions coming !","code":"mpg_drv_summary <- function() { ggplot2::ggplot(ggplot2::mpg) + ggplot2::geom_bar(ggplot2::aes(x = .data$drv)) + ggplot2::coord_flip() } #' @importFrom ggplot2 ggplot aes geom_bar coord_flip mpg_drv_summary <- function() { ggplot(ggplot2::mpg) + geom_bar(aes(x = drv)) + coord_flip() }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"using-aes-and-vars-in-a-package-function","dir":"Articles","previous_headings":"","what":"Using aes() and vars() in a package function","title":"Using ggplot2 in packages","text":"create graphic using ggplot2 probably need use aes() least . graphic uses facets, might using vars() refer columns plot/layer data. functions use non-standard evaluation, try use function within package result CMD check note: three situations encounter problem: already know column name expression advance. column name character vector. user specifies column name expression, want function use kind non-standard evaluation used aes() vars(). already know mapping advance (like example) use .data pronoun rlang make explicit referring drv layer data variable named drv (may may exist elsewhere). avoid similar note CMD check .data, use #' @importFrom rlang .data roxygen code block (typically package documentation generated usethis::use_package_doc()). column name character vector (e.g., col = \"drv\"), use .data[[col]]: column name expression supplied user, can also pass aes() vars() using {{ col }}. tidy eval operator captures expression supplied user forwards another tidy eval-enabled function aes() vars(). summarise: know mapping facet specification col advance, use aes(.data$col) vars(.data$col). col variable contains column name character vector, use aes(.data[[col]] vars(.data[[col]]). like behaviour col look feel like within aes() vars(), use aes({{ col }}) vars({{ col }}). see lot ways wild, syntax use one can guarantee work future! particular, don’t use aes_() aes_string(), deprecated may removed future version. Finally, don’t skip step creating data frame mapping pass ggplot() layers! see ways , may rely undocumented behaviour can fail unexpected ways.","code":"mpg_drv_summary <- function() { ggplot(ggplot2::mpg) + geom_bar(aes(y = drv)) + facet_wrap(vars(year)) } N checking R code for possible problems (2.7s) mpg_drv_summary: no visible binding for global variable ‘drv’ Undefined global functions or variables: drv mpg_drv_summary <- function() { ggplot(ggplot2::mpg) + geom_bar(aes(y = .data$drv)) + facet_wrap(vars(.data$year)) } col_summary <- function(df, col, by) { ggplot(df) + geom_bar(aes(y = .data[[col]])) + facet_wrap(vars(.data[[by]])) } col_summary(mpg, \"drv\", \"year\") col_summary <- function(df, col, by) { ggplot(df) + geom_bar(aes(y = {{ col }})) + facet_wrap(vars({{ by }})) } col_summary(mpg, drv, year)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"using-ggplot2-to-visualize-an-object","dir":"Articles","previous_headings":"Best practices for common tasks","what":"Using ggplot2 to visualize an object","title":"Using ggplot2 in packages","text":"ggplot2 commonly used packages visualize objects (e.g., plot()-style function). example, package might define S3 class represents probability various discrete values: Many S3 classes R plot() method, unrealistic expect single plot() method can provide visualization every one users looking . useful, however, provide plot() method visual summary users can call understand essence object. satisfy users, suggest writing function transforms object data frame (list() data frames object complicated). good example approach ggdendro, creates dendrograms using ggplot2 also computes data necessary users make . example, function might look like : general, users plot() call side-effects: results graphic displayed. different behaviour ggplot(), displayed unless explicitly print()ed. , ggplot2 defines generic autoplot(), call expected return ggplot() (side effects). autoplot() method defined, plot() method can consist print()ing result autoplot(): considered bad practice implement S3 generic like plot(), autoplot() don’t S3 class, makes hard package developer control S3 implement method . shouldn’t stop creating functions visualize objects!","code":"mpg_drv_dist <- structure( c( \"4\" = 103 / 234, \"f\" = 106 / 234, \"r\" = 25 / 234 ), class = \"discrete_distr\" ) discrete_distr_data <- function(x) { tibble::tibble( value = names(x), probability = as.numeric(x) ) } discrete_distr_data(mpg_drv_dist) #> # A tibble: 3 × 2 #> value probability #> #> 1 4 0.440 #> 2 f 0.453 #> 3 r 0.107 #' @importFrom ggplot2 autoplot autoplot.discrete_distr <- function(object, ...) { plot_data <- discrete_distr_data(object) ggplot(plot_data, aes(.data$value, .data$probability)) + geom_col() + coord_flip() + labs(x = \"Value\", y = \"Probability\") } #' @importFrom graphics plot plot.discrete_distr <- function(x, ...) { print(autoplot(x, ...)) }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"creating-a-new-theme","dir":"Articles","previous_headings":"Best practices for common tasks","what":"Creating a new theme","title":"Using ggplot2 in packages","text":"creating new theme, ’s always good practice start existing theme (e.g. theme_grey()) %+replace% elements changed. right strategy even seemingly elements replaced, makes difficult us improve themes adding new elements. many excellent examples themes ggthemes package. important theme calculated package loaded. , theme object stored compiled bytecode built package, may may align installed version ggplot2! package default theme visualizations, correct way load function returns default theme:","code":"#' @importFrom ggplot2 %+replace% theme_custom <- function(...) { theme_grey(...) %+replace% theme( panel.border = element_rect(linewidth = 1, fill = NA), panel.background = element_blank(), panel.grid = element_line(colour = \"grey80\") ) } mpg_drv_summary() + theme_custom() default_theme <- function() { theme_custom() } mpg_drv_summary2 <- function() { mpg_drv_summary() + default_theme() }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"testing-ggplot2-output","dir":"Articles","previous_headings":"Best practices for common tasks","what":"Testing ggplot2 output","title":"Using ggplot2 in packages","text":"suggest testing output ggplot2 using vdiffr package, tool manage visual test cases (one ways test ggplot2). changes ggplot2 code introduce change visual output ggplot, tests fail run locally part Continuous Integration setup. use vdiffr, make sure using testthat (can use usethis::use_testthat() get started) add vdiffr Suggests DESCRIPTION. , use vdiffr::expect_doppleganger(, ) make test fails visual changes . However, consider whether visual testing best strategy adds dependency ggplot2 performs rendering may change versions. extracting layer data using get_layer_data() testing values directly possible far better directly test behaviour code.","code":"test_that(\"output of ggplot() is stable\", { vdiffr::expect_doppelganger(\"A blank plot\", ggplot()) })"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"ggplot2-in-suggests","dir":"Articles","previous_headings":"Best practices for common tasks","what":"ggplot2 in Suggests","title":"Using ggplot2 in packages","text":"use ggplot2 package, likely want list Imports. like list ggplot2 Suggests instead, able #' @importFrom ggplot2 ... (.e., must refer ggplot2 objects using ::). use infix operators ggplot2 like %+replace% want keep ggplot2 Suggests, can assign operator within function used: Generally, add method ggplot2 generic like autoplot(), ggplot2 Imports. reason like keep ggplot2 Suggests, possible register generics ggplot2 installed using vctrs::s3_register(). , copy paste source vctrs::s3_register() package avoid adding vctrs dependency.","code":"theme_custom <- function(...) { `%+replace%` <- ggplot2::`%+replace%` ggplot2::theme_grey(...) %+replace% ggplot2::theme(panel.background = ggplot2::element_blank()) } .onLoad <- function(...) { if (requireNamespace(\"ggplot2\", quietly = TRUE)) { vctrs::s3_register(\"ggplot2::autoplot\", \"discrete_distr\") } }"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-in-packages.html","id":"read-more","dir":"Articles","previous_headings":"","what":"Read more","title":"Using ggplot2 in packages","text":"things consider taking dependency. post goes detail many using ggplot2 example good read anyone developing package using ggplot2.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"colour-and-fill","dir":"Articles","previous_headings":"","what":"Colour and fill","title":"Aesthetic specifications","text":"Almost every geom either colour, fill, . Colours fills can specified following ways: name, e.g., \"red\". R 657 built-named colours, can listed colours(). rgb specification, string form \"#RRGGBB\" pairs RR, GG, BB consists two hexadecimal digits giving value range 00 FF can optionally make colour transparent using form \"#RRGGBBAA\". NA, completely transparent colour. munsell package, Charlotte Wickham, makes easy choose specific colours using system designed Albert H. Munsell. invest little learning system, provides convenient way specifying aesthetically pleasing colours.","code":"munsell::mnsl(\"5PB 5/10\") #> [1] \"#447DBF\""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"lines","dir":"Articles","previous_headings":"","what":"Lines","title":"Aesthetic specifications","text":"well colour, appearance line affected linewidth, linetype, linejoin lineend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"sec:line-type-spec","dir":"Articles","previous_headings":"Lines","what":"Line type","title":"Aesthetic specifications","text":"Line types can specified : integer name: 0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash, shown : lengths /stretches line. done string containing 2, 4, 6, 8 hexadecimal digits give lengths consecutive lengths. example, string \"33\" specifies three units followed three \"3313\" specifies three units followed three followed one finally three . five standard dash-dot line types described correspond 44, 13, 1343, 73, 2262.","code":"lty <- c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\") linetypes <- data.frame( y = seq_along(lty), lty = lty ) ggplot(linetypes, aes(0, y)) + geom_segment(aes(xend = 5, yend = y, linetype = lty)) + scale_linetype_identity() + geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) + scale_x_continuous(NULL, breaks = NULL) + scale_y_reverse(NULL, breaks = NULL) lty <- c(\"11\", \"18\", \"1f\", \"81\", \"88\", \"8f\", \"f1\", \"f8\", \"ff\") linetypes <- data.frame( y = seq_along(lty), lty = lty ) ggplot(linetypes, aes(0, y)) + geom_segment(aes(xend = 5, yend = y, linetype = lty)) + scale_linetype_identity() + geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) + scale_x_continuous(NULL, breaks = NULL) + scale_y_reverse(NULL, breaks = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"linewidth","dir":"Articles","previous_headings":"Lines","what":"Linewidth","title":"Aesthetic specifications","text":"Due historical error, unit linewidth roughly 0.75 mm. Making exactly 1 mm change large number existing plots, ’re stuck mistake.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"line-endjoin-paramters","dir":"Articles","previous_headings":"Lines","what":"Line end/join paramters","title":"Aesthetic specifications","text":"appearance line end controlled lineend paramter, can one “round”, “butt” (default), “square”. appearance line joins controlled linejoin can one “round” (default), “mitre”, “bevel”. Mitre joins automatically converted bevel joins whenever angle small (create long bevel). controlled linemitre parameter specifies maximum ratio line width length mitre.","code":"df <- data.frame(x = 1:3, y = c(4, 1, 9)) base <- ggplot(df, aes(x, y)) + xlim(0.5, 3.5) + ylim(0, 10) base + geom_path(linewidth = 10) + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, lineend = \"round\") + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, lineend = \"square\") + geom_path(linewidth = 1, colour = \"red\") df <- data.frame(x = 1:3, y = c(9, 1, 9)) base <- ggplot(df, aes(x, y)) + ylim(0, 10) base + geom_path(linewidth = 10) + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, linejoin = \"mitre\") + geom_path(linewidth = 1, colour = \"red\") base + geom_path(linewidth = 10, linejoin = \"bevel\") + geom_path(linewidth = 1, colour = \"red\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"polygons","dir":"Articles","previous_headings":"","what":"Polygons","title":"Aesthetic specifications","text":"border polygon controlled colour, linetype, linewidth aesthetics described . inside controlled fill.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"sec:shape-spec","dir":"Articles","previous_headings":"Point","what":"Shape","title":"Aesthetic specifications","text":"Shapes take five types values: integer [0,25][0, 25]: name shape: single character, use character plotting symbol. . draw smallest rectangle visible, usually 1 pixel. NA, draw nothing.","code":"shapes <- data.frame( shape = c(0:19, 22, 21, 24, 23, 20), x = 0:24 %/% 5, y = -(0:24 %% 5) ) ggplot(shapes, aes(x, y)) + geom_point(aes(shape = shape), size = 5, fill = \"red\") + geom_text(aes(label = shape), hjust = 0, nudge_x = 0.15) + scale_shape_identity() + expand_limits(x = 4.1) + theme_void() shape_names <- c( \"circle\", paste(\"circle\", c(\"open\", \"filled\", \"cross\", \"plus\", \"small\")), \"bullet\", \"square\", paste(\"square\", c(\"open\", \"filled\", \"cross\", \"plus\", \"triangle\")), \"diamond\", paste(\"diamond\", c(\"open\", \"filled\", \"plus\")), \"triangle\", paste(\"triangle\", c(\"open\", \"filled\", \"square\")), paste(\"triangle down\", c(\"open\", \"filled\")), \"plus\", \"cross\", \"asterisk\" ) shapes <- data.frame( shape_names = shape_names, x = c(1:7, 1:6, 1:3, 5, 1:3, 6, 2:3, 1:3), y = -rep(1:6, c(7, 6, 4, 4, 2, 3)) ) ggplot(shapes, aes(x, y)) + geom_point(aes(shape = shape_names), fill = \"red\", size = 5) + geom_text(aes(label = shape_names), nudge_y = -0.3, size = 3.5) + scale_shape_identity() + theme_void()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"colour-and-fill-1","dir":"Articles","previous_headings":"Point","what":"Colour and fill","title":"Aesthetic specifications","text":"colour applies shapes, fill applies shapes 21-25, can seen . size filled part controlled size, size stroke controlled stroke. measured mm, total size point sum two. Note size constant along diagonal following figure.","code":"sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2) ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) + geom_abline(slope = -1, intercept = 6, colour = \"white\", linewidth = 6) + geom_point(shape = 21, fill = \"red\") + scale_size_identity()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"font-family","dir":"Articles","previous_headings":"Text","what":"Font family","title":"Aesthetic specifications","text":"three fonts guaranteed work everywhere: “sans” (default), “serif”, “mono”: ’s trickier include system font plot text drawing done differently graphics device (GD). five GDs common use (png(), pdf(), screen devices Windows, Mac Linux), font work everywhere need configure five devices five different ways. Two packages simplify quandary bit: showtext makes GD-independent plots rendering text polygons. extrafont converts fonts standard format devices can use. approaches pros cons, need try see works best needs.","code":"df <- data.frame(x = 1, y = 3:1, family = c(\"sans\", \"serif\", \"mono\")) ggplot(df, aes(x, y)) + geom_text(aes(label = family, family = family))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"font-face","dir":"Articles","previous_headings":"Text","what":"Font face","title":"Aesthetic specifications","text":"","code":"df <- data.frame(x = 1:4, fontface = c(\"plain\", \"bold\", \"italic\", \"bold.italic\")) ggplot(df, aes(1, x)) + geom_text(aes(label = fontface, fontface = fontface))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"font-size","dir":"Articles","previous_headings":"Text","what":"Font size","title":"Aesthetic specifications","text":"size text measured mm default. unusual, makes size text consistent size lines points. Typically specify font size using points (pt short), 1 pt = 0.35mm. geom_text() geom_label(), can set size.unit = \"pt\" use points instead millimeters. addition, ggplot2 provides conversion factor variable .pt, want draw 12pt text, can also set size = 12 / .pt.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2-specs.html","id":"justification","dir":"Articles","previous_headings":"Text","what":"Justification","title":"Aesthetic specifications","text":"Horizontal vertical justification parameterisation, either string (“top”, “middle”, “bottom”, “left”, “center”, “right”) number 0 1: top = 1, middle = 0.5, bottom = 0 left = 0, center = 0.5, right = 1 Note can use numbers outside range (0, 1), ’s recommended.","code":"just <- expand.grid(hjust = c(0, 0.5, 1), vjust = c(0, 0.5, 1)) just$label <- paste0(just$hjust, \", \", just$vjust) ggplot(just, aes(hjust, vjust)) + geom_point(colour = \"grey70\", size = 5) + geom_text(aes(label = label, hjust = hjust, vjust = vjust))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"data","dir":"Articles","previous_headings":"","what":"Data","title":"Introduction to ggplot2","text":"foundation every graphic, ggplot2 uses data construct plot. system works best data provided tidy format, briefly means rectangular data frame structure rows observations columns variables. first step many plots, pass data ggplot() function, stores data used later parts plotting system. example, intend make graphic mpg dataset, start follows:","code":"ggplot(data = mpg)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"mapping","dir":"Articles","previous_headings":"","what":"Mapping","title":"Introduction to ggplot2","text":"mapping plot set instructions parts data mapped onto aesthetic attributes geometric objects. ‘dictionary’ translate tidy data graphics system. mapping can made using aes() function make pairs graphical attributes parts data. want cty hwy columns map x- y-coordinates plot, can follows:","code":"ggplot(mpg, mapping = aes(x = cty, y = hwy))"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"layers","dir":"Articles","previous_headings":"","what":"Layers","title":"Introduction to ggplot2","text":"heart graphic layers. take mapped data display something humans can understand representation data. Every layer consists three important parts: geometry determines data displayed, points, lines, rectangles. statistical transformation may compute new variables data affect data displayed. position adjustment primarily determines piece data displayed. layer can constructed using geom_*() stat_*() functions. functions often determine one three parts layer, two can still specified. can use two layers display cty hwy columns mpg dataset points stack trend line top.","code":"ggplot(mpg, aes(cty, hwy)) + # to create a scatterplot geom_point() + # to fit and overlay a loess trendline geom_smooth(formula = y ~ x, method = \"lm\")"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"scales","dir":"Articles","previous_headings":"","what":"Scales","title":"Introduction to ggplot2","text":"Scales important translating shown graph back understanding data. scales typically form pairs aesthetic attributes plots, represented plots guides, like axes legends. Scales responsible updating limits plot, setting breaks, formatting labels, possibly applying transformation. use scales, one can use one scale functions patterned scale_{aesthetic}_{type}() functions, {aesthetic} one pairings made mapping part plot. map class column mpg dataset viridis colour palette, can write following:","code":"ggplot(mpg, aes(cty, hwy, colour = class)) + geom_point() + scale_colour_viridis_d()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"facets","dir":"Articles","previous_headings":"","what":"Facets","title":"Introduction to ggplot2","text":"Facets can used separate small multiples, different subsets data. powerful tool quickly split data smaller panels, based one variables, display patterns trends (lack thereof) within subsets. facets mapping can given formula. plot subsets mpg dataset based levels drv year variables, can use facet_grid() follows:","code":"ggplot(mpg, aes(cty, hwy)) + geom_point() + facet_grid(year ~ drv)"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"coordinates","dir":"Articles","previous_headings":"","what":"Coordinates","title":"Introduction to ggplot2","text":"can view coordinates part plot interpreter position aesthetics. typically Cartesian coordinates used, coordinate system powers display map projections polar plots. can also use coordinates display plot fixed aspect ratio one unit length x y directions. coord_fixed() function sets ratio automatically.","code":"ggplot(mpg, aes(cty, hwy)) + geom_point() + coord_fixed()"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"theme","dir":"Articles","previous_headings":"","what":"Theme","title":"Introduction to ggplot2","text":"theme system controls almost visuals plot controlled data therefore important look feel plot. can use theme customizations ranging changing location legends setting background color plot. Many elements theme hierarchical setting look general axis line affects x y axes simultaneously. tweak look plot, one can use many built-theme_*() functions /detail specific aspects theme() function. element_*() functions control graphical attributes theme components.","code":"ggplot(mpg, aes(cty, hwy, colour = class)) + geom_point() + theme_minimal() + theme( legend.position = \"top\", axis.line = element_line(linewidth = 0.75), axis.line.x.bottom = element_line(colour = \"blue\") )"},{"path":"https://ggplot2.tidyverse.org/dev/articles/ggplot2.html","id":"combining","dir":"Articles","previous_headings":"","what":"Combining","title":"Introduction to ggplot2","text":"mentioned start, can layer pieces build customized plot data, like one shown beginning vignette: want learn , sure take look ggplot2 book.","code":"ggplot(mpg, aes(cty, hwy)) + geom_point(mapping = aes(colour = displ)) + geom_smooth(formula = y ~ x, method = \"lm\") + scale_colour_viridis_c() + facet_grid(year ~ drv) + coord_fixed() + theme_minimal() + theme(panel.grid.minor = element_blank())"},{"path":"https://ggplot2.tidyverse.org/dev/articles/profiling.html","id":"performance-focused-changes-across-versions","dir":"Articles","previous_headings":"","what":"Performance focused changes across versions","title":"Profiling Performance","text":"keep track changes focused improving performance gtable summarised :","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/profiling.html","id":"v3-5-1-9000","dir":"Articles","previous_headings":"Performance focused changes across versions","what":"v3.5.1.9000","title":"Profiling Performance","text":"Avoid costly factor construction scale_apply issue really appeared plotting huge datasets (>1e6 rows). order train map position aesthetics rows matched based panel. require splitting row indexes panel included factor() call. factor constructor slow large vectors can simplified considerably specific case. , split can avoided completely one panel","code":""},{"path":"https://ggplot2.tidyverse.org/dev/articles/profiling.html","id":"v3-1-0","dir":"Articles","previous_headings":"Performance focused changes across versions","what":"v3.1.0","title":"Profiling Performance","text":"Caching calls grid::descentDetails() absolute biggest offender construction titles. recent versions included calls grid::descentDetails() ensure aligned across plots, quite heavy. calls now cached calculated per font setting. Use performant data.frame constructor throughout codebase data.frame() function carries lot overhead order sanitize check input. generally needed sure input just lead slower code. data.frame() call now used dealing output packages extra safety benefit. Use performant alternative utils::modifyList modifyList() nice convenience function carries lot overhead. mainly used plot element constructions slowed application theme settings. performant version added used throughout. Speed position transformation transform_position helper unreasonably slow due slowness getting assigning columns data.frame. input now treated list transformation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/authors.html","id":null,"dir":"","previous_headings":"","what":"Authors","title":"Authors and Citation","text":"Hadley Wickham. Author. Winston Chang. Author. Lionel Henry. Author. Thomas Lin Pedersen. Author, maintainer. Kohske Takahashi. Author. Claus Wilke. Author. Kara Woo. Author. Hiroaki Yutani. Author. Dewey Dunnington. Author. Teun van den Brand. Author. . Copyright holder, funder.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/authors.html","id":"citation","dir":"","previous_headings":"","what":"Citation","title":"Authors and Citation","text":"H. Wickham. ggplot2: Elegant Graphics Data Analysis. Springer-Verlag New York, 2016.","code":"@Book{, author = {Hadley Wickham}, title = {ggplot2: Elegant Graphics for Data Analysis}, publisher = {Springer-Verlag New York}, year = {2016}, isbn = {978-3-319-24277-4}, url = {https://ggplot2.tidyverse.org}, }"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"overview","dir":"","previous_headings":"","what":"Overview","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"ggplot2 system declaratively creating graphics, based Grammar Graphics. provide data, tell ggplot2 map variables aesthetics, graphical primitives use, takes care details.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"installation","dir":"","previous_headings":"","what":"Installation","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"","code":"# The easiest way to get ggplot2 is to install the whole tidyverse: install.packages(\"tidyverse\") # Alternatively, install just ggplot2: install.packages(\"ggplot2\") # Or the development version from GitHub: # install.packages(\"pak\") pak::pak(\"tidyverse/ggplot2\")"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"usage","dir":"","previous_headings":"","what":"Usage","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"’s hard succinctly describe ggplot2 works embodies deep philosophy visualisation. However, cases start ggplot(), supply dataset aesthetic mapping (aes()). add layers (like geom_point() geom_histogram()), scales (like scale_colour_brewer()), faceting specifications (like facet_wrap()) coordinate systems (like coord_flip()).","code":"library(ggplot2) ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"lifecycle","dir":"","previous_headings":"","what":"Lifecycle","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"ggplot2 now 10 years old used hundreds thousands people make millions plots. means, --large, ggplot2 changes relatively little. make changes, generally add new functions arguments rather changing behaviour existing functions, make changes existing behaviour compelling reasons. looking innovation, look ggplot2’s rich ecosystem extensions. See community maintained list https://exts.ggplot2.tidyverse.org/gallery/.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"learning-ggplot2","dir":"","previous_headings":"","what":"Learning ggplot2","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"new ggplot2 better starting systematic introduction, rather trying learn reading individual documentation pages. Currently, three good places start: Data Visualization Communication chapters R Data Science. R Data Science designed give comprehensive introduction tidyverse, two chapters get speed essentials ggplot2 quickly possible. ’d like take online course, try Data Visualization R ggplot2 Kara Woo. ’d like follow webinar, try Plotting Anything ggplot2 Thomas Lin Pedersen. want dive making common graphics quickly possible, recommend R Graphics Cookbook Winston Chang. provides set recipes solve common graphics problems. ’ve mastered basics want learn , read ggplot2: Elegant Graphics Data Analysis. describes theoretical underpinnings ggplot2 shows pieces fit together. book helps understand theory underpins ggplot2, help create new types graphics specifically tailored needs.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/index.html","id":"getting-help","dir":"","previous_headings":"","what":"Getting help","title":"Create Elegant Data Visualisations Using the Grammar of Graphics","text":"two main places get help ggplot2: RStudio community friendly place ask questions ggplot2. Stack Overflow great source answers common ggplot2 questions. also great place get help, created reproducible example illustrates problem.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/absoluteGrob.html","id":null,"dir":"Reference","previous_headings":"","what":"Absolute grob — absoluteGrob","title":"Absolute grob — absoluteGrob","text":"grob fixed dimensions position.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/absoluteGrob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Absolute grob — absoluteGrob","text":"","code":"absoluteGrob( grob, width = NULL, height = NULL, xmin = NULL, ymin = NULL, vp = NULL )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/absoluteGrob.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Absolute grob — absoluteGrob","text":"still experimental","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/add_theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify properties of an element in a theme object — add_theme","title":"Modify properties of an element in a theme object — add_theme","text":"Modify properties element theme object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/add_theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify properties of an element in a theme object — add_theme","text":"","code":"add_theme(t1, t2, t2name, call = caller_env())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/add_theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify properties of an element in a theme object — add_theme","text":"t1 theme object t2 theme object added t1 t2name name t2 object. used printing informative error messages.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":null,"dir":"Reference","previous_headings":"","what":"Construct aesthetic mappings — aes","title":"Construct aesthetic mappings — aes","text":"Aesthetic mappings describe variables data mapped visual properties (aesthetics) geoms. Aesthetic mappings can set ggplot() individual layers.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Construct aesthetic mappings — aes","text":"","code":"aes(x, y, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Construct aesthetic mappings — aes","text":"x, y, ... List name-value pairs form aesthetic = variable describing variables layer data mapped aesthetics used paired geom/stat. expression variable evaluated within layer data, need refer original dataset (.e., use ggplot(df, aes(variable)) instead ggplot(df, aes(df$variable))). names x y aesthetics typically omitted common; aesthetics must named.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Construct aesthetic mappings — aes","text":"list class uneval. Components list either quosures constants.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Construct aesthetic mappings — aes","text":"function also standardises aesthetic names converting color colour (also substrings, e.g., point_color point_colour) translating old style R names ggplot names (e.g., pch shape cex size).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"quasiquotation","dir":"Reference","previous_headings":"","what":"Quasiquotation","title":"Construct aesthetic mappings — aes","text":"aes() quoting function. means inputs quoted evaluated context data. makes easy work variables data frame can name directly. flip side use quasiquotation program aes(). See tidy evaluation tutorial dplyr programming vignette learn techniques.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Construct aesthetic mappings — aes","text":"","code":"aes(x = mpg, y = wt) #> Aesthetic mapping: #> * `x` -> `mpg` #> * `y` -> `wt` aes(mpg, wt) #> Aesthetic mapping: #> * `x` -> `mpg` #> * `y` -> `wt` # You can also map aesthetics to functions of variables aes(x = mpg ^ 2, y = wt / cyl) #> Aesthetic mapping: #> * `x` -> `mpg^2` #> * `y` -> `wt/cyl` # Or to constants aes(x = 1, colour = \"smooth\") #> Aesthetic mapping: #> * `x` -> 1 #> * `colour` -> \"smooth\" # Aesthetic names are automatically standardised aes(col = x) #> Aesthetic mapping: #> * `colour` -> `x` aes(fg = x) #> Aesthetic mapping: #> * `colour` -> `x` aes(color = x) #> Aesthetic mapping: #> * `colour` -> `x` aes(colour = x) #> Aesthetic mapping: #> * `colour` -> `x` # aes() is passed to either ggplot() or specific layer. Aesthetics supplied # to ggplot() are used as defaults for every layer. ggplot(mpg, aes(displ, hwy)) + geom_point() ggplot(mpg) + geom_point(aes(displ, hwy)) # Tidy evaluation ---------------------------------------------------- # aes() automatically quotes all its arguments, so you need to use tidy # evaluation to create wrappers around ggplot2 pipelines. The # simplest case occurs when your wrapper takes dots: scatter_by <- function(data, ...) { ggplot(data) + geom_point(aes(...)) } scatter_by(mtcars, disp, drat) # If your wrapper has a more specific interface with named arguments, # you need the \"embrace operator\": scatter_by <- function(data, x, y) { ggplot(data) + geom_point(aes({{ x }}, {{ y }})) } scatter_by(mtcars, disp, drat) # Note that users of your wrapper can use their own functions in the # quoted expressions and all will resolve as it should! cut3 <- function(x) cut_number(x, 3) scatter_by(mtcars, cut3(disp), drat)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":null,"dir":"Reference","previous_headings":"","what":"Define aesthetic mappings programmatically — aes_","title":"Define aesthetic mappings programmatically — aes_","text":"Aesthetic mappings describe variables data mapped visual properties (aesthetics) geoms. aes() uses non-standard evaluation capture variable names. aes_() aes_string() require explicitly quote inputs either \"\" aes_string(), quote ~ aes_(). (aes_q() alias aes_()). makes aes_() aes_string() easy program . aes_string() aes_() particularly useful writing functions create plots can use strings quoted names/calls define aesthetic mappings, rather use substitute() generate call aes(). recommend using aes_(), creating equivalents aes(colour = \"colour\") aes(x = `X$1`) aes_string() quite clunky.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Define aesthetic mappings programmatically — aes_","text":"","code":"aes_(x, y, ...) aes_string(x, y, ...) aes_q(x, y, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Define aesthetic mappings programmatically — aes_","text":"x, y, ... List name value pairs. Elements must either quoted calls, strings, one-sided formulas constants.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_.html","id":"life-cycle","dir":"Reference","previous_headings":"","what":"Life cycle","title":"Define aesthetic mappings programmatically — aes_","text":"functions soft-deprecated. Please use tidy evaluation idioms instead. Regarding aes_string(), can replace .data pronoun. example, following code can achieve mapping aes_string(x_var, y_var). details, please see vignette(\"ggplot2--packages\").","code":"x_var <- \"foo\" y_var <- \"bar\" aes(.data[[x_var]], .data[[y_var]])"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":null,"dir":"Reference","previous_headings":"","what":"Given a character vector, create a set of identity mappings — aes_all","title":"Given a character vector, create a set of identity mappings — aes_all","text":"Given character vector, create set identity mappings","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Given a character vector, create a set of identity mappings — aes_all","text":"","code":"aes_all(vars)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Given a character vector, create a set of identity mappings — aes_all","text":"vars vector variable names","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_all.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Given a character vector, create a set of identity mappings — aes_all","text":"","code":"aes_all(names(mtcars)) #> Aesthetic mapping: #> * `mpg` -> `mpg` #> * `cyl` -> `cyl` #> * `disp` -> `disp` #> * `hp` -> `hp` #> * `drat` -> `drat` #> * `wt` -> `wt` #> * `qsec` -> `qsec` #> * `vs` -> `vs` #> * `am` -> `am` #> * `gear` -> `gear` #> * `carb` -> `carb` aes_all(c(\"x\", \"y\", \"col\", \"pch\")) #> Aesthetic mapping: #> * `x` -> `x` #> * `y` -> `y` #> * `colour` -> `col` #> * `shape` -> `pch`"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_auto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Automatic aesthetic mapping — aes_auto","text":"","code":"aes_auto(data = NULL, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_auto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Automatic aesthetic mapping — aes_auto","text":"data data.frame names variables ... aesthetics need explicitly mapped.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"aesthetics parameters change colour (colour fill) opacity (alpha) geom elements plot. Almost every geom either colour fill (), well can alpha modified. Modifying colour plot useful way enhance presentation data, often especially plot graphs two variables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":"colour-and-fill","dir":"Reference","previous_headings":"","what":"Colour and fill","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"colour aesthetic used draw lines strokes, geom_point() geom_line(), also line contours geom_rect() geom_polygon(). fill aesthetic used colour inside areas geoms, geom_rect() geom_polygon(), also insides shapes 21-25 geom_point(). Colours fills can specified following ways: name, e.g., \"red\". R 657 built-named colours, can listed grDevices::colors(). rgb specification, string form \"#RRGGBB\" pairs RR, GG, BB consists two hexadecimal digits giving value range 00 FF. can optionally make colour transparent using form \"#RRGGBBAA\". NA, completely transparent colour.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":"alpha","dir":"Reference","previous_headings":"","what":"Alpha","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"Alpha refers opacity geom. Values alpha range 0 1, lower values corresponding transparent colors. Alpha can additionally modified colour fill aesthetic either aesthetic provides color values using rgb specification (\"#RRGGBBAA\"), AA refers transparency values.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_colour_fill_alpha.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Colour related aesthetics: colour, fill, and alpha — aes_colour_fill_alpha","text":"","code":"# \\donttest{ # Bar chart example p <- ggplot(mtcars, aes(factor(cyl))) # Default plotting p + geom_bar() # To change the interior colouring use fill aesthetic p + geom_bar(fill = \"red\") # Compare with the colour aesthetic which changes just the bar outline p + geom_bar(colour = \"red\") # Combining both, you can see the changes more clearly p + geom_bar(fill = \"white\", colour = \"red\") # Both colour and fill can take an rgb specification. p + geom_bar(fill = \"#00abff\") # Use NA for a completely transparent colour. p + geom_bar(fill = NA, colour = \"#00abff\") # Colouring scales differ depending on whether a discrete or # continuous variable is being mapped. For example, when mapping # fill to a factor variable, a discrete colour scale is used. ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar() # When mapping fill to continuous variable a continuous colour # scale is used. ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) # Some geoms only use the colour aesthetic but not the fill # aesthetic (e.g. geom_point() or geom_line()). p <- ggplot(economics, aes(x = date, y = unemploy)) p + geom_line() p + geom_line(colour = \"green\") p + geom_point() p + geom_point(colour = \"red\") # For large datasets with overplotting the alpha # aesthetic will make the points more transparent. set.seed(1) df <- data.frame(x = rnorm(5000), y = rnorm(5000)) p <- ggplot(df, aes(x,y)) p + geom_point() p + geom_point(alpha = 0.5) p + geom_point(alpha = 1/10) # Alpha can also be used to add shading. p <- ggplot(economics, aes(x = date, y = unemploy)) + geom_line() p yrng <- range(economics$unemploy) p <- p + geom_rect( aes(NULL, NULL, xmin = start, xmax = end, fill = party), ymin = yrng[1], ymax = yrng[2], data = presidential ) p p + scale_fill_manual(values = alpha(c(\"blue\", \"red\"), .3)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":null,"dir":"Reference","previous_headings":"","what":"Control aesthetic evaluation — aes_eval","title":"Control aesthetic evaluation — aes_eval","text":"aesthetics mapped variables found data. Sometimes, however, want delay mapping later rendering process. ggplot2 three stages data can map aesthetics , three functions control stage aesthetics evaluated. after_stat() replaces old approaches using either stat(), e.g. stat(density), surrounding variable names .., e.g. ..density...","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Control aesthetic evaluation — aes_eval","text":"","code":"# These functions can be used inside the `aes()` function # used as the `mapping` argument in layers, for example: # geom_density(mapping = aes(y = after_stat(scaled))) after_stat(x) after_scale(x) from_theme(x) stage(start = NULL, after_stat = NULL, after_scale = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Control aesthetic evaluation — aes_eval","text":"x aesthetic expression using variables calculated stat (after_stat()) layer aesthetics (after_scale()). start aesthetic expression using variables layer data. after_stat aesthetic expression using variables calculated stat. after_scale aesthetic expression using layer aesthetics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"staging","dir":"Reference","previous_headings":"","what":"Staging","title":"Control aesthetic evaluation — aes_eval","text":"follows overview three stages evaluation aesthetic evaluation can controlled.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"stage-direct-input","dir":"Reference","previous_headings":"","what":"Stage 1: direct input","title":"Control aesthetic evaluation — aes_eval","text":"default map beginning, using layer data provided user. want map directly layer data anything special. stage original layer data can accessed.","code":"# 'x' and 'y' are mapped directly ggplot(mtcars) + geom_point(aes(x = mpg, y = disp))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"stage-after-stat-transformation","dir":"Reference","previous_headings":"","what":"Stage 2: after stat transformation","title":"Control aesthetic evaluation — aes_eval","text":"second stage data transformed layer stat. common example mapping stat transformed data height bars geom_histogram(): height come variable underlying data, instead mapped count computed stat_bin(). order map stat transformed data use after_stat() function flag evaluation aesthetic mapping postponed stat transformation. Evaluation stat transformation access variables calculated stat, original mapped values. 'computed variables' section stat lists variables available access.","code":"# The 'y' values for the histogram are computed by the stat ggplot(faithful, aes(x = waiting)) + geom_histogram() # Choosing a different computed variable to display, matching up the # histogram with the density plot ggplot(faithful, aes(x = waiting)) + geom_histogram(aes(y = after_stat(density))) + geom_density()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"stage-after-scale-transformation","dir":"Reference","previous_headings":"","what":"Stage 3: after scale transformation","title":"Control aesthetic evaluation — aes_eval","text":"third last stage data transformed mapped plot scales. example mapping scaled data use desaturated version stroke colour fill. use after_scale() flag evaluation mapping data scaled. Evaluation scaling access final aesthetics layer (including non-mapped, default aesthetics).","code":"# The exact colour is known after scale transformation ggplot(mpg, aes(cty, colour = factor(cyl))) + geom_density() # We re-use colour properties for the fill without a separate fill scale ggplot(mpg, aes(cty, colour = factor(cyl))) + geom_density(aes(fill = after_scale(alpha(colour, 0.3))))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"complex-staging","dir":"Reference","previous_headings":"","what":"Complex staging","title":"Control aesthetic evaluation — aes_eval","text":"want map aesthetic multiple times, e.g. map x data column stat, remap geom, can use stage() function collect multiple mappings.","code":"# Use stage to modify the scaled fill ggplot(mpg, aes(class, hwy)) + geom_boxplot(aes(fill = stage(class, after_scale = alpha(fill, 0.4)))) # Using data for computing summary, but placing label elsewhere. # Also, we're making our own computed variable to use for the label. ggplot(mpg, aes(class, displ)) + geom_violin() + stat_summary( aes( y = stage(displ, after_stat = 8), label = after_stat(paste(mean, \"±\", sd)) ), geom = \"text\", fun.data = ~ round(data.frame(mean = mean(.x), sd = sd(.x)), 2) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"theme-access","dir":"Reference","previous_headings":"","what":"Theme access","title":"Control aesthetic evaluation — aes_eval","text":"from_theme() function can used acces element_geom() fields theme(geom) argument. Using aes(colour = from_theme(ink)) aes(colour = from_theme(accent)) allows swapping foreground accent colours.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_eval.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Control aesthetic evaluation — aes_eval","text":"","code":"# Default histogram display ggplot(mpg, aes(displ)) + geom_histogram(aes(y = after_stat(count))) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # Scale tallest bin to 1 ggplot(mpg, aes(displ)) + geom_histogram(aes(y = after_stat(count / max(count)))) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # Use a transparent version of colour for fill ggplot(mpg, aes(class, hwy)) + geom_boxplot(aes(colour = class, fill = after_scale(alpha(colour, 0.4)))) # Use stage to modify the scaled fill ggplot(mpg, aes(class, hwy)) + geom_boxplot(aes(fill = stage(class, after_scale = alpha(fill, 0.4)))) # Making a proportional stacked density plot ggplot(mpg, aes(cty)) + geom_density( aes( colour = factor(cyl), fill = after_scale(alpha(colour, 0.3)), y = after_stat(count / sum(n[!duplicated(group)])) ), position = \"stack\", bw = 1 ) + geom_density(bw = 1) # Imitating a ridgeline plot ggplot(mpg, aes(cty, colour = factor(cyl))) + geom_ribbon( stat = \"density\", outline.type = \"upper\", aes( fill = after_scale(alpha(colour, 0.3)), ymin = after_stat(group), ymax = after_stat(group + ndensity) ) ) # Labelling a bar plot ggplot(mpg, aes(class)) + geom_bar() + geom_text( aes( y = after_stat(count + 2), label = after_stat(count) ), stat = \"count\" ) # Labelling the upper hinge of a boxplot, # inspired by June Choe ggplot(mpg, aes(displ, class)) + geom_boxplot(outlier.shape = NA) + geom_text( aes( label = after_stat(xmax), x = stage(displ, after_stat = xmax) ), stat = \"boxplot\", hjust = -0.5 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_group_order.html","id":null,"dir":"Reference","previous_headings":"","what":"Aesthetics: grouping — aes_group_order","title":"Aesthetics: grouping — aes_group_order","text":"group aesthetic default set interaction discrete variables plot. choice often partitions data correctly, , discrete variable used plot, need explicitly define grouping structure mapping group variable different value group.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_group_order.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Aesthetics: grouping — aes_group_order","text":"applications grouping set implicitly mapping one discrete variables x, y, colour, fill, alpha, shape, size, /linetype. demonstrated examples . three common cases default display data correctly. geom_line() multiple individuals plot tries connect every observation, even across individuals, line. geom_line() discrete x-position implies groups, whereas observations span discrete x-positions. grouping needs different different layers, example computing statistic observations another layer shows individuals. examples use longitudinal dataset, Oxboys, nlme package demonstrate cases. Oxboys records heights (height) centered ages (age) 26 boys (Subject), measured nine occasions (Occasion).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_group_order.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Aesthetics: grouping — aes_group_order","text":"","code":"# \\donttest{ p <- ggplot(mtcars, aes(wt, mpg)) # A basic scatter plot p + geom_point(size = 4) # Using the colour aesthetic p + geom_point(aes(colour = factor(cyl)), size = 4) # Using the shape aesthetic p + geom_point(aes(shape = factor(cyl)), size = 4) # Using fill p <- ggplot(mtcars, aes(factor(cyl))) p + geom_bar() p + geom_bar(aes(fill = factor(cyl))) p + geom_bar(aes(fill = factor(vs))) # Using linetypes ggplot(economics_long, aes(date, value01)) + geom_line(aes(linetype = variable)) # Multiple groups with one aesthetic p <- ggplot(nlme::Oxboys, aes(age, height)) # The default is not sufficient here. A single line tries to connect all # the observations. p + geom_line() # To fix this, use the group aesthetic to map a different line for each # subject. p + geom_line(aes(group = Subject)) # Different groups on different layers p <- p + geom_line(aes(group = Subject)) # Using the group aesthetic with both geom_line() and geom_smooth() # groups the data the same way for both layers p + geom_smooth(aes(group = Subject), method = \"lm\", se = FALSE) #> `geom_smooth()` using formula = 'y ~ x' # Changing the group aesthetic for the smoother layer # fits a single line of best fit across all boys p + geom_smooth(aes(group = 1), size = 2, method = \"lm\", se = FALSE) #> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0. #> ℹ Please use `linewidth` instead. #> `geom_smooth()` using formula = 'y ~ x' # Overriding the default grouping # Sometimes the plot has a discrete scale but you want to draw lines # that connect across groups. This is the strategy used in interaction # plots, profile plots, and parallel coordinate plots, among others. # For example, we draw boxplots of height at each measurement occasion. p <- ggplot(nlme::Oxboys, aes(Occasion, height)) + geom_boxplot() p # There is no need to specify the group aesthetic here; the default grouping # works because occasion is a discrete variable. To overlay individual # trajectories, we again need to override the default grouping for that layer # with aes(group = Subject) p + geom_line(aes(group = Subject), colour = \"blue\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":null,"dir":"Reference","previous_headings":"","what":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"linetype, linewidth, size, shape aesthetics modify appearance lines /points. also apply outlines polygons (linetype linewidth) text (size).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"linetype","dir":"Reference","previous_headings":"","what":"Linetype","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"linetype aesthetic can specified either integer (0-6), name (0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash), mapping discrete variable, string even number (eight) hexadecimal digits give lengths consecutive positions string. See examples hex string demonstration.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"linewidth-and-stroke","dir":"Reference","previous_headings":"","what":"Linewidth and stroke","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"linewidth aesthetic sets widths lines, can specified numeric value (historical reasons, units 0.75 millimetres). Alternatively, can also set via mapping continuous variable. stroke aesthetic serves role points, distinct discriminating points lines geoms geom_pointrange().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"size","dir":"Reference","previous_headings":"","what":"Size","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"size aesthetic control size points text, can specified numerical value (millimetres) via mapping continuous variable.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"shape","dir":"Reference","previous_headings":"","what":"Shape","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"shape aesthetic controls symbols points, can specified integer (0 25), single character (uses character plotting symbol), . draw smallest rectangle visible (.e., one pixel), NA draw nothing, mapping discrete variable. Symbols filled shapes described examples .","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_linetype_size_shape.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Differentiation related aesthetics: linetype, size, shape — aes_linetype_size_shape","text":"","code":"df <- data.frame(x = 1:10 , y = 1:10) p <- ggplot(df, aes(x, y)) p + geom_line(linetype = 2) p + geom_line(linetype = \"dotdash\") # An example with hex strings; the string \"33\" specifies three units on followed # by three off and \"3313\" specifies three units on followed by three off followed # by one on and finally three off. p + geom_line(linetype = \"3313\") # Mapping line type from a grouping variable ggplot(economics_long, aes(date, value01)) + geom_line(aes(linetype = variable)) # Linewidth examples ggplot(economics, aes(date, unemploy)) + geom_line(linewidth = 2, lineend = \"round\") ggplot(economics, aes(date, unemploy)) + geom_line(aes(linewidth = uempmed), lineend = \"round\") # Size examples p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point(size = 4) p + geom_point(aes(size = qsec)) p + geom_point(size = 2.5) + geom_hline(yintercept = 25, size = 3.5) # Shape examples p + geom_point() p + geom_point(shape = 5) p + geom_point(shape = \"k\", size = 3) p + geom_point(shape = \".\") p + geom_point(shape = NA) #> Warning: Removed 32 rows containing missing values or values outside the scale #> range (`geom_point()`). p + geom_point(aes(shape = factor(cyl))) # A look at all 25 symbols df2 <- data.frame(x = 1:5 , y = 1:25, z = 1:25) p <- ggplot(df2, aes(x, y)) p + geom_point(aes(shape = z), size = 4) + scale_shape_identity() # While all symbols have a foreground colour, symbols 19-25 also take a # background colour (fill) p + geom_point(aes(shape = z), size = 4, colour = \"Red\") + scale_shape_identity() p + geom_point(aes(shape = z), size = 4, colour = \"Red\", fill = \"Black\") + scale_shape_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":null,"dir":"Reference","previous_headings":"","what":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"following aesthetics can used specify position elements: x, y, xmin, xmax, ymin, ymax, xend, yend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"x y define locations points positions along line path. x, y xend, yend define starting ending points segment curve geometries. xmin, xmax, ymin ymax can used specify position annotations represent rectangular areas. addition, position aesthetics contextual geometry used . xintercept, yintercept, xmin_final, ymin_final, xmax_final, ymax_final, xlower, lower, xmiddle, middle, xupper, upper, x0 y0. Many used automatically computed geom_boxplot().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":"relation-to-width-and-height","dir":"Reference","previous_headings":"","what":"Relation to width and height","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"position aesthetics mentioned like x y location based. width height aesthetics closely related length based aesthetics, position aesthetics. Consequently, x y aesthetics respond scale transformations, whereas length based width height aesthetics transformed scales. example, pair x = 10, width = 2, gets translated locations xmin = 9, xmax = 11 using default identity scales. However, pair becomes xmin = 1, xmax = 100 using log10 scales, width = 2 log10-space spans 100-fold change.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/aes_position.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position related aesthetics: x, y, xmin, xmax, ymin, ymax, xend, yend — aes_position","text":"","code":"# Generate data: means and standard errors of means for prices # for each type of cut dmod <- lm(price ~ cut, data = diamonds) cut <- unique(diamonds$cut) cuts_df <- data.frame( cut, predict(dmod, data.frame(cut), se = TRUE)[c(\"fit\", \"se.fit\")] ) ggplot(cuts_df) + aes( x = cut, y = fit, ymin = fit - se.fit, ymax = fit + se.fit, colour = cut ) + geom_pointrange() # Using annotate p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() p p + annotate( \"rect\", xmin = 2, xmax = 3.5, ymin = 2, ymax = 25, fill = \"dark grey\", alpha = .5 ) # Geom_segment examples p + geom_segment( aes(x = 2, y = 15, xend = 2, yend = 25), arrow = arrow(length = unit(0.5, \"cm\")) ) #> Warning: All aesthetics have length 1, but the data has 32 rows. #> ℹ Please consider using `annotate()` or provide this layer with data #> containing a single row. p + geom_segment( aes(x = 2, y = 15, xend = 3, yend = 15), arrow = arrow(length = unit(0.5, \"cm\")) ) #> Warning: All aesthetics have length 1, but the data has 32 rows. #> ℹ Please consider using `annotate()` or provide this layer with data #> containing a single row. p + geom_segment( aes(x = 5, y = 30, xend = 3.5, yend = 25), arrow = arrow(length = unit(0.5, \"cm\")) ) #> Warning: All aesthetics have length 1, but the data has 32 rows. #> ℹ Please consider using `annotate()` or provide this layer with data #> containing a single row. # You can also use geom_segment() to recreate plot(type = \"h\") # from base R: set.seed(1) counts <- as.data.frame(table(x = rpois(100, 5))) counts$x <- as.numeric(as.character(counts$x)) with(counts, plot(x, Freq, type = \"h\", lwd = 10)) ggplot(counts, aes(x = x, y = Freq)) + geom_segment(aes(yend = 0, xend = x), size = 10)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":null,"dir":"Reference","previous_headings":"","what":"Create an annotation layer — annotate","title":"Create an annotation layer — annotate","text":"function adds geoms plot, unlike typical geom function, properties geoms mapped variables data frame, instead passed vectors. useful adding small annotations (text labels) data vectors, reason want put data frame.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create an annotation layer — annotate","text":"","code":"annotate( geom, x = NULL, y = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, xend = NULL, yend = NULL, ..., na.rm = FALSE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create an annotation layer — annotate","text":"geom name geom use annotation x, y, xmin, ymin, xmax, ymax, xend, yend positioning aesthetics - must specify least one . ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create an annotation layer — annotate","text":"Note position aesthetics scaled (.e. expand limits plot visible), aesthetics set. means layers created function never affect legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"unsupported-geoms","dir":"Reference","previous_headings":"","what":"Unsupported geoms","title":"Create an annotation layer — annotate","text":"Due special nature, reference line geoms geom_abline(), geom_hline(), geom_vline() used annotate(). can use geoms directly annotations.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotate.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create an annotation layer — annotate","text":"","code":"p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() p + annotate(\"text\", x = 4, y = 25, label = \"Some text\") p + annotate(\"text\", x = 2:5, y = 25, label = \"Some text\") p + annotate(\"rect\", xmin = 3, xmax = 4.2, ymin = 12, ymax = 21, alpha = .2) p + annotate(\"segment\", x = 2.5, xend = 4, y = 15, yend = 25, colour = \"blue\") p + annotate(\"pointrange\", x = 3.5, y = 20, ymin = 12, ymax = 28, colour = \"red\", size = 2.5, linewidth = 1.5) p + annotate(\"text\", x = 2:3, y = 20:21, label = c(\"my label\", \"label 2\")) p + annotate(\"text\", x = 4, y = 25, label = \"italic(R) ^ 2 == 0.75\", parse = TRUE) p + annotate(\"text\", x = 4, y = 25, label = \"paste(italic(R) ^ 2, \\\" = .75\\\")\", parse = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: Custom grob — annotation_custom","title":"Annotation: Custom grob — annotation_custom","text":"special geom intended use static annotations every panel. annotations affect scales (.e. x y axes grow cover range grob, grob modified ggplot settings mappings).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: Custom grob — annotation_custom","text":"","code":"annotation_custom(grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: Custom grob — annotation_custom","text":"grob grob display xmin, xmax x location (data coordinates) giving horizontal location raster ymin, ymax y location (data coordinates) giving vertical location raster","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Annotation: Custom grob — annotation_custom","text":"useful adding tables, inset plots, grid-based decorations.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Annotation: Custom grob — annotation_custom","text":"annotation_custom() expects grob fill entire viewport defined xmin, xmax, ymin, ymax. Grobs different (absolute) size center-justified region. Inf values can used fill full plot panel (see examples).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_custom.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: Custom grob — annotation_custom","text":"","code":"# Dummy plot df <- data.frame(x = 1:10, y = 1:10) base <- ggplot(df, aes(x, y)) + geom_blank() + theme_bw() # Full panel annotation base + annotation_custom( grob = grid::roundrectGrob(), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf ) # Inset plot df2 <- data.frame(x = 1 , y = 1) g <- ggplotGrob(ggplot(df2, aes(x, y)) + geom_point() + theme(plot.background = element_rect(colour = \"black\"))) base + annotation_custom(grob = g, xmin = 1, xmax = 10, ymin = 8, ymax = 10)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: log tick marks — annotation_logticks","title":"Annotation: log tick marks — annotation_logticks","text":"function superseded using guide_axis_logticks(). annotation adds log tick marks diminishing spacing. tick marks probably make sense base 10.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: log tick marks — annotation_logticks","text":"","code":"annotation_logticks( base = 10, sides = \"bl\", outside = FALSE, scaled = TRUE, short = unit(0.1, \"cm\"), mid = unit(0.2, \"cm\"), long = unit(0.3, \"cm\"), colour = \"black\", linewidth = 0.5, linetype = 1, alpha = 1, color = NULL, ..., size = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: log tick marks — annotation_logticks","text":"base base log (default 10) sides string controls sides plot log ticks appear . can set string containing \"trbl\", top, right, bottom, left. outside logical controls whether move log ticks outside plot area. Default (FALSE). also need use coord_cartesian(clip = \"\"). See examples. scaled data already log-scaled? TRUE (default) data already transformed log10() using scale_y_log10(). FALSE using coord_trans(y = \"log10\"). short grid::unit() object specifying length short tick marks mid grid::unit() object specifying length middle tick marks. base 10, \"5\" ticks. long grid::unit() object specifying length long tick marks. base 10, \"1\" (\"10\") ticks. colour Colour tick marks. linewidth Thickness tick marks, mm. linetype Linetype tick marks (solid, dashed, etc.) alpha transparency tick marks. color alias colour. ... parameters passed layer size","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_logticks.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: log tick marks — annotation_logticks","text":"","code":"# Make a log-log plot (without log ticks) a <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point(na.rm = TRUE) + scale_x_log10( breaks = scales::trans_breaks(\"log10\", function(x) 10^x), labels = scales::trans_format(\"log10\", scales::math_format(10^.x)) ) + scale_y_log10( breaks = scales::trans_breaks(\"log10\", function(x) 10^x), labels = scales::trans_format(\"log10\", scales::math_format(10^.x)) ) + theme_bw() a + annotation_logticks() # Default: log ticks on bottom and left a + annotation_logticks(sides = \"lr\") # Log ticks for y, on left and right a + annotation_logticks(sides = \"trbl\") # All four sides a + annotation_logticks(sides = \"lr\", outside = TRUE) + coord_cartesian(clip = \"off\") # Ticks outside plot # Hide the minor grid lines because they don't align with the ticks a + annotation_logticks(sides = \"trbl\") + theme(panel.grid.minor = element_blank()) # Another way to get the same results as 'a' above: log-transform the data before # plotting it. Also hide the minor grid lines. b <- ggplot(msleep, aes(log10(bodywt), log10(brainwt))) + geom_point(na.rm = TRUE) + scale_x_continuous(name = \"body\", labels = scales::label_math(10^.x)) + scale_y_continuous(name = \"brain\", labels = scales::label_math(10^.x)) + theme_bw() + theme(panel.grid.minor = element_blank()) b + annotation_logticks() # Using a coordinate transform requires scaled = FALSE t <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point() + coord_trans(x = \"log10\", y = \"log10\") + theme_bw() t + annotation_logticks(scaled = FALSE) #> Warning: Removed 27 rows containing missing values or values outside the scale #> range (`geom_point()`). # Change the length of the ticks a + annotation_logticks( short = unit(.5,\"mm\"), mid = unit(3,\"mm\"), long = unit(4,\"mm\") )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: a map — annotation_map","title":"Annotation: a map — annotation_map","text":"Display fixed map plot. function predates geom_sf() framework work sf geometry columns input. However, can used conjunction geom_sf() layers /coord_sf() (see examples).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: a map — annotation_map","text":"","code":"annotation_map(map, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: a map — annotation_map","text":"map Data frame representing map. See geom_map() details. ... arguments used modify visual parameters, colour fill.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: a map — annotation_map","text":"","code":"if (FALSE) { # \\dontrun{ if (requireNamespace(\"maps\", quietly = TRUE)) { # location of cities in North Carolina df <- data.frame( name = c(\"Charlotte\", \"Raleigh\", \"Greensboro\"), lat = c(35.227, 35.772, 36.073), long = c(-80.843, -78.639, -79.792) ) p <- ggplot(df, aes(x = long, y = lat)) + annotation_map( map_data(\"state\"), fill = \"antiquewhite\", colour = \"darkgrey\" ) + geom_point(color = \"blue\") + geom_text( aes(label = name), hjust = 1.105, vjust = 1.05, color = \"blue\" ) # use without coord_sf() is possible but not recommended p + xlim(-84, -76) + ylim(34, 37.2) if (requireNamespace(\"sf\", quietly = TRUE)) { # use with coord_sf() for appropriate projection p + coord_sf( crs = sf::st_crs(3347), default_crs = sf::st_crs(4326), # data is provided as long-lat xlim = c(-84, -76), ylim = c(34, 37.2) ) # you can mix annotation_map() and geom_sf() nc <- sf::st_read(system.file(\"shape/nc.shp\", package = \"sf\"), quiet = TRUE) p + geom_sf( data = nc, inherit.aes = FALSE, fill = NA, color = \"black\", linewidth = 0.1 ) + coord_sf(crs = sf::st_crs(3347), default_crs = sf::st_crs(4326)) }}} # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":null,"dir":"Reference","previous_headings":"","what":"Annotation: high-performance rectangular tiling — annotation_raster","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"special version geom_raster() optimised static annotations every panel. annotations affect scales (.e. x y axes grow cover range raster, raster must already colours). useful adding bitmap images.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"","code":"annotation_raster(raster, xmin, xmax, ymin, ymax, interpolate = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"raster raster object display, may array nativeRaster xmin, xmax x location (data coordinates) giving horizontal location raster ymin, ymax y location (data coordinates) giving vertical location raster interpolate TRUE interpolate linearly, FALSE (default) interpolate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/annotation_raster.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Annotation: high-performance rectangular tiling — annotation_raster","text":"","code":"# Generate data rainbow <- matrix(hcl(seq(0, 360, length.out = 50 * 50), 80, 70), nrow = 50) ggplot(mtcars, aes(mpg, wt)) + geom_point() + annotation_raster(rainbow, 15, 20, 3, 4) # To fill up whole plot ggplot(mtcars, aes(mpg, wt)) + annotation_raster(rainbow, -Inf, Inf, -Inf, Inf) + geom_point() rainbow2 <- matrix(hcl(seq(0, 360, length.out = 10), 80, 70), nrow = 1) ggplot(mtcars, aes(mpg, wt)) + annotation_raster(rainbow2, -Inf, Inf, -Inf, Inf) + geom_point() rainbow2 <- matrix(hcl(seq(0, 360, length.out = 10), 80, 70), nrow = 1) ggplot(mtcars, aes(mpg, wt)) + annotation_raster(rainbow2, -Inf, Inf, -Inf, Inf, interpolate = TRUE) + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/as.list.ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Convert a ggproto object to a list — as.list.ggproto","title":"Convert a ggproto object to a list — as.list.ggproto","text":"include object's super member.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/as.list.ggproto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Convert a ggproto object to a list — as.list.ggproto","text":"","code":"# S3 method for class 'ggproto' as.list(x, inherit = TRUE, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/as.list.ggproto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Convert a ggproto object to a list — as.list.ggproto","text":"x ggproto object convert list. inherit TRUE (default), flatten inherited items returned list. FALSE, include inherited items. ... Arguments passed base::.list.environment .names logical indicating whether copy values (default) whose names begin dot. sorted logical indicating whether names resulting list sorted (increasingly). Note somewhat costly, may useful comparison environments.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":null,"dir":"Reference","previous_headings":"","what":"Coerce to labeller function — as_labeller","title":"Coerce to labeller function — as_labeller","text":"transforms objects labeller functions. Used internally labeller().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Coerce to labeller function — as_labeller","text":"","code":"as_labeller(x, default = label_value, multi_line = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Coerce to labeller function — as_labeller","text":"x Object coerce labeller function. named character vector, used lookup table passed default. non-labeller function, assumed takes returns character vectors applied labels. labeller, simply applied labels. default Default labeller process labels produced lookup tables modified non-labeller functions. multi_line Whether display labels multiple factors separate lines. passed labeller function.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/as_labeller.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Coerce to labeller function — as_labeller","text":"","code":"p <- ggplot(mtcars, aes(disp, drat)) + geom_point() p + facet_wrap(~am) # Rename labels on the fly with a lookup character vector to_string <- as_labeller(c(`0` = \"Zero\", `1` = \"One\")) p + facet_wrap(~am, labeller = to_string) # Quickly transform a function operating on character vectors to a # labeller function: appender <- function(string, suffix = \"-foo\") paste0(string, suffix) p + facet_wrap(~am, labeller = as_labeller(appender)) # If you have more than one faceting variable, be sure to dispatch # your labeller to the right variable with labeller() p + facet_grid(cyl ~ am, labeller = labeller(am = to_string))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a ggplot layer appropriate to a particular data type — autolayer","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"autolayer() uses ggplot2 draw particular layer object particular class single command. defines S3 generic classes packages can extend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"","code":"autolayer(object, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"object object, whose class determine behaviour autolayer ... arguments passed specific methods","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autolayer.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a ggplot layer appropriate to a particular data type — autolayer","text":"ggplot layer","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":null,"dir":"Reference","previous_headings":"","what":"Tailoring plots to particular data types — automatic_plotting","title":"Tailoring plots to particular data types — automatic_plotting","text":"three functions make plotting particular data types easier: autoplot(), autolayer() fortify(). S3 generics packages can write methods display classes data. three functions complementary allow different levels customisation. explore implementing series methods automate plotting class. suppose writing packages class called 'my_heatmap', wraps matrix like users easily plot heatmap.","code":"my_heatmap <- function(...) { m <- matrix(...) class(m) <- c(\"my_heatmap\", class(m)) m } my_data <- my_heatmap(volcano)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":"automatic-data-shaping","dir":"Reference","previous_headings":"","what":"Automatic data shaping","title":"Tailoring plots to particular data types — automatic_plotting","text":"One things ensure data shaped long format compatible ggplot2. job fortify() function. 'my_heatmap' wraps matrix, can let fortify method 'melt' matrix long format. data already based long-format , can skip implementing fortify() method. implemented fortify() method, easier construct plot data matrix.","code":"fortify.my_heatmap <- function(model, ...) { data.frame( row = as.vector(row(model)), col = as.vector(col(model)), value = as.vector(model) ) } fortify(my_data) ggplot(my_data, aes(x = col, y = row, fill = value)) + geom_raster()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":"automatic-layers","dir":"Reference","previous_headings":"","what":"Automatic layers","title":"Tailoring plots to particular data types — automatic_plotting","text":"next step automating plotting data type write autolayer() method. typically wrappers around geoms stats automatically set aesthetics parameters. implemented fortify() method data type, might reshape data autolayer(). require multiple layers display data type, can use autolayer() method constructs list layers, can added plot. quick tip: define mapping autolayer(), might want set inherit.aes = FALSE aesthetics set layers interfere layer.","code":"autolayer.my_heatmap <- function(object, ...) { geom_raster( mapping = aes(x = col, y = row, fill = value), data = object, ..., inherit.aes = FALSE ) } ggplot() + autolayer(my_data)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/automatic_plotting.html","id":"automatic-plots","dir":"Reference","previous_headings":"","what":"Automatic plots","title":"Tailoring plots to particular data types — automatic_plotting","text":"last step automating plotting write autoplot() method data type. expectation return complete plot. example , exploiting autolayer() method already written make complete plot. wish implement base R plotting method, can set plot method class autoplot method.","code":"autoplot.my_heatmap <- function(object, ..., option = \"magma\") { ggplot() + autolayer(my_data) + scale_fill_viridis_c(option = option) + theme_void() } autoplot(my_data) plot.my_heatmap <- autoplot.my_heatmap plot(my_data)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a complete ggplot appropriate to a particular data type — autoplot","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"autoplot() uses ggplot2 draw particular plot object particular class single command. defines S3 generic classes packages can extend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"","code":"autoplot(object, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"object object, whose class determine behaviour autoplot ... arguments passed specific methods","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/autoplot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Create a complete ggplot appropriate to a particular data type — autoplot","text":"ggplot object","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"Benchmark plot creation time. Broken construct, build, render draw times.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"","code":"benchplot(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"x code create ggplot2 plot","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/benchplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Benchmark plot creation time. Broken down into construct, build, render and draw times. — benchplot","text":"","code":"benchplot(ggplot(mtcars, aes(mpg, wt)) + geom_point()) #> step user.self sys.self elapsed #> 1 construct 0.002 0 0.003 #> 2 build 0.019 0 0.019 #> 3 render 0.018 0 0.019 #> 4 draw 0.019 0 0.020 #> 5 TOTAL 0.058 0 0.061 benchplot(ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl)) #> step user.self sys.self elapsed #> 1 construct 0.002 0 0.003 #> 2 build 0.020 0 0.020 #> 3 render 0.044 0 0.044 #> 4 draw 0.035 0 0.035 #> 5 TOTAL 0.101 0 0.102 # With tidy eval: p <- expr(ggplot(mtcars, aes(mpg, wt)) + geom_point()) benchplot(!!p) #> step user.self sys.self elapsed #> 1 construct 0.002 0 0.003 #> 2 build 0.019 0 0.019 #> 3 render 0.019 0 0.018 #> 4 draw 0.020 0 0.020 #> 5 TOTAL 0.060 0 0.060"},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":null,"dir":"Reference","previous_headings":"","what":"Utilities for working with bidirectional layers — bidirection","title":"Utilities for working with bidirectional layers — bidirection","text":"functions underpins ability certain geoms work automatically directions. See Extending ggplot2 vignette used implementing Geom, Stat, Position classes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Utilities for working with bidirectional layers — bidirection","text":"","code":"has_flipped_aes( data, params = list(), main_is_orthogonal = NA, range_is_orthogonal = NA, group_has_equal = FALSE, ambiguous = FALSE, main_is_continuous = FALSE, main_is_optional = FALSE, default = FALSE ) flip_data(data, flip = NULL) flipped_names(flip = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Utilities for working with bidirectional layers — bidirection","text":"data layer data params parameters Stat/Geom. orientation parameter used. main_is_orthogonal x y present correspond main orientation reverse. E.g. TRUE y present flipped. NA check ignored. range_is_orthogonal xmin/xmax ymin/ymax present correspond main orientation reverse. NA check ignored. group_has_equal expected grouped data either single x y value correspond orientation. ambiguous layer ambiguous mapping nature. , flipped params$orientation == \"y\" main_is_continuous discrete continuous axis, continuous one correspond main orientation? main_is_optional main axis aesthetic optional , given, set 0 default logical value return orientation can discerned data. flip Logical. layer flipped.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Utilities for working with bidirectional layers — bidirection","text":"has_flipped_aes() returns TRUE detects layer orientation FALSE otherwise. flip_data() return input unchanged flip = FALSE data flipped aesthetic names flip = TRUE. flipped_names() returns named list strings. flip = FALSE name element correspond element, e.g. flipped_names(FALSE)$x == \"x\" flip = TRUE correspond flipped name, e.g. flipped_names(FALSE)$x == \"y\"","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Utilities for working with bidirectional layers — bidirection","text":"has_flipped_aes() used sniff orientation layer data. range arguments can used finetune sniffing based data look like. flip_data() switch column names data looks like x-oriented data. flipped_names() provides named list aesthetic names corresponds orientation layer.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/bidirection.html","id":"controlling-the-sniffing","dir":"Reference","previous_headings":"","what":"Controlling the sniffing","title":"Utilities for working with bidirectional layers — bidirection","text":"layer data interpreted depends specific features. has_flipped_aes() contains range flags defining certain features data correspond : main_is_orthogonal: argument controls existence x y aesthetic understood. TRUE existing aesthetic secondary axis. behaviour present stat_ydensity() stat_boxplot(). FALSE existing aesthetic main axis seen e.g. stat_bin(), geom_count(), stat_density(). range_is_orthogonal: argument controls whether existence range-like aesthetics (e.g. xmin xmax) represents main secondary axis. TRUE range given secondary axis seen e.g. geom_ribbon() geom_linerange(). group_has_equal: argument controls whether test equality x y values inside group set main axis one equal. test performed TRUE, less computationally heavy tests come empty handed. Examples stat_boxplot() stat_ydensity ambiguous: argument tells function layer, bidirectional, treat axis differently. circumvent data based guessing take hint orientation element params. present fall back FALSE. Examples geom_line() geom_area() main_is_continuous: argument controls test discreteness scales interpreted. TRUE main axis one discrete-like. Conversely, FALSE main axis discrete-like one. Examples TRUE stat_density() stat_bin(), examples FALSE stat_ydensity() stat_boxplot() main_is_optional: argument controls rare case layers main direction optional aesthetic. seen stat_boxplot() x set 0 given. TRUE check whether x y equal 0","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/binned_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Binning scale constructor — binned_scale","title":"Binning scale constructor — binned_scale","text":"Binning scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/binned_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Binning scale constructor — binned_scale","text":"","code":"binned_scale( aesthetics, scale_name = deprecated(), palette, name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, rescaler = rescale, oob = squish, expand = waiver(), na.value = NA_real_, n.breaks = NULL, nice.breaks = TRUE, right = TRUE, transform = \"identity\", trans = deprecated(), show.limits = FALSE, guide = \"bins\", position = \"left\", call = caller_call(), super = ScaleBinned )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/binned_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Binning scale constructor — binned_scale","text":"aesthetics names aesthetics scale works . scale_name name scale used error messages associated scale. palette palette function called numeric vector values 0 1 returns corresponding output values (e.g., scales::pal_area()). name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::squish()) squishes bounds values range. scales::censor replacing bounds values NA. scales::squish_infinite() squishing infinite values range. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. na.value Missing values replaced value. n.breaks number break points create breaks given directly. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. right intervals closed right (TRUE, default) intervals closed left (FALSE)? 'Closed right' means values break positions part lower bin (open left), whereas part upper bin intervals closed left (open right). transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. show.limits limits scale appear ticks guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. call call used construct scale reporting messages. super super class use constructed scale","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a layer of map borders — borders","title":"Create a layer of map borders — borders","text":"quick dirty way get map data (maps package) onto plot. good place start need crude reference lines, typically want something sophisticated communication graphics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a layer of map borders — borders","text":"","code":"borders( database = \"world\", regions = \".\", fill = NA, colour = \"grey50\", xlim = NULL, ylim = NULL, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a layer of map borders — borders","text":"database map data, see maps::map() details regions map region fill fill colour colour border colour xlim, ylim latitudinal longitudinal ranges extracting map polygons, see maps::map() details. ... Arguments passed geom_polygon rule Either \"evenodd\" \"winding\". polygons holes drawn (using subgroup aesthetic) argument defines hole coordinates interpreted. See examples grid::pathGrob() explanation. mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/borders.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a layer of map borders — borders","text":"","code":"if (require(\"maps\")) { ia <- map_data(\"county\", \"iowa\") mid_range <- function(x) mean(range(x)) seats <- do.call(rbind, lapply(split(ia, ia$subregion), function(d) { data.frame(lat = mid_range(d$lat), long = mid_range(d$long), subregion = unique(d$subregion)) })) ggplot(ia, aes(long, lat)) + geom_polygon(aes(group = group), fill = NA, colour = \"grey60\") + geom_text(aes(label = subregion), data = seats, size = 2, angle = 45) } #> Loading required package: maps if (require(\"maps\")) { data(us.cities) capitals <- subset(us.cities, capital == 2) ggplot(capitals, aes(long, lat)) + borders(\"state\") + geom_point(aes(size = pop)) + scale_size_area() + coord_quickmap() } if (require(\"maps\")) { # Same map, with some world context ggplot(capitals, aes(long, lat)) + borders(\"world\", xlim = c(-130, -60), ylim = c(20, 50)) + geom_point(aes(size = pop)) + scale_size_area() + coord_quickmap() }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate the element properties, by inheriting properties from its parents — calc_element","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"Calculate element properties, inheriting properties parents","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"","code":"calc_element( element, theme, verbose = FALSE, skip_blank = FALSE, call = caller_env() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"element name theme element calculate theme theme object (like theme_grey()) verbose TRUE, print elements one inherits skip_blank TRUE, elements type element_blank inheritance hierarchy ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/calc_element.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Calculate the element properties, by inheriting properties from its parents — calc_element","text":"","code":"t <- theme_grey() calc_element('text', t) #> List of 11 #> $ family : chr \"\" #> $ face : chr \"plain\" #> $ colour : chr \"black\" #> $ size : num 11 #> $ hjust : num 0.5 #> $ vjust : num 0.5 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 0points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" # Compare the \"raw\" element definition to the element with calculated inheritance t$axis.text.x #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : NULL #> $ size : NULL #> $ hjust : NULL #> $ vjust : num 1 #> $ angle : NULL #> $ lineheight : NULL #> $ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : NULL #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" calc_element('axis.text.x', t, verbose = TRUE) #> axis.text.x --> #> axis.text #> axis.text --> #> text #> text --> #> nothing (top level) #> List of 11 #> $ family : chr \"\" #> $ face : chr \"plain\" #> $ colour : chr \"grey30\" #> $ size : num 8.8 #> $ hjust : num 0.5 #> $ vjust : num 1 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" # This reports that axis.text.x inherits from axis.text, # which inherits from text. You can view each of them with: t$axis.text.x #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : NULL #> $ size : NULL #> $ hjust : NULL #> $ vjust : num 1 #> $ angle : NULL #> $ lineheight : NULL #> $ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : NULL #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" t$axis.text #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : chr \"grey30\" #> $ size : 'rel' num 0.8 #> $ hjust : NULL #> $ vjust : NULL #> $ angle : NULL #> $ lineheight : NULL #> $ margin : NULL #> $ debug : NULL #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" t$text #> List of 11 #> $ family : chr \"\" #> $ face : chr \"plain\" #> $ colour : chr \"black\" #> $ size : num 11 #> $ hjust : num 0.5 #> $ vjust : num 0.5 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 0points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi TRUE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":null,"dir":"Reference","previous_headings":"","what":"Check graphics device capabilities — check_device","title":"Check graphics device capabilities — check_device","text":"function makes attempt estimate whether graphics device able render newer graphics features.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Check graphics device capabilities — check_device","text":"","code":"check_device( feature, action = \"warn\", op = NULL, maybe = FALSE, call = caller_env() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Check graphics device capabilities — check_device","text":"feature string naming graphics device feature. One : \"clippingPaths\", \"alpha_masks\", \"lumi_masks\", \"compositing\", \"blending\", \"transformations\", \"gradients\", \"patterns\", \"paths\" \"glyphs\". See 'Features' section explanation terms. action string action take. One : \"test\" returns TRUE FALSE indicating support feature. \"warn\" also returns logical, throws informative warning FALSE. \"abort\" throws error device estimated support feature. op string specific operation test feature either \"blending\" \"compositing\". NULL (default), support known blending compositing operations queried. maybe logical length 1 determining return value case device capabilities assessed. current device 'null device', maybe returned. call execution environment currently running function, e.g. caller_env(). function mentioned warnings error messages source warning error. See call argument abort() information.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Check graphics device capabilities — check_device","text":"TRUE feature thought supported FALSE otherwise.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Check graphics device capabilities — check_device","text":"procedure testing follows: First, R version checked version wherein feature introduced. Next, dev.capabilities() function queried support feature. check ambiguous, svglite ragg devices checked known support. Lastly, answer yet, checked whether device one 'known' devices supports feature.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"features","dir":"Reference","previous_headings":"","what":"Features","title":"Check graphics device capabilities — check_device","text":"\"clippingPaths\" devices support rectangular clipping regions, feature support clipping arbitrary paths. can used display part drawing. \"alpha_masks\" Like clipping regions paths, alpha masks can also used display part drawing. particular semi-transparent mask can used display drawing opaque parts mask hide drawing transparent part mask. \"lumi_masks Similar alpha masks, using mask's luminance (greyscale value) determine drawn. Light values opaque dark values transparent. \"compositing\" Compositing allows one control drawings drawn relation one another. default, one drawing drawn '' previous one, operators possible, like 'clear', '' ''. \"blending\" placing one drawing atop another, blend mode determines colours drawings relate one another. \"transformations\" Performing affine transformation group can used translate, rotate, scale, shear flip drawing. \"gradients\" Gradients can used show transition two colours fill drawing. checks expects linear radial gradients supported. \"patterns\" Patterns can used display repeated, tiled drawing fill another drawing. \"paths\" Contrary 'paths' polyline polygon drawings, \"paths\" refers ability fill stroke collections drawings. \"glyphs\" Refers advanced typesetting feature controlling appearance individual glyphs.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"limitations","dir":"Reference","previous_headings":"","what":"Limitations","title":"Check graphics device capabilities — check_device","text":"Windows machines, bitmap devices png() jpeg() default type = \"windows\". time writing, support new features, contrast type = \"cairo\", . Prior R version 4.2.0, capabilities resolved value maybe argument returned. exception ragg svglite devices, device report capabilities via dev.capabilities(), R version 4.2.0, maybe value returned. Even though patterns gradients introduced R 4.1.0, considered unsupported providing vectorised patterns gradients introduced later R 4.2.0. using RStudio graphics device, back end assumed next device list. assumption typically met default, unless device list purposefully rearranged.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/check_device.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Check graphics device capabilities — check_device","text":"","code":"# Typically you'd run `check_device()` inside a function that might produce # advanced graphics. # The check is designed for use in control flow statements in the test mode if (check_device(\"patterns\", action = \"test\")) { print(\"Yay\") } else { print(\"Nay\") } #> [1] \"Yay\" # Automatically throw a warning when unavailable if (check_device(\"compositing\", action = \"warn\")) { print(\"Yay\") } else { print(\"Nay\") } #> Warning: The agg_png device does not support compositing. #> [1] \"Nay\" # Possibly throw an error try(check_device(\"glyphs\", action = \"abort\")) #> [1] TRUE"},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":null,"dir":"Reference","previous_headings":"","what":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"Take input data define mapping faceting variables ROW, COL PANEL keys","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"","code":"combine_vars(data, env = emptyenv(), vars = NULL, drop = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"data list data.frames, first plot data subsequent individual layer data env environment vars evaluated vars list quoted symbols matching columns data drop missing combinations/levels dropped","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/combine_vars.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Take input data and define a mapping between faceting variables and ROW, COL and PANEL keys — combine_vars","text":"data.frame columns PANEL, ROW, COL, faceting vars","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Complete a theme — complete_theme","title":"Complete a theme — complete_theme","text":"function takes theme completes can used downstream render theme elements. Missing elements filled every item validated specifications element tree.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Complete a theme — complete_theme","text":"","code":"complete_theme(theme = NULL, default = theme_get())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Complete a theme — complete_theme","text":"theme incomplete theme object complete, NULL complete default theme. default complete theme fill missing pieces. Defaults global theme settings.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Complete a theme — complete_theme","text":"theme object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/complete_theme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Complete a theme — complete_theme","text":"","code":"my_theme <- theme(line = element_line(colour = \"red\")) complete_theme(my_theme) #> List of 139 #> $ line :List of 7 #> ..$ colour : chr \"red\" #> ..$ linewidth : num 0.5 #> ..$ linetype : num 1 #> ..$ lineend : chr \"butt\" #> ..$ arrow : logi FALSE #> ..$ arrow.fill : chr \"red\" #> ..$ inherit.blank: logi FALSE #> ..- attr(*, \"class\")= chr [1:2] \"element_line\" \"element\" #> $ rect :List of 5 #> ..$ fill : chr \"white\" #> ..$ colour : chr \"black\" #> ..$ linewidth : num 0.5 #> ..$ linetype : num 1 #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\" #> $ text :List of 11 #> ..$ family : chr \"\" #> ..$ face : chr \"plain\" #> ..$ colour : chr \"black\" #> ..$ size : num 11 #> ..$ hjust : num 0.5 #> ..$ vjust : num 0.5 #> ..$ angle : num 0 #> ..$ lineheight : num 0.9 #> ..$ margin : 'margin' num [1:4] 0points 0points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : logi FALSE #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ title :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ geom :List of 12 #> ..$ ink : chr \"black\" #> ..$ paper : chr \"white\" #> ..$ accent : chr \"#3366FF\" #> ..$ linewidth : num 0.5 #> ..$ borderwidth : num 0.5 #> ..$ linetype : int 1 #> ..$ bordertype : int 1 #> ..$ family : chr \"\" #> ..$ fontsize : num 3.87 #> ..$ pointsize : num 1.5 #> ..$ pointshape : num 19 #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_geom\" \"element\" #> $ spacing : 'simpleUnit' num 5.5points #> ..- attr(*, \"unit\")= int 8 #> $ margins : 'margin' num [1:4] 5.5points 5.5points 5.5points 5.5points #> ..- attr(*, \"unit\")= int 8 #> $ aspect.ratio : NULL #> $ axis.title : NULL #> $ axis.title.x :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 2.75points 0points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.title.x.top :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 0 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 2.75points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.title.x.bottom : NULL #> $ axis.title.y :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : num 90 #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 2.75points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.title.y.left : NULL #> $ axis.title.y.right :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : num -90 #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 0points 2.75points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : chr \"grey30\" #> ..$ size : 'rel' num 0.8 #> ..$ hjust : NULL #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.x :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 1 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 2.2points 0points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.x.top :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : NULL #> ..$ vjust : num 0 #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 2.2points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.x.bottom : NULL #> $ axis.text.y :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 1 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 2.2points 0points 0points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.y.left : NULL #> $ axis.text.y.right :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 0 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 0points 0points 2.2points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.text.theta : NULL #> $ axis.text.r :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 0.5 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : 'margin' num [1:4] 0points 2.2points 0points 2.2points #> .. ..- attr(*, \"unit\")= int 8 #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ axis.ticks :List of 7 #> ..$ colour : chr \"grey20\" #> ..$ linewidth : NULL #> ..$ linetype : NULL #> ..$ lineend : NULL #> ..$ arrow : logi FALSE #> ..$ arrow.fill : chr \"grey20\" #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_line\" \"element\" #> $ axis.ticks.x : NULL #> $ axis.ticks.x.top : NULL #> $ axis.ticks.x.bottom : NULL #> $ axis.ticks.y : NULL #> $ axis.ticks.y.left : NULL #> $ axis.ticks.y.right : NULL #> $ axis.ticks.theta : NULL #> $ axis.ticks.r : NULL #> $ axis.minor.ticks.x.top : NULL #> $ axis.minor.ticks.x.bottom : NULL #> $ axis.minor.ticks.y.left : NULL #> $ axis.minor.ticks.y.right : NULL #> $ axis.minor.ticks.theta : NULL #> $ axis.minor.ticks.r : NULL #> $ axis.ticks.length : 'rel' num 0.5 #> $ axis.ticks.length.x : NULL #> $ axis.ticks.length.x.top : NULL #> $ axis.ticks.length.x.bottom : NULL #> $ axis.ticks.length.y : NULL #> $ axis.ticks.length.y.left : NULL #> $ axis.ticks.length.y.right : NULL #> $ axis.ticks.length.theta : NULL #> $ axis.ticks.length.r : NULL #> $ axis.minor.ticks.length : 'rel' num 0.75 #> $ axis.minor.ticks.length.x : NULL #> $ axis.minor.ticks.length.x.top : NULL #> $ axis.minor.ticks.length.x.bottom: NULL #> $ axis.minor.ticks.length.y : NULL #> $ axis.minor.ticks.length.y.left : NULL #> $ axis.minor.ticks.length.y.right : NULL #> $ axis.minor.ticks.length.theta : NULL #> $ axis.minor.ticks.length.r : NULL #> $ axis.line : list() #> ..- attr(*, \"class\")= chr [1:2] \"element_blank\" \"element\" #> $ axis.line.x : NULL #> $ axis.line.x.top : NULL #> $ axis.line.x.bottom : NULL #> $ axis.line.y : NULL #> $ axis.line.y.left : NULL #> $ axis.line.y.right : NULL #> $ axis.line.theta : NULL #> $ axis.line.r : NULL #> $ legend.background :List of 5 #> ..$ fill : NULL #> ..$ colour : logi NA #> ..$ linewidth : NULL #> ..$ linetype : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_rect\" \"element\" #> $ legend.margin : NULL #> $ legend.spacing : 'rel' num 2 #> $ legend.spacing.x : NULL #> $ legend.spacing.y : NULL #> $ legend.key : NULL #> $ legend.key.size : 'simpleUnit' num 1.2lines #> ..- attr(*, \"unit\")= int 3 #> $ legend.key.height : NULL #> $ legend.key.width : NULL #> $ legend.key.spacing : NULL #> $ legend.key.spacing.x : NULL #> $ legend.key.spacing.y : NULL #> $ legend.frame : NULL #> $ legend.ticks : NULL #> $ legend.ticks.length : 'rel' num 0.2 #> $ legend.axis.line : NULL #> $ legend.text :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : 'rel' num 0.8 #> ..$ hjust : NULL #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ legend.text.position : NULL #> $ legend.title :List of 11 #> ..$ family : NULL #> ..$ face : NULL #> ..$ colour : NULL #> ..$ size : NULL #> ..$ hjust : num 0 #> ..$ vjust : NULL #> ..$ angle : NULL #> ..$ lineheight : NULL #> ..$ margin : NULL #> ..$ debug : NULL #> ..$ inherit.blank: logi TRUE #> ..- attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" #> $ legend.title.position : NULL #> $ legend.position : chr \"right\" #> $ legend.position.inside : NULL #> $ legend.direction : NULL #> $ legend.byrow : NULL #> $ legend.justification : chr \"center\" #> $ legend.justification.top : NULL #> $ legend.justification.bottom : NULL #> $ legend.justification.left : NULL #> $ legend.justification.right : NULL #> $ legend.justification.inside : NULL #> $ legend.location : NULL #> $ legend.box : NULL #> $ legend.box.just : NULL #> [list output truncated] #> - attr(*, \"class\")= chr [1:2] \"theme\" \"gg\" #> - attr(*, \"complete\")= logi TRUE #> - attr(*, \"validate\")= logi FALSE"},{"path":"https://ggplot2.tidyverse.org/dev/reference/continuous_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Continuous scale constructor — continuous_scale","title":"Continuous scale constructor — continuous_scale","text":"Continuous scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/continuous_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Continuous scale constructor — continuous_scale","text":"","code":"continuous_scale( aesthetics, scale_name = deprecated(), palette, name = waiver(), breaks = waiver(), minor_breaks = waiver(), n.breaks = NULL, labels = waiver(), limits = NULL, rescaler = rescale, oob = censor, expand = waiver(), na.value = NA_real_, transform = \"identity\", trans = deprecated(), guide = \"legend\", position = \"left\", call = caller_call(), super = ScaleContinuous )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/continuous_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Continuous scale constructor — continuous_scale","text":"aesthetics names aesthetics scale works . scale_name name scale used error messages associated scale. palette palette function called numeric vector values 0 1 returns corresponding output values (e.g., scales::pal_area()). name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. na.value Missing values replaced value. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. call call used construct scale reporting messages. super super class use constructed scale","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":null,"dir":"Reference","previous_headings":"","what":"Cartesian coordinates — coord_cartesian","title":"Cartesian coordinates — coord_cartesian","text":"Cartesian coordinate system familiar, common, type coordinate system. Setting limits coordinate system zoom plot (like looking magnifying glass), change underlying data like setting limits scale .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cartesian coordinates — coord_cartesian","text":"","code":"coord_cartesian( xlim = NULL, ylim = NULL, expand = TRUE, default = FALSE, clip = \"on\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cartesian coordinates — coord_cartesian","text":"xlim, ylim Limits x y axes. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. Giving logical vector separately control expansion four directions (top, left, bottom right). expand argument recycled length 4 necessary. Alternatively, can named logical vector control single direction, e.g. expand = c(bottom = FALSE). default default coordinate system? FALSE (default), replacing coordinate system another one creates message alerting user coordinate system replaced. TRUE, warning suppressed. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_cartesian.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cartesian coordinates — coord_cartesian","text":"","code":"# There are two ways of zooming the plot display: with scales or # with coordinate systems. They work in two rather different ways. p <- ggplot(mtcars, aes(disp, wt)) + geom_point() + geom_smooth() p #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Setting the limits on a scale converts all values outside the range to NA. p + scale_x_continuous(limits = c(325, 500)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' #> Warning: Removed 24 rows containing non-finite outside the scale range #> (`stat_smooth()`). #> Warning: Removed 24 rows containing missing values or values outside the scale #> range (`geom_point()`). # Setting the limits on the coordinate system performs a visual zoom. # The data is unchanged, and we just view a small portion of the original # plot. Note how smooth continues past the points visible on this plot. p + coord_cartesian(xlim = c(325, 500)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # By default, the same expansion factor is applied as when setting scale # limits. You can set the limits precisely by setting expand = FALSE p + coord_cartesian(xlim = c(325, 500), expand = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Similarly, we can use expand = FALSE to turn off expansion with the # default limits p + coord_cartesian(expand = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # You can see the same thing with this 2d histogram d <- ggplot(diamonds, aes(carat, price)) + stat_bin_2d(bins = 25, colour = \"white\") d # When zooming the scale, the we get 25 new bins that are the same # size on the plot, but represent smaller regions of the data space d + scale_x_continuous(limits = c(0, 1)) #> Warning: Removed 17502 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 17 rows containing missing values or values outside the scale #> range (`geom_tile()`). # When zooming the coordinate system, we see a subset of original 50 bins, # displayed bigger d + coord_cartesian(xlim = c(0, 1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":null,"dir":"Reference","previous_headings":"","what":"Cartesian coordinates with fixed ","title":"Cartesian coordinates with fixed ","text":"fixed scale coordinate system forces specified ratio physical representation data units axes. ratio represents number units y-axis equivalent one unit x-axis. default, ratio = 1, ensures one unit x-axis length one unit y-axis. Ratios higher one make units y axis longer units x-axis, vice versa. similar MASS::eqscplot(), works types graphics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cartesian coordinates with fixed ","text":"","code":"coord_fixed(ratio = 1, xlim = NULL, ylim = NULL, expand = TRUE, clip = \"on\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cartesian coordinates with fixed ","text":"ratio aspect ratio, expressed y / x xlim, ylim Limits x y axes. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. Giving logical vector separately control expansion four directions (top, left, bottom right). expand argument recycled length 4 necessary. Alternatively, can named logical vector control single direction, e.g. expand = c(bottom = FALSE). clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_fixed.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cartesian coordinates with fixed ","text":"","code":"# ensures that the ranges of axes are equal to the specified ratio by # adjusting the plot aspect ratio p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p + coord_fixed(ratio = 1) p + coord_fixed(ratio = 5) p + coord_fixed(ratio = 1/5) p + coord_fixed(xlim = c(15, 30)) # Resize the plot to see that the specified aspect ratio is maintained"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":null,"dir":"Reference","previous_headings":"","what":"Cartesian coordinates with x and y flipped — coord_flip","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"function superseded many cases, coord_flip() can easily replaced swapping x y aesthetics, optionally setting orientation argument geom stat layers. coord_flip() useful geoms statistics support orientation setting, converting display y conditional x, x conditional y.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"","code":"coord_flip(xlim = NULL, ylim = NULL, expand = TRUE, clip = \"on\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"xlim, ylim Limits x y axes. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. Giving logical vector separately control expansion four directions (top, left, bottom right). expand argument recycled length 4 necessary. Alternatively, can named logical vector control single direction, e.g. expand = c(bottom = FALSE). clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"Coordinate systems interact many parts plotting system. can expect following coord_flip(): change facet order facet_grid() facet_wrap(). scale_x_*() functions apply vertical direction, whereas scale_y_*() functions apply horizontal direction. holds xlim ylim arguments coord_flip() xlim() ylim() functions. x-axis theme settings, axis.line.x apply horizontal direction. y-axis theme settings, axis.text.y apply vertical direction.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_flip.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Cartesian coordinates with x and y flipped — coord_flip","text":"","code":"# The preferred method of creating horizontal instead of vertical boxplots ggplot(diamonds, aes(price, cut)) + geom_boxplot() # Using `coord_flip()` to make the same plot ggplot(diamonds, aes(cut, price)) + geom_boxplot() + coord_flip() # With swapped aesthetics, the y-scale controls the left axis ggplot(diamonds, aes(y = carat)) + geom_histogram() + scale_y_reverse() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # In `coord_flip()`, the x-scale controls the left axis ggplot(diamonds, aes(carat)) + geom_histogram() + coord_flip() + scale_x_reverse() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # In line and area plots, swapped aesthetics require an explicit orientation df <- data.frame(a = 1:5, b = (1:5) ^ 2) ggplot(df, aes(b, a)) + geom_area(orientation = \"y\") # The same plot with `coord_flip()` ggplot(df, aes(a, b)) + geom_area() + coord_flip()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":null,"dir":"Reference","previous_headings":"","what":"Map projections — coord_map","title":"Map projections — coord_map","text":"coord_map() projects portion earth, approximately spherical, onto flat 2D plane using projection defined mapproj package. Map projections , general, preserve straight lines, requires considerable computation. coord_quickmap() quick approximation preserve straight lines. works best smaller areas closer equator. coord_map() coord_quickmap() superseded coord_sf(), longer used new code. regular (non-sf) geoms can used coord_sf() setting default coordinate system via default_crs argument. See also examples annotation_map() geom_map().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Map projections — coord_map","text":"","code":"coord_map( projection = \"mercator\", ..., parameters = NULL, orientation = NULL, xlim = NULL, ylim = NULL, clip = \"on\" ) coord_quickmap(xlim = NULL, ylim = NULL, expand = TRUE, clip = \"on\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Map projections — coord_map","text":"projection projection use, see mapproj::mapproject() list ..., parameters arguments passed mapproj::mapproject(). Use ... named parameters projection, parameters unnamed parameters. ... ignored parameters argument present. orientation projection orientation, defaults c(90, 0, mean(range(x))). optimal many projections, supply . See mapproj::mapproject() information. xlim, ylim Manually specific x/y limits (degrees longitude/latitude) clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . details, please see coord_cartesian(). expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. Giving logical vector separately control expansion four directions (top, left, bottom right). expand argument recycled length 4 necessary. Alternatively, can named logical vector control single direction, e.g. expand = c(bottom = FALSE).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Map projections — coord_map","text":"Map projections must account fact actual length (km) one degree longitude varies equator pole. Near equator, ratio lengths one degree latitude one degree longitude approximately 1. Near pole, tends towards infinity length one degree longitude tends towards 0. regions span degrees close poles, setting aspect ratio plot appropriate lat/lon ratio approximates usual mercator projection. coord_quickmap() , much faster (particularly complex plots like geom_tile()) expense correctness.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Map projections — coord_map","text":"","code":"if (require(\"maps\")) { nz <- map_data(\"nz\") # Prepare a map of NZ nzmap <- ggplot(nz, aes(x = long, y = lat, group = group)) + geom_polygon(fill = \"white\", colour = \"black\") # Plot it in cartesian coordinates nzmap } if (require(\"maps\")) { # With correct mercator projection nzmap + coord_map() } if (require(\"maps\")) { # With the aspect ratio approximation nzmap + coord_quickmap() } if (require(\"maps\")) { # Other projections nzmap + coord_map(\"azequalarea\", orientation = c(-36.92, 174.6, 0)) } if (require(\"maps\")) { states <- map_data(\"state\") usamap <- ggplot(states, aes(long, lat, group = group)) + geom_polygon(fill = \"white\", colour = \"black\") # Use cartesian coordinates usamap } if (require(\"maps\")) { # With mercator projection usamap + coord_map() } if (require(\"maps\")) { # See ?mapproject for coordinate systems and their parameters usamap + coord_map(\"gilbert\") } if (require(\"maps\")) { # For most projections, you'll need to set the orientation yourself # as the automatic selection done by mapproject is not available to # ggplot usamap + coord_map(\"orthographic\") } if (require(\"maps\")) { usamap + coord_map(\"conic\", lat0 = 30) } if (require(\"maps\")) { usamap + coord_map(\"bonne\", lat0 = 50) } if (FALSE) { # \\dontrun{ if (require(\"maps\")) { # World map, using geom_path instead of geom_polygon world <- map_data(\"world\") worldmap <- ggplot(world, aes(x = long, y = lat, group = group)) + geom_path() + scale_y_continuous(breaks = (-2:2) * 30) + scale_x_continuous(breaks = (-4:4) * 45) # Orthographic projection with default orientation (looking down at North pole) worldmap + coord_map(\"ortho\") } if (require(\"maps\")) { # Looking up up at South Pole worldmap + coord_map(\"ortho\", orientation = c(-90, 0, 0)) } if (require(\"maps\")) { # Centered on New York (currently has issues with closing polygons) worldmap + coord_map(\"ortho\", orientation = c(41, -74, 0)) } } # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_munch.html","id":null,"dir":"Reference","previous_headings":"","what":"Munch coordinates data — coord_munch","title":"Munch coordinates data — coord_munch","text":"function \"munches\" lines, dividing line many small pieces can transformed independently. Used inside geom functions.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_munch.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Munch coordinates data — coord_munch","text":"","code":"coord_munch(coord, data, range, segment_length = 0.01, is_closed = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_munch.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Munch coordinates data — coord_munch","text":"coord Coordinate system definition. data Data set transform - variables x y chopped small pieces (defined group). variables duplicated needed. range Panel range specification. segment_length Target segment length is_closed Whether data considered closed polygon.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":null,"dir":"Reference","previous_headings":"","what":"Polar coordinates — coord_polar","title":"Polar coordinates — coord_polar","text":"polar coordinate system commonly used pie charts, stacked bar chart polar coordinates. coord_radial() extended options.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Polar coordinates — coord_polar","text":"","code":"coord_polar(theta = \"x\", start = 0, direction = 1, clip = \"on\") coord_radial( theta = \"x\", start = 0, end = NULL, expand = TRUE, direction = 1, clip = \"off\", r.axis.inside = NULL, rotate.angle = FALSE, inner.radius = 0, r_axis_inside = deprecated(), rotate_angle = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Polar coordinates — coord_polar","text":"theta variable map angle (x y) start Offset starting point 12 o'clock radians. Offset applied clockwise anticlockwise depending value direction. direction 1, clockwise; -1, anticlockwise clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . details, please see coord_cartesian(). end Position 12 o'clock radians plot ends, allow partial polar coordinates. default, NULL, set start + 2 * pi. expand TRUE, default, adds small expansion factor limits prevent overlap data axes. FALSE, limits taken directly scale. r.axis.inside One following: NULL (default) places axis next panel start end arguments form full circle inside panel otherwise. TRUE place radius axis inside panel. FALSE place radius axis next panel. numeric value, setting theta axis value axis placed inside panel. Can given length 2 vector control primary secondary axis placement separately. rotate.angle TRUE, transforms angle aesthetic data accordance computed theta position. FALSE (default), transformation performed. Can useful rotate text geoms alignment coordinates. inner.radius numeric 0 1 setting size inner.radius hole. r_axis_inside, rotate_angle","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Polar coordinates — coord_polar","text":"coord_radial(), position guides can defined using guides(r = ..., theta = ..., r.sec = ..., theta.sec = ...). Note guides require r theta available aesthetics. classic guide_axis() can used r positions guide_axis_theta() can used theta positions. Using theta.sec position sensible inner.radius > 0.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_polar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Polar coordinates — coord_polar","text":"","code":"# NOTE: Use these plots with caution - polar coordinates has # major perceptual problems. The main point of these examples is # to demonstrate how these common plots can be described in the # grammar. Use with EXTREME caution. #' # A pie chart = stacked bar chart + polar coordinates pie <- ggplot(mtcars, aes(x = factor(1), fill = factor(cyl))) + geom_bar(width = 1) pie + coord_polar(theta = \"y\") # \\donttest{ # A coxcomb plot = bar chart + polar coordinates cxc <- ggplot(mtcars, aes(x = factor(cyl))) + geom_bar(width = 1, colour = \"black\") cxc + coord_polar() # A new type of plot? cxc + coord_polar(theta = \"y\") # The bullseye chart pie + coord_polar() # Hadley's favourite pie chart df <- data.frame( variable = c(\"does not resemble\", \"resembles\"), value = c(20, 80) ) ggplot(df, aes(x = \"\", y = value, fill = variable)) + geom_col(width = 1) + scale_fill_manual(values = c(\"red\", \"yellow\")) + coord_polar(\"y\", start = pi / 3) + labs(title = \"Pac man\") # Windrose + doughnut plot if (require(\"ggplot2movies\")) { movies$rrating <- cut_interval(movies$rating, length = 1) movies$budgetq <- cut_number(movies$budget, 4) doh <- ggplot(movies, aes(x = rrating, fill = budgetq)) # Wind rose doh + geom_bar(width = 1) + coord_polar() # Race track plot doh + geom_bar(width = 0.9, position = \"fill\") + coord_polar(theta = \"y\") } #> Loading required package: ggplot2movies # } # A partial polar plot ggplot(mtcars, aes(disp, mpg)) + geom_point() + coord_radial(start = -0.4 * pi, end = 0.4 * pi, inner.radius = 0.3)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":null,"dir":"Reference","previous_headings":"","what":"Transformed Cartesian coordinate system — coord_trans","title":"Transformed Cartesian coordinate system — coord_trans","text":"coord_trans() different scale transformations occurs statistical transformation affect visual appearance geoms - guarantee straight lines continue straight.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Transformed Cartesian coordinate system — coord_trans","text":"","code":"coord_trans( x = \"identity\", y = \"identity\", xlim = NULL, ylim = NULL, limx = deprecated(), limy = deprecated(), clip = \"on\", expand = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Transformed Cartesian coordinate system — coord_trans","text":"x, y Transformers x y axes names. xlim, ylim Limits x y axes. limx, limy use xlim ylim instead. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. Giving logical vector separately control expansion four directions (top, left, bottom right). expand argument recycled length 4 necessary. Alternatively, can named logical vector control single direction, e.g. expand = c(bottom = FALSE).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Transformed Cartesian coordinate system — coord_trans","text":"Transformations work continuous values: see scales::new_transform() list transformations, instructions create .","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/coord_trans.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Transformed Cartesian coordinate system — coord_trans","text":"","code":"# \\donttest{ # See ?geom_boxplot for other examples # Three ways of doing transformation in ggplot: # * by transforming the data ggplot(diamonds, aes(log10(carat), log10(price))) + geom_point() # * by transforming the scales ggplot(diamonds, aes(carat, price)) + geom_point() + scale_x_log10() + scale_y_log10() # * by transforming the coordinate system: ggplot(diamonds, aes(carat, price)) + geom_point() + coord_trans(x = \"log10\", y = \"log10\") # The difference between transforming the scales and # transforming the coordinate system is that scale # transformation occurs BEFORE statistics, and coordinate # transformation afterwards. Coordinate transformation also # changes the shape of geoms: d <- subset(diamonds, carat > 0.5) ggplot(d, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") + scale_x_log10() + scale_y_log10() #> `geom_smooth()` using formula = 'y ~ x' ggplot(d, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") + coord_trans(x = \"log10\", y = \"log10\") #> `geom_smooth()` using formula = 'y ~ x' # Here I used a subset of diamonds so that the smoothed line didn't # drop below zero, which obviously causes problems on the log-transformed # scale # With a combination of scale and coordinate transformation, it's # possible to do back-transformations: ggplot(diamonds, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") + scale_x_log10() + scale_y_log10() + coord_trans(x = scales::transform_exp(10), y = scales::transform_exp(10)) #> `geom_smooth()` using formula = 'y ~ x' #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced # cf. ggplot(diamonds, aes(carat, price)) + geom_point() + geom_smooth(method = \"lm\") #> `geom_smooth()` using formula = 'y ~ x' # Also works with discrete scales set.seed(1) df <- data.frame(a = abs(rnorm(26)),letters) plot <- ggplot(df,aes(a,letters)) + geom_point() plot + coord_trans(x = \"log10\") plot + coord_trans(x = \"sqrt\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":null,"dir":"Reference","previous_headings":"","what":"Discretise numeric data into categorical — cut_interval","title":"Discretise numeric data into categorical — cut_interval","text":"cut_interval() makes n groups equal range, cut_number() makes n groups (approximately) equal numbers observations; cut_width() makes groups width width.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discretise numeric data into categorical — cut_interval","text":"","code":"cut_interval(x, n = NULL, length = NULL, ...) cut_number(x, n = NULL, ...) cut_width(x, width, center = NULL, boundary = NULL, closed = \"right\", ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discretise numeric data into categorical — cut_interval","text":"x numeric vector n number intervals create, length length interval ... Arguments passed base::cut.default breaks either numeric vector two unique cut points single number (greater equal 2) giving number intervals x cut. labels labels levels resulting category. default, labels constructed using \"(,b]\" interval notation. labels = FALSE, simple integer codes returned instead factor. right logical, indicating intervals closed right (open left) vice versa. dig.lab integer used labels given. determines number digits used formatting break numbers. ordered_result logical: result ordered factor? width bin width. center, boundary Specify either position edge center bin. Since bins aligned, specifying position single bin (need range data) affects location bins. specified, uses \"tile layers algorithm\", sets boundary half binwidth. center integers, width = 1 center = 0. boundary = 0.5. closed One \"right\" \"left\" indicating whether right left edges bins included bin.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"Discretise numeric data into categorical — cut_interval","text":"Randall Prium contributed implementation cut_width().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/cut_interval.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Discretise numeric data into categorical — cut_interval","text":"","code":"table(cut_interval(1:100, 10)) #> #> [1,10.9] (10.9,20.8] (20.8,30.7] (30.7,40.6] (40.6,50.5] (50.5,60.4] #> 10 10 10 10 10 10 #> (60.4,70.3] (70.3,80.2] (80.2,90.1] (90.1,100] #> 10 10 10 10 table(cut_interval(1:100, 11)) #> #> [1,10] (10,19] (19,28] (28,37] (37,46] (46,55] (55,64] (64,73] #> 10 9 9 9 9 9 9 9 #> (73,82] (82,91] (91,100] #> 9 9 9 set.seed(1) table(cut_number(runif(1000), 10)) #> #> [0.00131,0.105] (0.105,0.201] (0.201,0.312] (0.312,0.398] #> 100 100 100 100 #> (0.398,0.483] (0.483,0.596] (0.596,0.706] (0.706,0.797] #> 100 100 100 100 #> (0.797,0.91] (0.91,1] #> 100 100 table(cut_width(runif(1000), 0.1)) #> #> [-0.05,0.05] (0.05,0.15] (0.15,0.25] (0.25,0.35] (0.35,0.45] #> 59 109 103 96 110 #> (0.45,0.55] (0.55,0.65] (0.65,0.75] (0.75,0.85] (0.85,0.95] #> 85 89 86 113 97 #> (0.95,1.05] #> 53 table(cut_width(runif(1000), 0.1, boundary = 0)) #> #> [0,0.1] (0.1,0.2] (0.2,0.3] (0.3,0.4] (0.4,0.5] (0.5,0.6] (0.6,0.7] #> 106 106 108 100 99 107 84 #> (0.7,0.8] (0.8,0.9] (0.9,1] #> 96 95 99 table(cut_width(runif(1000), 0.1, center = 0)) #> #> [-0.05,0.05] (0.05,0.15] (0.15,0.25] (0.25,0.35] (0.35,0.45] #> 72 104 80 104 100 #> (0.45,0.55] (0.55,0.65] (0.65,0.75] (0.75,0.85] (0.85,0.95] #> 91 94 75 115 110 #> (0.95,1.05] #> 55 table(cut_width(runif(1000), 0.1, labels = FALSE)) #> #> 1 2 3 4 5 6 7 8 9 10 11 #> 49 92 100 98 112 102 88 89 97 116 57"},{"path":"https://ggplot2.tidyverse.org/dev/reference/datetime_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Date/time scale constructor — datetime_scale","title":"Date/time scale constructor — datetime_scale","text":"Date/time scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/datetime_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Date/time scale constructor — datetime_scale","text":"","code":"datetime_scale( aesthetics, transform, trans = deprecated(), palette, breaks = pretty_breaks(), minor_breaks = waiver(), labels = waiver(), date_breaks = waiver(), date_labels = waiver(), date_minor_breaks = waiver(), timezone = NULL, guide = \"legend\", call = caller_call(), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/datetime_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Date/time scale constructor — datetime_scale","text":"aesthetics names aesthetics scale works . transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans date/time scales, name date/time transformation object . Built-transformations include \"hms\", \"date\" \"time\". palette palette function called numeric vector values 0 1 returns corresponding output values (e.g., scales::pal_area()). breaks One : NULL breaks waiver() breaks specified date_breaks Date/POSIXct vector giving positions breaks function takes limits input returns breaks output minor_breaks One : NULL breaks waiver() breaks specified date_minor_breaks Date/POSIXct vector giving positions minor breaks function takes limits input returns minor breaks output labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. date_breaks string giving distance breaks like \"2 weeks\", \"10 years\". breaks date_breaks specified, date_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. date_labels string giving formatting specification labels. Codes defined strftime(). labels date_labels specified, date_labels wins. date_minor_breaks string giving distance minor breaks like \"2 weeks\", \"10 years\". minor_breaks date_minor_breaks specified, date_minor_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. timezone timezone use display axes. default (NULL) uses timezone encoded data. guide function used create guide name. See guides() information. call call used construct scale reporting messages. ... Arguments passed continuous_scale scale_name name scale used error messages associated scale. name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. position position scales, position axis. left right y axes, top bottom x axes. super super class use constructed scale","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/diamonds.html","id":null,"dir":"Reference","previous_headings":"","what":"Prices of over 50,000 round cut diamonds — diamonds","title":"Prices of over 50,000 round cut diamonds — diamonds","text":"dataset containing prices attributes almost 54,000 diamonds. variables follows:","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/diamonds.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Prices of over 50,000 round cut diamonds — diamonds","text":"","code":"diamonds"},{"path":"https://ggplot2.tidyverse.org/dev/reference/diamonds.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Prices of over 50,000 round cut diamonds — diamonds","text":"data frame 53940 rows 10 variables: price price US dollars ($326–$18,823) carat weight diamond (0.2–5.01) cut quality cut (Fair, Good, Good, Premium, Ideal) color diamond colour, D (best) J (worst) clarity measurement clear diamond (I1 (worst), SI2, SI1, VS2, VS1, VVS2, VVS1, (best)) x length mm (0–10.74) y width mm (0–58.9) z depth mm (0–31.8) depth total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43–79) table width top diamond relative widest point (43–95)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/discrete_scale.html","id":null,"dir":"Reference","previous_headings":"","what":"Discrete scale constructor — discrete_scale","title":"Discrete scale constructor — discrete_scale","text":"Discrete scale constructor","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/discrete_scale.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discrete scale constructor — discrete_scale","text":"","code":"discrete_scale( aesthetics, scale_name = deprecated(), palette, name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), na.translate = TRUE, na.value = NA, drop = TRUE, guide = \"legend\", position = \"left\", call = caller_call(), super = ScaleDiscrete )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/discrete_scale.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discrete scale constructor — discrete_scale","text":"aesthetics names aesthetics scale works . scale_name name scale used error messages associated scale. palette palette function called single integer argument (number levels scale) returns values take (e.g., scales::pal_hue()). name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. na.value na.translate = TRUE, aesthetic value missing values displayed ? apply position scales NA always placed far right. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. call call used construct scale reporting messages. super super class use constructed scale","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":null,"dir":"Reference","previous_headings":"","what":"Key glyphs for legends — draw_key","title":"Key glyphs for legends — draw_key","text":"geom associated function draws key geom needs displayed legend. functions called draw_key_*(), * stands name respective key glyph. key glyphs can customized individual geoms providing geom key_glyph argument (see layer() examples .)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Key glyphs for legends — draw_key","text":"","code":"draw_key_point(data, params, size) draw_key_abline(data, params, size) draw_key_rect(data, params, size) draw_key_polygon(data, params, size) draw_key_blank(data, params, size) draw_key_boxplot(data, params, size) draw_key_crossbar(data, params, size) draw_key_path(data, params, size) draw_key_vpath(data, params, size) draw_key_dotplot(data, params, size) draw_key_linerange(data, params, size) draw_key_pointrange(data, params, size) draw_key_smooth(data, params, size) draw_key_text(data, params, size) draw_key_label(data, params, size) draw_key_vline(data, params, size) draw_key_timeseries(data, params, size)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Key glyphs for legends — draw_key","text":"data single row data frame containing scaled aesthetics display key params list additional parameters supplied geom. size Width height key mm.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Key glyphs for legends — draw_key","text":"grid grob.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/draw_key.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Key glyphs for legends — draw_key","text":"","code":"p <- ggplot(economics, aes(date, psavert, color = \"savings rate\")) # key glyphs can be specified by their name p + geom_line(key_glyph = \"timeseries\") # key glyphs can be specified via their drawing function p + geom_line(key_glyph = draw_key_rect)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/economics.html","id":null,"dir":"Reference","previous_headings":"","what":"US economic time series — economics","title":"US economic time series — economics","text":"dataset produced US economic time series data available https://fred.stlouisfed.org/. economics \"wide\" format, economics_long \"long\" format.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/economics.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"US economic time series — economics","text":"","code":"economics economics_long"},{"path":"https://ggplot2.tidyverse.org/dev/reference/economics.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"US economic time series — economics","text":"data frame 574 rows 6 variables: date Month data collection pce personal consumption expenditures, billions dollars, https://fred.stlouisfed.org/series/PCE pop total population, thousands, https://fred.stlouisfed.org/series/POP psavert personal savings rate, https://fred.stlouisfed.org/series/PSAVERT/ uempmed median duration unemployment, weeks, https://fred.stlouisfed.org/series/UEMPMED unemploy number unemployed thousands, https://fred.stlouisfed.org/series/UNEMPLOY object class tbl_df (inherits tbl, data.frame) 2870 rows 4 columns.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":null,"dir":"Reference","previous_headings":"","what":"Theme elements — element","title":"Theme elements — element","text":"conjunction theme system, element_ functions specify display non-data components plot drawn. element_blank(): draws nothing, assigns space. element_rect(): borders backgrounds. element_line(): lines. element_text(): text. element_geom(): defaults drawing layers. rel() used specify sizes relative parent, margin() used specify margins elements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Theme elements — element","text":"","code":"element_blank() element_rect( fill = NULL, colour = NULL, linewidth = NULL, linetype = NULL, color = NULL, inherit.blank = FALSE, size = deprecated() ) element_line( colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL, color = NULL, arrow = NULL, arrow.fill = NULL, inherit.blank = FALSE, size = deprecated() ) element_text( family = NULL, face = NULL, colour = NULL, size = NULL, hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL, color = NULL, margin = NULL, debug = NULL, inherit.blank = FALSE ) element_geom( ink = NULL, paper = NULL, accent = NULL, linewidth = NULL, borderwidth = NULL, linetype = NULL, bordertype = NULL, family = NULL, fontsize = NULL, pointsize = NULL, pointshape = NULL ) rel(x) margin(t = 0, r = 0, b = 0, l = 0, unit = \"pt\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Theme elements — element","text":"fill Fill colour. colour, color Line/border colour. Color alias colour. linewidth, borderwidth Line/border size mm. linetype, bordertype Line type lines borders respectively. integer (0:8), name (blank, solid, dashed, dotted, dotdash, longdash, twodash), string even number (eight) hexadecimal digits give lengths consecutive positions string. inherit.blank element inherit existence element_blank among parents? TRUE existence blank element among parents cause element blank well. FALSE blank parent element ignored calculating final element state. size, fontsize text size pts. lineend Line end Line end style (round, butt, square) arrow Arrow specification, created grid::arrow() arrow.fill Fill colour arrows. family Font family face Font face (\"plain\", \"italic\", \"bold\", \"bold.italic\") hjust Horizontal justification (\\([0, 1]\\)) vjust Vertical justification (\\([0, 1]\\)) angle Angle (\\([0, 360]\\)) lineheight Line height margin Margins around text. See margin() details. creating theme, margins placed side text facing towards center plot. debug TRUE, aids visual debugging drawing solid rectangle behind complete text area, point label anchored. ink Foreground colour. paper Background colour. accent Accent colour. pointsize Size points mm. pointshape Shape points (1-25). x single number specifying size relative parent element. t, r, b, l Dimensions margin. (remember order, think trouble). unit Default units dimensions. Defaults \"pt\" can easily scaled text.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Theme elements — element","text":"S3 object class element, rel, margin.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Theme elements — element","text":"","code":"plot <- ggplot(mpg, aes(displ, hwy)) + geom_point() plot + theme( panel.background = element_blank(), axis.text = element_blank() ) plot + theme( axis.text = element_text(colour = \"red\", size = rel(1.5)) ) plot + theme( axis.line = element_line(arrow = arrow()) ) plot + theme( panel.background = element_rect(fill = \"white\"), plot.margin = margin(2, 2, 2, 2, \"cm\"), plot.background = element_rect( fill = \"grey90\", colour = \"black\", linewidth = 1 ) ) ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(formula = y ~ x, method = \"lm\") + theme(geom = element_geom( ink = \"red\", accent = \"black\", pointsize = 1, linewidth = 2 ))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_grob.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate grid grob from theme element — element_grob","title":"Generate grid grob from theme element — element_grob","text":"Generate grid grob theme element","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_grob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate grid grob from theme element — element_grob","text":"","code":"element_grob(element, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_grob.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate grid grob from theme element — element_grob","text":"element Theme element, .e. element_rect similar. ... arguments control specific rendering. usually least position. See source code individual methods.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_render.html","id":null,"dir":"Reference","previous_headings":"","what":"Render a specified theme element into a grob — element_render","title":"Render a specified theme element into a grob — element_render","text":"Given theme object element name, returns grob element. Uses element_grob() generate grob.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_render.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Render a specified theme element into a grob — element_render","text":"","code":"element_render(theme, element, ..., name = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/element_render.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Render a specified theme element into a grob — element_render","text":"theme theme object element element name given character vector ... arguments provided element_grob() name Character vector added name grob","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":null,"dir":"Reference","previous_headings":"","what":"Expand the plot limits, using data — expand_limits","title":"Expand the plot limits, using data — expand_limits","text":"Sometimes may want ensure limits include single value, panels plots. function thin wrapper around geom_blank() makes easy add values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Expand the plot limits, using data — expand_limits","text":"","code":"expand_limits(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Expand the plot limits, using data — expand_limits","text":"... named list aesthetics specifying value (values) included scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expand_limits.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Expand the plot limits, using data — expand_limits","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p + expand_limits(x = 0) p + expand_limits(y = c(1, 9)) p + expand_limits(x = 0, y = 0) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = cyl)) + expand_limits(colour = seq(2, 10, by = 2)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl))) + expand_limits(colour = factor(seq(2, 10, by = 2)))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate expansion vector for scales — expansion","title":"Generate expansion vector for scales — expansion","text":"convenience function generating scale expansion vectors expand argument scale_(x|y)_continuous scale_(x|y)_discrete. expansion vectors used add space data axes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate expansion vector for scales — expansion","text":"","code":"expansion(mult = 0, add = 0) expand_scale(mult = 0, add = 0)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate expansion vector for scales — expansion","text":"mult vector multiplicative range expansion factors. length 1, lower upper limits scale expanded outwards mult. length 2, lower limit expanded mult[1] upper limit mult[2]. add vector additive range expansion constants. length 1, lower upper limits scale expanded outwards add units. length 2, lower limit expanded add[1] upper limit add[2].","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/expansion.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate expansion vector for scales — expansion","text":"","code":"# No space below the bars but 10% above them ggplot(mtcars) + geom_bar(aes(x = factor(cyl))) + scale_y_continuous(expand = expansion(mult = c(0, .1))) # Add 2 units of space on the left and right of the data ggplot(subset(diamonds, carat > 2), aes(cut, clarity)) + geom_jitter() + scale_x_discrete(expand = expansion(add = 2)) # Reproduce the default range expansion used # when the 'expand' argument is not specified ggplot(subset(diamonds, carat > 2), aes(cut, price)) + geom_jitter() + scale_x_discrete(expand = expansion(add = .6)) + scale_y_continuous(expand = expansion(mult = .05))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":null,"dir":"Reference","previous_headings":"","what":"Lay out panels in a grid — facet_grid","title":"Lay out panels in a grid — facet_grid","text":"facet_grid() forms matrix panels defined row column faceting variables. useful two discrete variables, combinations variables exist data. one variable many levels, try facet_wrap().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Lay out panels in a grid — facet_grid","text":"","code":"facet_grid( rows = NULL, cols = NULL, scales = \"fixed\", space = \"fixed\", shrink = TRUE, labeller = \"label_value\", as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE, axes = \"margins\", axis.labels = \"all\", facets = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Lay out panels in a grid — facet_grid","text":"rows, cols set variables expressions quoted vars() defining faceting groups rows columns dimension. variables can named (names passed labeller). compatibility classic interface, rows can also formula rows (tabular display) LHS columns (tabular display) RHS; dot formula used indicate faceting dimension (either row column). scales scales shared across facets (default, \"fixed\"), vary across rows (\"free_x\"), columns (\"free_y\"), rows columns (\"free\")? space \"fixed\", default, panels size. \"free_y\" height proportional length y scale; \"free_x\" width proportional length x scale; \"free\" height width vary. setting effect unless appropriate scales also vary. shrink TRUE, shrink scales fit output statistics, raw data. FALSE, range raw data statistical summary. labeller function takes one data frame labels returns list data frame character vectors. input column corresponds one factor. Thus one vars(cyl, ). output column gets displayed one separate line strip label. function inherit \"labeller\" S3 class compatibility labeller(). can use different labeling functions different kind labels, example use label_parsed() formatting facet labels. label_value() used default, check details pointers options. .table TRUE, default, facets laid like table highest values bottom-right. FALSE, facets laid like plot highest value top-right. switch default, labels displayed top right plot. \"x\", top labels displayed bottom. \"y\", right-hand side labels displayed left. Can also set \"\". drop TRUE, default, factor levels used data automatically dropped. FALSE, factor levels shown, regardless whether appear data. margins Either logical value character vector. Margins additional facets contain data possible values faceting variables. FALSE, additional facets included (default). TRUE, margins included faceting variables. specified character vector, names variables margins created. axes Determines axes drawn. \"margins\" (default), axes drawn exterior margins. \"all_x\" \"all_y\" draw respective axes interior panels , whereas \"\" draw axes panels. axis.labels Determines whether draw labels interior axes axes argument \"margins\". \"\" (default), interior axes get labels. \"margins\", exterior axes get labels interior axes get none. \"all_x\" \"all_y\", draws labels interior axes x- y-direction respectively. facets Please use rows cols instead.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_grid.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Lay out panels in a grid — facet_grid","text":"","code":"p <- ggplot(mpg, aes(displ, cty)) + geom_point() # Use vars() to supply variables from the dataset: p + facet_grid(rows = vars(drv)) p + facet_grid(cols = vars(cyl)) p + facet_grid(vars(drv), vars(cyl)) # To change plot order of facet grid, # change the order of variable levels with factor() # If you combine a facetted dataset with a dataset that lacks those # faceting variables, the data will be repeated across the missing # combinations: df <- data.frame(displ = mean(mpg$displ), cty = mean(mpg$cty)) p + facet_grid(cols = vars(cyl)) + geom_point(data = df, colour = \"red\", size = 2) # When scales are constant, duplicated axes can be shown with # or without labels ggplot(mpg, aes(cty, hwy)) + geom_point() + facet_grid(year ~ drv, axes = \"all\", axis.labels = \"all_x\") # Free scales ------------------------------------------------------- # You can also choose whether the scales should be constant # across all panels (the default), or whether they should be allowed # to vary mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() mt + facet_grid(vars(cyl), scales = \"free\") # If scales and space are free, then the mapping between position # and values in the data will be the same across all panels. This # is particularly useful for categorical axes ggplot(mpg, aes(drv, model)) + geom_point() + facet_grid(manufacturer ~ ., scales = \"free\", space = \"free\") + theme(strip.text.y = element_text(angle = 0)) # Margins ---------------------------------------------------------- # \\donttest{ # Margins can be specified logically (all yes or all no) or for specific # variables as (character) variable names mg <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point() mg + facet_grid(vs + am ~ gear, margins = TRUE) mg + facet_grid(vs + am ~ gear, margins = \"am\") # when margins are made over \"vs\", since the facets for \"am\" vary # within the values of \"vs\", the marginal facet for \"vs\" is also # a margin over \"am\". mg + facet_grid(vs + am ~ gear, margins = \"vs\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":null,"dir":"Reference","previous_headings":"","what":"Facet specification: a single panel. — facet_null","title":"Facet specification: a single panel. — facet_null","text":"Facet specification: single panel.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Facet specification: a single panel. — facet_null","text":"","code":"facet_null(shrink = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Facet specification: a single panel. — facet_null","text":"shrink TRUE, shrink scales fit output statistics, raw data. FALSE, range raw data statistical summary.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_null.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Facet specification: a single panel. — facet_null","text":"","code":"# facet_null is the default faceting specification if you # don't override it with facet_grid or facet_wrap ggplot(mtcars, aes(mpg, wt)) + geom_point()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":null,"dir":"Reference","previous_headings":"","what":"Wrap a 1d ribbon of panels into 2d — facet_wrap","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"facet_wrap() wraps 1d sequence panels 2d. generally better use screen space facet_grid() displays roughly rectangular.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"","code":"facet_wrap( facets, nrow = NULL, ncol = NULL, scales = \"fixed\", space = \"fixed\", shrink = TRUE, labeller = \"label_value\", as.table = TRUE, switch = deprecated(), drop = TRUE, dir = \"h\", strip.position = \"top\", axes = \"margins\", axis.labels = \"all\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"facets set variables expressions quoted vars() defining faceting groups rows columns dimension. variables can named (names passed labeller). compatibility classic interface, can also formula character vector. Use either one sided formula, ~+ b, character vector, c(\"\", \"b\"). nrow, ncol Number rows columns. scales scales fixed (\"fixed\", default), free (\"free\"), free one dimension (\"free_x\", \"free_y\")? space \"fixed\" (default), panels size number rows columns layout can arbitrary. \"free_x\", panels widths proportional length x-scale, layout constrained one row. \"free_y\", panels heights proportional length y-scale, layout constrained one column. shrink TRUE, shrink scales fit output statistics, raw data. FALSE, range raw data statistical summary. labeller function takes one data frame labels returns list data frame character vectors. input column corresponds one factor. Thus one vars(cyl, ). output column gets displayed one separate line strip label. function inherit \"labeller\" S3 class compatibility labeller(). can use different labeling functions different kind labels, example use label_parsed() formatting facet labels. label_value() used default, check details pointers options. .table TRUE, default, facets laid like table highest values bottom-right. FALSE, facets laid like plot highest value top-right. switch default, labels displayed top right plot. \"x\", top labels displayed bottom. \"y\", right-hand side labels displayed left. Can also set \"\". drop TRUE, default, factor levels used data automatically dropped. FALSE, factor levels shown, regardless whether appear data. dir Direction: either \"h\" horizontal, default, \"v\", vertical. \"h\" \"v\" combined .table set final layout. Alternatively, combination \"t\" (top) \"b\" (bottom) \"l\" (left) \"r\" (right) set layout directly. two letters give starting position first letter gives growing direction. example \"rt\" place first panel top-right starts filling panels right--left. strip.position default, labels displayed top plot. Using strip.position possible place labels either four sides setting strip.position = c(\"top\", \"bottom\", \"left\", \"right\") axes Determines axes drawn case fixed scales. \"margins\" (default), axes drawn exterior margins. \"all_x\" \"all_y\" draw respective axes interior panels , whereas \"\" draw axes panels. axis.labels Determines whether draw labels interior axes scale fixed axis argument \"margins\". \"\" (default), interior axes get labels. \"margins\", exterior axes get labels, interior axes get none. \"all_x\" \"all_y\", draws labels interior axes x- y-direction respectively.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/facet_wrap.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Wrap a 1d ribbon of panels into 2d — facet_wrap","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Use vars() to supply faceting variables: p + facet_wrap(vars(class)) # Control the number of rows and columns with nrow and ncol p + facet_wrap(vars(class), nrow = 4) # \\donttest{ # You can facet by multiple variables ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(cyl, drv)) # Use the `labeller` option to control how labels are printed: ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(cyl, drv), labeller = \"label_both\") # To change the order in which the panels appear, change the levels # of the underlying factor. mpg$class2 <- reorder(mpg$class, mpg$displ) ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class2)) # By default, the same scales are used for all panels. You can allow # scales to vary across the panels with the `scales` argument. # Free scales make it easier to see patterns within each panel, but # harder to compare across panels. ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class), scales = \"free\") # When scales are constant, duplicated axes can be shown with # or without labels ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class), axes = \"all\", axis.labels = \"all_y\") # To repeat the same data in every panel, simply construct a data frame # that does not contain the faceting variable. ggplot(mpg, aes(displ, hwy)) + geom_point(data = transform(mpg, class = NULL), colour = \"grey85\") + geom_point() + facet_wrap(vars(class)) # Use `strip.position` to display the facet labels at the side of your # choice. Setting it to `bottom` makes it act as a subtitle for the axis. # This is typically used with free scales and a theme without boxes around # strip labels. ggplot(economics_long, aes(date, value)) + geom_line() + facet_wrap(vars(variable), scales = \"free_y\", nrow = 2, strip.position = \"top\") + theme(strip.background = element_blank(), strip.placement = \"outside\") # } # The two letters determine the starting position, so 'tr' starts # in the top-right. # The first letter determines direction, so 'tr' fills top-to-bottom. # `dir = \"tr\"` is equivalent to `dir = \"v\", as.table = FALSE` ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(vars(class), dir = \"tr\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/faithfuld.html","id":null,"dir":"Reference","previous_headings":"","what":"2d density estimate of Old Faithful data — faithfuld","title":"2d density estimate of Old Faithful data — faithfuld","text":"2d density estimate waiting eruptions variables data faithful.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/faithfuld.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"2d density estimate of Old Faithful data — faithfuld","text":"","code":"faithfuld"},{"path":"https://ggplot2.tidyverse.org/dev/reference/faithfuld.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"2d density estimate of Old Faithful data — faithfuld","text":"data frame 5,625 observations 3 variables: eruptions Eruption time mins waiting Waiting time next eruption mins density 2d density estimate","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify fill transparency — fill_alpha","title":"Modify fill transparency — fill_alpha","text":"works much like alpha() modifies transparency fill colours. differs fill_alpha() also attempts set transparency objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify fill transparency — fill_alpha","text":"","code":"fill_alpha(fill, alpha)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify fill transparency — fill_alpha","text":"fill fill colour given character integer vector, (list ) object(s). alpha transparency value 0 (transparent) 1 (opaque), parallel fill.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Modify fill transparency — fill_alpha","text":"character vector colours, list objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fill_alpha.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify fill transparency — fill_alpha","text":"","code":"# Typical colour input fill_alpha(\"red\", 0.5) #> [1] \"#FF000080\" if (utils::packageVersion(\"grid\") > \"4.2\") { # Pattern input fill_alpha(list(grid::linearGradient()), 0.5) } #> [[1]] #> $x1 #> [1] 0npc #> #> $y1 #> [1] 0npc #> #> $x2 #> [1] 1npc #> #> $y2 #> [1] 1npc #> #> $stops #> [1] 0 1 #> #> $colours #> [1] \"#00000080\" \"#FFFFFF80\" #> #> $extend #> [1] \"pad\" #> #> $group #> [1] TRUE #> #> attr(,\"class\") #> [1] \"GridLinearGradient\" \"GridPattern\" #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":null,"dir":"Reference","previous_headings":"","what":"Find panels in a gtable — find_panel","title":"Find panels in a gtable — find_panel","text":"functions help detect placement panels gtable, named \"panel\" beginning. find_panel() returns extend panel area, panel_cols() panel_rows() returns columns rows contains panels respectively.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Find panels in a gtable — find_panel","text":"","code":"find_panel(table) panel_cols(table) panel_rows(table)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Find panels in a gtable — find_panel","text":"table gtable","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/find_panel.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Find panels in a gtable — find_panel","text":"data.frame columns t(op), r(ight), b(ottom), l(eft)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify methods for objects produced by multcomp — fortify-multcomp","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"Fortify methods objects produced multcomp","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"","code":"# S3 method for class 'glht' fortify(model, data, ...) # S3 method for class 'confint.glht' fortify(model, data, ...) # S3 method for class 'summary.glht' fortify(model, data, ...) # S3 method for class 'cld' fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"model object class glht, confint.glht, summary.glht multcomp::cld() data, ... arguments generic ignored method.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify-multcomp.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Fortify methods for objects produced by multcomp — fortify-multcomp","text":"","code":"if (require(\"multcomp\")) { amod <- aov(breaks ~ wool + tension, data = warpbreaks) wht <- glht(amod, linfct = mcp(tension = \"Tukey\")) fortify(wht) ggplot(wht, aes(lhs, estimate)) + geom_point() CI <- confint(wht) fortify(CI) ggplot(CI, aes(lhs, estimate, ymin = lwr, ymax = upr)) + geom_pointrange() fortify(summary(wht)) ggplot(mapping = aes(lhs, estimate)) + geom_linerange(aes(ymin = lwr, ymax = upr), data = CI) + geom_point(aes(size = p), data = summary(wht)) + scale_size(transform = \"reverse\") cld <- cld(wht) fortify(cld) } #> Loading required package: multcomp #> Loading required package: mvtnorm #> Loading required package: survival #> Loading required package: TH.data #> Loading required package: MASS #> #> Attaching package: ‘TH.data’ #> The following object is masked from ‘package:MASS’: #> #> geyser #> lhs letters #> L L a #> M M b #> H H b"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify a model with data. — fortify","title":"Fortify a model with data. — fortify","text":"Rather using function, now recommend using broom package, implements much wider range methods. fortify() may deprecated future.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify a model with data. — fortify","text":"","code":"fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify a model with data. — fortify","text":"model model R object convert data frame data original dataset, needed ... Arguments passed methods.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":null,"dir":"Reference","previous_headings":"","what":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"missing values model data, may need refit model na.action = na.exclude.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"","code":"# S3 method for class 'lm' fortify(model, data = model$model, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"model linear model data data set, defaults data used fit model ... used method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"original data extra columns: .hat Diagonal hat matrix .sigma Estimate residual standard deviation corresponding observation dropped model .cooksd Cooks distance, cooks.distance() .fitted Fitted values model .resid Residuals .stdresid Standardised residuals","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.lm.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Supplement the data fitted to a linear model with model fit statistics. — fortify.lm","text":"","code":"mod <- lm(mpg ~ wt, data = mtcars) head(fortify(mod)) #> mpg wt .hat .sigma .cooksd .fitted #> Mazda RX4 21.0 2.620 0.04326896 3.067494 1.327407e-02 23.28261 #> Mazda RX4 Wag 21.0 2.875 0.03519677 3.093068 1.723963e-03 21.91977 #> Datsun 710 22.8 2.320 0.05837573 3.072127 1.543937e-02 24.88595 #> Hornet 4 Drive 21.4 3.215 0.03125017 3.088268 3.020558e-03 20.10265 #> Hornet Sportabout 18.7 3.440 0.03292182 3.097722 7.599578e-05 18.90014 #> Valiant 18.1 3.460 0.03323551 3.095184 9.210650e-04 18.79325 #> .resid .stdresid #> Mazda RX4 -2.2826106 -0.76616765 #> Mazda RX4 Wag -0.9197704 -0.30743051 #> Datsun 710 -2.0859521 -0.70575249 #> Hornet 4 Drive 1.2973499 0.43275114 #> Hornet Sportabout -0.2001440 -0.06681879 #> Valiant -0.6932545 -0.23148309 head(fortify(mod, mtcars)) #> mpg cyl disp hp drat wt qsec vs am gear carb #> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 #> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 #> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 #> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 #> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 #> Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 #> .hat .sigma .cooksd .fitted .resid #> Mazda RX4 0.04326896 3.067494 1.327407e-02 23.28261 -2.2826106 #> Mazda RX4 Wag 0.03519677 3.093068 1.723963e-03 21.91977 -0.9197704 #> Datsun 710 0.05837573 3.072127 1.543937e-02 24.88595 -2.0859521 #> Hornet 4 Drive 0.03125017 3.088268 3.020558e-03 20.10265 1.2973499 #> Hornet Sportabout 0.03292182 3.097722 7.599578e-05 18.90014 -0.2001440 #> Valiant 0.03323551 3.095184 9.210650e-04 18.79325 -0.6932545 #> .stdresid #> Mazda RX4 -0.76616765 #> Mazda RX4 Wag -0.30743051 #> Datsun 710 -0.70575249 #> Hornet 4 Drive 0.43275114 #> Hornet Sportabout -0.06681879 #> Valiant -0.23148309 plot(mod, which = 1) ggplot(mod, aes(.fitted, .resid)) + geom_point() + geom_hline(yintercept = 0) + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(mod, aes(.fitted, .stdresid)) + geom_point() + geom_hline(yintercept = 0) + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(fortify(mod, mtcars), aes(.fitted, .stdresid)) + geom_point(aes(colour = factor(cyl))) ggplot(fortify(mod, mtcars), aes(mpg, .stdresid)) + geom_point(aes(colour = factor(cyl))) plot(mod, which = 2) ggplot(mod) + stat_qq(aes(sample = .stdresid)) + geom_abline() plot(mod, which = 3) ggplot(mod, aes(.fitted, sqrt(abs(.stdresid)))) + geom_point() + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' plot(mod, which = 4) ggplot(mod, aes(seq_along(.cooksd), .cooksd)) + geom_col() plot(mod, which = 5) ggplot(mod, aes(.hat, .stdresid)) + geom_vline(linewidth = 2, colour = \"white\", xintercept = 0) + geom_hline(linewidth = 2, colour = \"white\", yintercept = 0) + geom_point() + geom_smooth(se = FALSE) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(mod, aes(.hat, .stdresid)) + geom_point(aes(size = .cooksd)) + geom_smooth(se = FALSE, linewidth = 0.5) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' plot(mod, which = 6) ggplot(mod, aes(.hat, .cooksd)) + geom_vline(xintercept = 0, colour = NA) + geom_abline(slope = seq(0, 3, by = 0.5), colour = \"white\") + geom_smooth(se = FALSE) + geom_point() #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ggplot(mod, aes(.hat, .cooksd)) + geom_point(aes(size = .cooksd / .hat)) + scale_size_area()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify method for map objects — fortify.map","title":"Fortify method for map objects — fortify.map","text":"function turns map data frame can easily plotted ggplot2.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify method for map objects — fortify.map","text":"","code":"# S3 method for class 'map' fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify method for map objects — fortify.map","text":"model map object data used method ... used method","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Fortify method for map objects — fortify.map","text":"","code":"if (require(\"maps\")) { ca <- map(\"county\", \"ca\", plot = FALSE, fill = TRUE) head(fortify(ca)) ggplot(ca, aes(long, lat)) + geom_polygon(aes(group = group)) } if (require(\"maps\")) { tx <- map(\"county\", \"texas\", plot = FALSE, fill = TRUE) head(fortify(tx)) ggplot(tx, aes(long, lat)) + geom_polygon(aes(group = group), colour = \"white\") }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.sp.html","id":null,"dir":"Reference","previous_headings":"","what":"Fortify method for classes from the sp package. — fortify.sp","title":"Fortify method for classes from the sp package. — fortify.sp","text":"figure correct variable name region, inspect .data.frame(model).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.sp.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fortify method for classes from the sp package. — fortify.sp","text":"","code":"# S3 method for class 'SpatialPolygonsDataFrame' fortify(model, data, region = NULL, ...) # S3 method for class 'SpatialPolygons' fortify(model, data, ...) # S3 method for class 'Polygons' fortify(model, data, ...) # S3 method for class 'Polygon' fortify(model, data, ...) # S3 method for class 'SpatialLinesDataFrame' fortify(model, data, ...) # S3 method for class 'Lines' fortify(model, data, ...) # S3 method for class 'Line' fortify(model, data, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/fortify.sp.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Fortify method for classes from the sp package. — fortify.sp","text":"model SpatialPolygonsDataFrame convert dataframe. data used method region name variable used split regions ... used method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":null,"dir":"Reference","previous_headings":"","what":"Reference lines: horizontal, vertical, and diagonal — geom_abline","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"geoms add reference lines (sometimes called rules) plot, either horizontal, vertical, diagonal (specified slope intercept). useful annotating plots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"","code":"geom_abline( mapping = NULL, data = NULL, ..., slope, intercept, na.rm = FALSE, show.legend = NA ) geom_hline( mapping = NULL, data = NULL, position = \"identity\", ..., yintercept, na.rm = FALSE, show.legend = NA ) geom_vline( mapping = NULL, data = NULL, position = \"identity\", ..., xintercept, na.rm = FALSE, show.legend = NA )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"mapping Set aesthetic mappings created aes(). data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. xintercept, yintercept, slope, intercept Parameters control position line. set, data, mapping show.legend overridden.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"geoms act slightly differently geoms. can supply parameters two ways: either arguments layer function, via aesthetics. use arguments, e.g. geom_abline(intercept = 0, slope = 1), behind scenes geom makes new data frame containing just data supplied. means lines facets; want vary across facets, construct data frame use aesthetics. Unlike geoms, geoms inherit aesthetics plot default, understand x y aesthetics commonly set plot. also affect x y scales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"geoms drawn using geom_line() support aesthetics: alpha, colour, linetype linewidth. also aesthetics control position line: geom_vline(): xintercept geom_hline(): yintercept geom_abline(): slope intercept","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_abline.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Reference lines: horizontal, vertical, and diagonal — geom_abline","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() # Fixed values p + geom_vline(xintercept = 5) p + geom_vline(xintercept = 1:5) p + geom_hline(yintercept = 20) p + geom_abline() # Can't see it - outside the range of the data p + geom_abline(intercept = 20) # Calculate slope and intercept of line of best fit coef(lm(mpg ~ wt, data = mtcars)) #> (Intercept) wt #> 37.285126 -5.344472 p + geom_abline(intercept = 37, slope = -5) # But this is easier to do with geom_smooth: p + geom_smooth(method = \"lm\", se = FALSE) #> `geom_smooth()` using formula = 'y ~ x' # To show different lines in different facets, use aesthetics p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_wrap(~ cyl) mean_wt <- data.frame(cyl = c(4, 6, 8), wt = c(2.28, 3.11, 4.00)) p + geom_hline(aes(yintercept = wt), mean_wt) # You can also control other aesthetics ggplot(mtcars, aes(mpg, wt, colour = wt)) + geom_point() + geom_hline(aes(yintercept = wt, colour = wt), mean_wt) + facet_wrap(~ cyl)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":null,"dir":"Reference","previous_headings":"","what":"Bar charts — geom_bar","title":"Bar charts — geom_bar","text":"two types bar charts: geom_bar() geom_col(). geom_bar() makes height bar proportional number cases group (weight aesthetic supplied, sum weights). want heights bars represent values data, use geom_col() instead. geom_bar() uses stat_count() default: counts number cases x position. geom_col() uses stat_identity(): leaves data .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Bar charts — geom_bar","text":"","code":"geom_bar( mapping = NULL, data = NULL, stat = \"count\", position = \"stack\", ..., just = 0.5, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_col( mapping = NULL, data = NULL, position = \"stack\", ..., just = 0.5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_count( mapping = NULL, data = NULL, geom = \"bar\", position = \"stack\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Bar charts — geom_bar","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. just Adjustment column placement. Set 0.5 default, meaning columns centered axis breaks. Set 0 1 place columns left/right axis breaks. Note argument may unintended behaviour used alternative positions, e.g. position_dodge(). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Override default connection geom_bar() stat_count(). information overriding connections, see stat geom arguments work.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Bar charts — geom_bar","text":"bar chart uses height represent value, base bar must always shown produce valid visual comparison. Proceed caution using transformed scales bar chart. important always use meaningful reference point base bar. example, log transformations reference point 1. fact, using log scale, geom_bar() automatically places base bar 1. Furthermore, never use stacked bars transformed scale, scaling happens stacking. consequence, height bars wrong stacking occurs transformed scale. default, multiple bars occupying x position stacked atop one another position_stack(). want dodged side--side, use position_dodge() position_dodge2(). Finally, position_fill() shows relative proportions x stacking bars standardising bar height.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Bar charts — geom_bar","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Bar charts — geom_bar","text":"geom_bar() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth width Learn setting aesthetics vignette(\"ggplot2-specs\"). geom_col() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth width Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_count() understands following aesthetics (required aesthetics bold): x y group weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Bar charts — geom_bar","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(prop) groupwise proportion","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Bar charts — geom_bar","text":"","code":"# geom_bar is designed to make it easy to create bar charts that show # counts (or sums of weights) g <- ggplot(mpg, aes(class)) # Number of cars in each class: g + geom_bar() # Total engine displacement of each class g + geom_bar(aes(weight = displ)) # Map class to y instead to flip the orientation ggplot(mpg) + geom_bar(aes(y = class)) # Bar charts are automatically stacked when multiple bars are placed # at the same location. The order of the fill is designed to match # the legend g + geom_bar(aes(fill = drv)) # If you need to flip the order (because you've flipped the orientation) # call position_stack() explicitly: ggplot(mpg, aes(y = class)) + geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) + theme(legend.position = \"top\") # To show (e.g.) means, you need geom_col() df <- data.frame(trt = c(\"a\", \"b\", \"c\"), outcome = c(2.3, 1.9, 3.2)) ggplot(df, aes(trt, outcome)) + geom_col() # But geom_point() displays exactly the same information and doesn't # require the y-axis to touch zero. ggplot(df, aes(trt, outcome)) + geom_point() # You can also use geom_bar() with continuous data, in which case # it will show counts at unique locations df <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4))) ggplot(df, aes(x)) + geom_bar() # cf. a histogram of the same data ggplot(df, aes(x)) + geom_histogram(binwidth = 0.5) # Use `just` to control how columns are aligned with axis breaks: df <- data.frame(x = as.Date(c(\"2020-01-01\", \"2020-02-01\")), y = 1:2) # Columns centered on the first day of the month ggplot(df, aes(x, y)) + geom_col(just = 0.5) # Columns begin on the first day of the month ggplot(df, aes(x, y)) + geom_col(just = 1)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":null,"dir":"Reference","previous_headings":"","what":"Heatmap of 2d bin counts — geom_bin_2d","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"Divides plane rectangles, counts number cases rectangle, (default) maps number cases rectangle's fill. useful alternative geom_point() presence overplotting.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"","code":"geom_bin_2d( mapping = NULL, data = NULL, stat = \"bin2d\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_bin_2d( mapping = NULL, data = NULL, geom = \"tile\", position = \"identity\", ..., bins = 30, binwidth = NULL, drop = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_bin_2d() stat_bin_2d(). information overriding connections, see stat geom arguments work. bins numeric vector giving number bins vertical horizontal directions. Set 30 default. binwidth Numeric vector giving bin width vertical horizontal directions. Overrides bins set. drop TRUE removes cells 0 counts.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"stat_bin_2d() understands following aesthetics (required aesthetics bold): x y fill group weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(density) density points bin, scaled integrate 1. after_stat(ncount) count, scaled maximum 1. after_stat(ndensity) density, scaled maximum 1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_bin_2d.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Heatmap of 2d bin counts — geom_bin_2d","text":"","code":"d <- ggplot(diamonds, aes(x, y)) + xlim(4, 10) + ylim(4, 10) d + geom_bin_2d() #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 5 rows containing missing values or values outside the scale #> range (`geom_tile()`). # You can control the size of the bins by specifying the number of # bins in each direction: d + geom_bin_2d(bins = 10) #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 6 rows containing missing values or values outside the scale #> range (`geom_tile()`). d + geom_bin_2d(bins = 30) #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 5 rows containing missing values or values outside the scale #> range (`geom_tile()`). # Or by specifying the width of the bins d + geom_bin_2d(binwidth = c(0.1, 0.1)) #> Warning: Removed 478 rows containing non-finite outside the scale range #> (`stat_bin2d()`). #> Warning: Removed 5 rows containing missing values or values outside the scale #> range (`geom_tile()`)."},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":null,"dir":"Reference","previous_headings":"","what":"Draw nothing — geom_blank","title":"Draw nothing — geom_blank","text":"blank geom draws nothing, can useful way ensuring common scales different plots. See expand_limits() details.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Draw nothing — geom_blank","text":"","code":"geom_blank( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Draw nothing — geom_blank","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_blank.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Draw nothing — geom_blank","text":"","code":"ggplot(mtcars, aes(wt, mpg)) # Nothing to see here!"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":null,"dir":"Reference","previous_headings":"","what":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"boxplot compactly displays distribution continuous variable. visualises five summary statistics (median, two hinges two whiskers), \"outlying\" points individually.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"","code":"geom_boxplot( mapping = NULL, data = NULL, stat = \"boxplot\", position = \"dodge2\", ..., outliers = TRUE, outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, outlier.shape = NULL, outlier.size = NULL, outlier.stroke = 0.5, outlier.alpha = NULL, notch = FALSE, notchwidth = 0.5, staplewidth = 0, varwidth = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_boxplot( mapping = NULL, data = NULL, geom = \"boxplot\", position = \"dodge2\", ..., coef = 1.5, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. outliers Whether display (TRUE) discard (FALSE) outliers plot. Hiding discarding outliers can useful , example, raw data points need displayed top boxplot. discarding outliers, axis limits adapt box whiskers , full data range. outliers need hidden axes needs show full data range, please use outlier.shape = NA instead. outlier.colour, outlier.color, outlier.fill, outlier.shape, outlier.size, outlier.stroke, outlier.alpha Default aesthetics outliers. Set NULL inherit aesthetics used box. unlikely event specify US UK spellings colour, US spelling take precedence. notch FALSE (default) make standard box plot. TRUE, make notched box plot. Notches used compare groups; notches two boxes overlap, suggests medians significantly different. notchwidth notched box plot, width notch relative body (defaults notchwidth = 0.5). staplewidth relative width staples width box. Staples mark ends whiskers line. varwidth FALSE (default) make standard box plot. TRUE, boxes drawn widths proportional square-roots number observations groups (possibly weighted, using weight aesthetic). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_boxplot() stat_boxplot(). information overriding connections, see stat geom arguments work. coef Length whiskers multiple IQR. Defaults 1.5.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"summary-statistics","dir":"Reference","previous_headings":"","what":"Summary statistics","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"lower upper hinges correspond first third quartiles (25th 75th percentiles). differs slightly method used boxplot() function, may apparent small samples. See boxplot.stats() information hinge positions calculated boxplot(). upper whisker extends hinge largest value 1.5 * IQR hinge (IQR inter-quartile range, distance first third quartiles). lower whisker extends hinge smallest value 1.5 * IQR hinge. Data beyond end whiskers called \"outlying\" points plotted individually. notched box plot, notches extend 1.58 * IQR / sqrt(n). gives roughly 95% confidence interval comparing medians. See McGill et al. (1978) details.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"geom_boxplot() understands following aesthetics (required aesthetics bold): x y lower xlower upper xupper middle xmiddle ymin xmin ymax xmax alpha colour fill group linetype linewidth shape size weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"calculated 'stat' part layers can accessed delayed evaluation. stat_boxplot() provides following variables, depend orientation: after_stat(width) width boxplot. after_stat(ymin) after_stat(xmin) lower whisker = smallest observation greater equal lower hinger - 1.5 * IQR. after_stat(lower) after_stat(xlower) lower hinge, 25% quantile. after_stat(notchlower) lower edge notch = median - 1.58 * IQR / sqrt(n). after_stat(middle) after_stat(xmiddle) median, 50% quantile. after_stat(notchupper) upper edge notch = median + 1.58 * IQR / sqrt(n). after_stat(upper) after_stat(xupper) upper hinge, 75% quantile. after_stat(ymax) after_stat(xmax) upper whisker = largest observation less equal upper hinger + 1.5 * IQR.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"McGill, R., Tukey, J. W. Larsen, W. . (1978) Variations box plots. American Statistician 32, 12-16.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_boxplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A box and whiskers plot (in the style of Tukey) — geom_boxplot","text":"","code":"p <- ggplot(mpg, aes(class, hwy)) p + geom_boxplot() # Orientation follows the discrete axis ggplot(mpg, aes(hwy, class)) + geom_boxplot() p + geom_boxplot(notch = TRUE) #> Notch went outside hinges #> ℹ Do you want `notch = FALSE`? #> Notch went outside hinges #> ℹ Do you want `notch = FALSE`? p + geom_boxplot(varwidth = TRUE) p + geom_boxplot(fill = \"white\", colour = \"#3366FF\") # By default, outlier points match the colour of the box. Use # outlier.colour to override p + geom_boxplot(outlier.colour = \"red\", outlier.shape = 1) # Remove outliers when overlaying boxplot with original data points p + geom_boxplot(outlier.shape = NA) + geom_jitter(width = 0.2) # Boxplots are automatically dodged when any aesthetic is a factor p + geom_boxplot(aes(colour = drv)) # You can also use boxplots with continuous x, as long as you supply # a grouping variable. cut_width is particularly useful ggplot(diamonds, aes(carat, price)) + geom_boxplot() #> Warning: Continuous x aesthetic #> ℹ did you forget `aes(group = ...)`? ggplot(diamonds, aes(carat, price)) + geom_boxplot(aes(group = cut_width(carat, 0.25))) # Adjust the transparency of outliers using outlier.alpha ggplot(diamonds, aes(carat, price)) + geom_boxplot(aes(group = cut_width(carat, 0.25)), outlier.alpha = 0.1) # \\donttest{ # It's possible to draw a boxplot with your own computations if you # use stat = \"identity\": set.seed(1) y <- rnorm(100) df <- data.frame( x = 1, y0 = min(y), y25 = quantile(y, 0.25), y50 = median(y), y75 = quantile(y, 0.75), y100 = max(y) ) ggplot(df, aes(x)) + geom_boxplot( aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100), stat = \"identity\" ) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":null,"dir":"Reference","previous_headings":"","what":"2D contours of a 3D surface — geom_contour","title":"2D contours of a 3D surface — geom_contour","text":"ggplot2 can draw true 3D surfaces, can use geom_contour(), geom_contour_filled(), geom_tile() visualise 3D surfaces 2D. functions require regular data, x y coordinates form equally spaced grid, combination x y appears . Missing values z allowed, contouring work grid points four corners non-missing. irregular data, need first interpolate grid visualising, using interp::interp(), akima::bilinear(), similar.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"2D contours of a 3D surface — geom_contour","text":"","code":"geom_contour( mapping = NULL, data = NULL, stat = \"contour\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, lineend = \"butt\", linejoin = \"round\", linemitre = 10, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_contour_filled( mapping = NULL, data = NULL, stat = \"contour_filled\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_contour( mapping = NULL, data = NULL, geom = \"contour\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_contour_filled( mapping = NULL, data = NULL, geom = \"contour_filled\", position = \"identity\", ..., bins = NULL, binwidth = NULL, breaks = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"2D contours of a 3D surface — geom_contour","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. bins Number contour bins. Overridden breaks. binwidth width contour bins. Overridden bins. breaks One : Numeric vector set contour breaks function takes range data binwidth input returns breaks output. function can created formula (e.g. ~ fullseq(.x, .y)). Overrides binwidth bins. default, vector length ten pretty() breaks. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"2D contours of a 3D surface — geom_contour","text":"geom_contour() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\"). geom_contour_filled() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_contour() understands following aesthetics (required aesthetics bold): x y z group order Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_contour_filled() understands following aesthetics (required aesthetics bold): x y z fill group order Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"2D contours of a 3D surface — geom_contour","text":"calculated 'stat' part layers can accessed delayed evaluation. computed variables differ somewhat contour lines (computed stat_contour()) contour bands (filled contours, computed stat_contour_filled()). variables nlevel piece available , whereas level_low, level_high, level_mid available bands. variable level numeric factor depending whether lines bands calculated. after_stat(level) Height contour. contour lines, numeric vector represents bin boundaries. contour bands, ordered factor represents bin ranges. after_stat(level_low), after_stat(level_high), after_stat(level_mid) (contour bands ) Lower upper bin boundaries band, well mid point boundaries. after_stat(nlevel) Height contour, scaled maximum 1. after_stat(piece) Contour piece (integer).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"2D contours of a 3D surface — geom_contour","text":"z contouring, z values individual data points longer available.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_contour.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"2D contours of a 3D surface — geom_contour","text":"","code":"# Basic plot v <- ggplot(faithfuld, aes(waiting, eruptions, z = density)) v + geom_contour() # Or compute from raw data ggplot(faithful, aes(waiting, eruptions)) + geom_density_2d() # \\donttest{ # use geom_contour_filled() for filled contours v + geom_contour_filled() # Setting bins creates evenly spaced contours in the range of the data v + geom_contour(bins = 3) v + geom_contour(bins = 5) # Setting binwidth does the same thing, parameterised by the distance # between contours v + geom_contour(binwidth = 0.01) v + geom_contour(binwidth = 0.001) # Other parameters v + geom_contour(aes(colour = after_stat(level))) v + geom_contour(colour = \"red\") v + geom_raster(aes(fill = density)) + geom_contour(colour = \"white\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":null,"dir":"Reference","previous_headings":"","what":"Count overlapping points — geom_count","title":"Count overlapping points — geom_count","text":"variant geom_point() counts number observations location, maps count point area. useful discrete data overplotting.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Count overlapping points — geom_count","text":"","code":"geom_count( mapping = NULL, data = NULL, stat = \"sum\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_sum( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Count overlapping points — geom_count","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_count() stat_sum(). information overriding connections, see stat geom arguments work.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Count overlapping points — geom_count","text":"geom_point() understands following aesthetics (required aesthetics bold): x y alpha colour fill group shape size stroke Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Count overlapping points — geom_count","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(n) Number observations position. after_stat(prop) Percent points panel position.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_count.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Count overlapping points — geom_count","text":"","code":"ggplot(mpg, aes(cty, hwy)) + geom_point() ggplot(mpg, aes(cty, hwy)) + geom_count() # Best used in conjunction with scale_size_area which ensures that # counts of zero would be given size 0. Doesn't make much different # here because the smallest count is already close to 0. ggplot(mpg, aes(cty, hwy)) + geom_count() + scale_size_area() # Display proportions instead of counts ------------------------------------- # By default, all categorical variables in the plot form the groups. # Specifying geom_count without a group identifier leads to a plot which is # not useful: d <- ggplot(diamonds, aes(x = cut, y = clarity)) d + geom_count(aes(size = after_stat(prop))) # To correct this problem and achieve a more desirable plot, we need # to specify which group the proportion is to be calculated over. d + geom_count(aes(size = after_stat(prop), group = 1)) + scale_size_area(max_size = 10) # Or group by x/y variables to have rows/columns sum to 1. d + geom_count(aes(size = after_stat(prop), group = cut)) + scale_size_area(max_size = 10) d + geom_count(aes(size = after_stat(prop), group = clarity)) + scale_size_area(max_size = 10)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":null,"dir":"Reference","previous_headings":"","what":"Smoothed density estimates — geom_density","title":"Smoothed density estimates — geom_density","text":"Computes draws kernel density estimate, smoothed version histogram. useful alternative histogram continuous data comes underlying smooth distribution.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Smoothed density estimates — geom_density","text":"","code":"geom_density( mapping = NULL, data = NULL, stat = \"density\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, outline.type = \"upper\" ) stat_density( mapping = NULL, data = NULL, geom = \"area\", position = \"stack\", ..., bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512, trim = FALSE, na.rm = FALSE, bounds = c(-Inf, Inf), orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Smoothed density estimates — geom_density","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). outline.type Type outline area; \"\" draws upper lower lines, \"upper\"/\"lower\" draws respective lines . \"full\" draws closed polygon around area. geom, stat Use override default connection geom_density() stat_density(). information overriding connections, see stat geom arguments work. bw smoothing bandwidth used. numeric, standard deviation smoothing kernel. character, rule choose bandwidth, listed stats::bw.nrd(). Note automatic calculation bandwidth take weights account. adjust multiplicate bandwidth adjustment. makes possible adjust bandwidth still using bandwidth estimator. example, adjust = 1/2 means use half default bandwidth. kernel Kernel. See list available kernels density(). n number equally spaced points density estimated, power two, see density() details trim FALSE, default, density computed full range data. TRUE, density computed range group: typically means estimated x values line-, hence able stack density values. parameter matters displaying multiple densities one plot manually adjusting scale limits. bounds Known lower upper bounds estimated data. Default c(-Inf, Inf) means (finite) bounds. bound finite, boundary effect default density estimation corrected reflecting tails outside bounds around closest edge. Data points outside bounds removed warning.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Smoothed density estimates — geom_density","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Smoothed density estimates — geom_density","text":"geom_density() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Smoothed density estimates — geom_density","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(density) density estimate. after_stat(count) density * number points - useful stacked density plots. after_stat(wdensity) density * sum weights. absence weights, count. after_stat(scaled) density estimate, scaled maximum 1. after_stat(n) number points. after_stat(ndensity) alias scaled, mirror syntax stat_bin().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Smoothed density estimates — geom_density","text":"","code":"ggplot(diamonds, aes(carat)) + geom_density() # Map the values to y to flip the orientation ggplot(diamonds, aes(y = carat)) + geom_density() ggplot(diamonds, aes(carat)) + geom_density(adjust = 1/5) ggplot(diamonds, aes(carat)) + geom_density(adjust = 5) ggplot(diamonds, aes(depth, colour = cut)) + geom_density() + xlim(55, 70) #> Warning: Removed 45 rows containing non-finite outside the scale range #> (`stat_density()`). ggplot(diamonds, aes(depth, fill = cut, colour = cut)) + geom_density(alpha = 0.1) + xlim(55, 70) #> Warning: Removed 45 rows containing non-finite outside the scale range #> (`stat_density()`). # Use `bounds` to adjust computation for known data limits big_diamonds <- diamonds[diamonds$carat >= 1, ] ggplot(big_diamonds, aes(carat)) + geom_density(color = 'red') + geom_density(bounds = c(1, Inf), color = 'blue') # \\donttest{ # Stacked density plots: if you want to create a stacked density plot, you # probably want to 'count' (density * n) variable instead of the default # density # Loses marginal densities ggplot(diamonds, aes(carat, fill = cut)) + geom_density(position = \"stack\") # Preserves marginal densities ggplot(diamonds, aes(carat, after_stat(count), fill = cut)) + geom_density(position = \"stack\") # You can use position=\"fill\" to produce a conditional density estimate ggplot(diamonds, aes(carat, after_stat(count), fill = cut)) + geom_density(position = \"fill\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":null,"dir":"Reference","previous_headings":"","what":"Contours of a 2D density estimate — geom_density_2d","title":"Contours of a 2D density estimate — geom_density_2d","text":"Perform 2D kernel density estimation using MASS::kde2d() display results contours. can useful dealing overplotting. 2D version geom_density(). geom_density_2d() draws contour lines, geom_density_2d_filled() draws filled contour bands.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Contours of a 2D density estimate — geom_density_2d","text":"","code":"geom_density_2d( mapping = NULL, data = NULL, stat = \"density_2d\", position = \"identity\", ..., contour_var = \"density\", lineend = \"butt\", linejoin = \"round\", linemitre = 10, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_density_2d_filled( mapping = NULL, data = NULL, stat = \"density_2d_filled\", position = \"identity\", ..., contour_var = \"density\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_density_2d( mapping = NULL, data = NULL, geom = \"density_2d\", position = \"identity\", ..., contour = TRUE, contour_var = \"density\", n = 100, h = NULL, adjust = c(1, 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_density_2d_filled( mapping = NULL, data = NULL, geom = \"density_2d_filled\", position = \"identity\", ..., contour = TRUE, contour_var = \"density\", n = 100, h = NULL, adjust = c(1, 1), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Contours of a 2D density estimate — geom_density_2d","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... Arguments passed geom_contour binwidth width contour bins. Overridden bins. bins Number contour bins. Overridden breaks. breaks One : Numeric vector set contour breaks function takes range data binwidth input returns breaks output. function can created formula (e.g. ~ fullseq(.x, .y)). Overrides binwidth bins. default, vector length ten pretty() breaks. contour_var Character string identifying variable contour . Can one \"density\", \"ndensity\", \"count\". See section computed variables details. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_density_2d() stat_density_2d(). information overriding connections, see stat geom arguments work. contour TRUE, contour results 2d density estimation. n Number grid points direction. h Bandwidth (vector length two). NULL, estimated using MASS::bandwidth.nrd(). adjust multiplicative bandwidth adjustment used 'h' 'NULL'. makes possible adjust bandwidth still using bandwidth estimator. example, adjust = 1/2 means use half default bandwidth.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Contours of a 2D density estimate — geom_density_2d","text":"geom_density_2d() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\"). geom_density_2d_filled() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Contours of a 2D density estimate — geom_density_2d","text":"calculated 'stat' part layers can accessed delayed evaluation. stat_density_2d() stat_density_2d_filled() compute different variables depending whether contouring turned . contouring (contour = FALSE), stats behave , following variables provided: after_stat(density) density estimate. after_stat(ndensity) Density estimate, scaled maximum 1. after_stat(count) Density estimate * number observations group. after_stat(n) Number observations group. contouring (contour = TRUE), either stat_contour() stat_contour_filled() (contour lines contour bands, respectively) run density estimate obtained, computed variables determined stats. Contours calculated one three types density estimates obtained contouring, density, ndensity, count. used determined contour_var parameter.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Contours of a 2D density estimate — geom_density_2d","text":"z density estimation, z values individual data points longer available. contouring enabled, similarly density, ndensity, count longer available contouring pass.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_density_2d.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Contours of a 2D density estimate — geom_density_2d","text":"","code":"m <- ggplot(faithful, aes(x = eruptions, y = waiting)) + geom_point() + xlim(0.5, 6) + ylim(40, 110) # contour lines m + geom_density_2d() # \\donttest{ # contour bands m + geom_density_2d_filled(alpha = 0.5) # contour bands and contour lines m + geom_density_2d_filled(alpha = 0.5) + geom_density_2d(linewidth = 0.25, colour = \"black\") set.seed(4393) dsmall <- diamonds[sample(nrow(diamonds), 1000), ] d <- ggplot(dsmall, aes(x, y)) # If you map an aesthetic to a categorical variable, you will get a # set of contours for each value of that variable d + geom_density_2d(aes(colour = cut)) # If you draw filled contours across multiple facets, the same bins are # used across all facets d + geom_density_2d_filled() + facet_wrap(vars(cut)) # If you want to make sure the peak intensity is the same in each facet, # use `contour_var = \"ndensity\"`. d + geom_density_2d_filled(contour_var = \"ndensity\") + facet_wrap(vars(cut)) # If you want to scale intensity by the number of observations in each group, # use `contour_var = \"count\"`. d + geom_density_2d_filled(contour_var = \"count\") + facet_wrap(vars(cut)) # If we turn contouring off, we can use other geoms, such as tiles: d + stat_density_2d( geom = \"raster\", aes(fill = after_stat(density)), contour = FALSE ) + scale_fill_viridis_c() # Or points: d + stat_density_2d(geom = \"point\", aes(size = after_stat(density)), n = 20, contour = FALSE) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Dot plot — geom_dotplot","title":"Dot plot — geom_dotplot","text":"dot plot, width dot corresponds bin width (maximum width, depending binning algorithm), dots stacked, dot representing one observation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Dot plot — geom_dotplot","text":"","code":"geom_dotplot( mapping = NULL, data = NULL, position = \"identity\", ..., binwidth = NULL, binaxis = \"x\", method = \"dotdensity\", binpositions = \"bygroup\", stackdir = \"up\", stackratio = 1, dotsize = 1, stackgroups = FALSE, origin = NULL, right = TRUE, width = 0.9, drop = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Dot plot — geom_dotplot","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. binwidth method \"dotdensity\", specifies maximum bin width. method \"histodot\", specifies bin width. Defaults 1/30 range data binaxis axis bin along, \"x\" (default) \"y\" method \"dotdensity\" (default) dot-density binning, \"histodot\" fixed bin widths (like stat_bin) binpositions method \"dotdensity\", \"bygroup\" (default) determines positions bins group separately. \"\" determines positions bins data taken together; used aligning dot stacks across multiple groups. stackdir direction stack dots. \"\" (default), \"\", \"center\", \"centerwhole\" (centered, dots aligned) stackratio close stack dots. Default 1, dots just touch. Use smaller values closer, overlapping dots. dotsize diameter dots relative binwidth, default 1. stackgroups dots stacked across groups? effect position = \"stack\" , (geom odd properties). origin method \"histodot\", origin first bin right method \"histodot\", intervals closed right (, b], [, b) width binaxis \"y\", spacing dot stacks dodging. drop TRUE, remove bins zero counts na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Dot plot — geom_dotplot","text":"two basic approaches: dot-density histodot. dot-density binning, bin positions determined data binwidth, maximum width bin. See Wilkinson (1999) details dot-density binning algorithm. histodot binning, bins fixed positions fixed widths, much like histogram. binning along x axis stacking along y axis, numbers y axis meaningful, due technical limitations ggplot2. can hide y axis, one examples, manually scale match number dots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Dot plot — geom_dotplot","text":"geom_dotplot() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype stroke weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Dot plot — geom_dotplot","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x) center bin, binaxis \"x\". after_stat(y) center bin, binaxis \"x\". after_stat(binwidth) maximum width bin method \"dotdensity\"; width bin method \"histodot\". after_stat(count) number points bin. after_stat(ncount) count, scaled maximum 1. after_stat(density) density points bin, scaled integrate 1, method \"histodot\". after_stat(ndensity) density, scaled maximum 1, method \"histodot\".","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Dot plot — geom_dotplot","text":"Wilkinson, L. (1999) Dot plots. American Statistician, 53(3), 276-281.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_dotplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Dot plot — geom_dotplot","text":"","code":"ggplot(mtcars, aes(x = mpg)) + geom_dotplot() #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5) # Use fixed-width bins ggplot(mtcars, aes(x = mpg)) + geom_dotplot(method=\"histodot\", binwidth = 1.5) # Some other stacking methods ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, stackdir = \"center\") ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, stackdir = \"centerwhole\") # y axis isn't really meaningful, so hide it ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5) + scale_y_continuous(NULL, breaks = NULL) # Overlap dots vertically ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, stackratio = .7) # Expand dot diameter ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, dotsize = 1.25) # Change dot fill colour, stroke width ggplot(mtcars, aes(x = mpg)) + geom_dotplot(binwidth = 1.5, fill = \"white\", stroke = 2) # \\donttest{ # Examples with stacking along y axis instead of x ggplot(mtcars, aes(x = 1, y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"centerwhole\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. ggplot(mtcars, aes(x = factor(vs), fill = factor(cyl), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\", position = \"dodge\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. # binpositions=\"all\" ensures that the bins are aligned between groups ggplot(mtcars, aes(x = factor(am), y = mpg)) + geom_dotplot(binaxis = \"y\", stackdir = \"center\", binpositions=\"all\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. # Stacking multiple groups, with different fill ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + geom_dotplot(stackgroups = TRUE, binwidth = 1, binpositions = \"all\") ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + geom_dotplot(stackgroups = TRUE, binwidth = 1, method = \"histodot\") ggplot(mtcars, aes(x = 1, y = mpg, fill = factor(cyl))) + geom_dotplot(binaxis = \"y\", stackgroups = TRUE, binwidth = 1, method = \"histodot\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":null,"dir":"Reference","previous_headings":"","what":"Horizontal error bars — geom_errorbarh","title":"Horizontal error bars — geom_errorbarh","text":"rotated version geom_errorbar().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Horizontal error bars — geom_errorbarh","text":"","code":"geom_errorbarh( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Horizontal error bars — geom_errorbarh","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Horizontal error bars — geom_errorbarh","text":"geom_errorbarh() understands following aesthetics (required aesthetics bold): xmin xmax y alpha colour group height linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_errorbarh.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Horizontal error bars — geom_errorbarh","text":"","code":"df <- data.frame( trt = factor(c(1, 1, 2, 2)), resp = c(1, 5, 3, 4), group = factor(c(1, 2, 1, 2)), se = c(0.1, 0.3, 0.3, 0.2) ) # Define the top and bottom of the errorbars p <- ggplot(df, aes(resp, trt, colour = group)) p + geom_point() + geom_errorbarh(aes(xmax = resp + se, xmin = resp - se)) p + geom_point() + geom_errorbarh(aes(xmax = resp + se, xmin = resp - se, height = .2))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":null,"dir":"Reference","previous_headings":"","what":"Draw a function as a continuous curve — geom_function","title":"Draw a function as a continuous curve — geom_function","text":"Computes draws function continuous curve. makes easy superimpose function top existing plot. function called grid evenly spaced values along x axis, results drawn (default) line.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Draw a function as a continuous curve — geom_function","text":"","code":"geom_function( mapping = NULL, data = NULL, stat = \"function\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_function( mapping = NULL, data = NULL, geom = \"function\", position = \"identity\", ..., fun, xlim = NULL, n = 101, args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Draw a function as a continuous curve — geom_function","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data Ignored stat_function(), use. stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. fun Function use. Either 1) anonymous function base rlang formula syntax (see rlang::as_function()) 2) quoted character name referencing function; see examples. Must vectorised. xlim Optionally, specify range function. n Number points interpolate along x axis. args List additional arguments passed function defined fun.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Draw a function as a continuous curve — geom_function","text":"geom_function() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Draw a function as a continuous curve — geom_function","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x)x values along grid. after_stat(y) values function evaluated corresponding x.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_function.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Draw a function as a continuous curve — geom_function","text":"","code":"# geom_function() is useful for overlaying functions set.seed(1492) ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density() + geom_function(fun = dnorm, colour = \"red\") # To plot functions without data, specify range of x-axis base <- ggplot() + xlim(-5, 5) base + geom_function(fun = dnorm) base + geom_function(fun = dnorm, args = list(mean = 2, sd = .5)) # The underlying mechanics evaluate the function at discrete points # and connect the points with lines base + stat_function(fun = dnorm, geom = \"point\") base + stat_function(fun = dnorm, geom = \"point\", n = 20) base + stat_function(fun = dnorm, geom = \"polygon\", color = \"blue\", fill = \"blue\", alpha = 0.5) base + geom_function(fun = dnorm, n = 20) # Two functions on the same plot base + geom_function(aes(colour = \"normal\"), fun = dnorm) + geom_function(aes(colour = \"t, df = 1\"), fun = dt, args = list(df = 1)) # Using a custom anonymous function base + geom_function(fun = function(x) 0.5 * exp(-abs(x))) # or using lambda syntax: # base + geom_function(fun = ~ 0.5 * exp(-abs(.x))) # or in R4.1.0 and above: # base + geom_function(fun = \\(x) 0.5 * exp(-abs(x))) # or using a custom named function: # f <- function(x) 0.5 * exp(-abs(x)) # base + geom_function(fun = f) # Using xlim to restrict the range of function ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density() + geom_function(fun = dnorm, colour = \"red\", xlim=c(-1, 1)) # Using xlim to widen the range of function ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density() + geom_function(fun = dnorm, colour = \"red\", xlim=c(-7, 7))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":null,"dir":"Reference","previous_headings":"","what":"Hexagonal heatmap of 2d bin counts — geom_hex","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"Divides plane regular hexagons, counts number cases hexagon, (default) maps number cases hexagon fill. Hexagon bins avoid visual artefacts sometimes generated regular alignment geom_bin_2d().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"","code":"geom_hex( mapping = NULL, data = NULL, stat = \"binhex\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_bin_hex( mapping = NULL, data = NULL, geom = \"hex\", position = \"identity\", ..., bins = 30, binwidth = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Override default connection geom_hex() stat_bin_hex(). information overriding connections, see stat geom arguments work. bins numeric vector giving number bins vertical horizontal directions. Set 30 default. binwidth Numeric vector giving bin width vertical horizontal directions. Overrides bins set.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"geom_hex() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(density) density points bin, scaled integrate 1. after_stat(ncount) count, scaled maximum 1. after_stat(ndensity) density, scaled maximum 1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_hex.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Hexagonal heatmap of 2d bin counts — geom_hex","text":"","code":"d <- ggplot(diamonds, aes(carat, price)) d + geom_hex() # \\donttest{ # You can control the size of the bins by specifying the number of # bins in each direction: d + geom_hex(bins = 10) d + geom_hex(bins = 30) # Or by specifying the width of the bins d + geom_hex(binwidth = c(1, 1000)) d + geom_hex(binwidth = c(.1, 500)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":null,"dir":"Reference","previous_headings":"","what":"Histograms and frequency polygons — geom_freqpoly","title":"Histograms and frequency polygons — geom_freqpoly","text":"Visualise distribution single continuous variable dividing x axis bins counting number observations bin. Histograms (geom_histogram()) display counts bars; frequency polygons (geom_freqpoly()) display counts lines. Frequency polygons suitable want compare distribution across levels categorical variable.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Histograms and frequency polygons — geom_freqpoly","text":"","code":"geom_freqpoly( mapping = NULL, data = NULL, stat = \"bin\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_histogram( mapping = NULL, data = NULL, stat = \"bin\", position = \"stack\", ..., binwidth = NULL, bins = NULL, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_bin( mapping = NULL, data = NULL, geom = \"bar\", position = \"stack\", ..., binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, breaks = NULL, closed = c(\"right\", \"left\"), pad = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Histograms and frequency polygons — geom_freqpoly","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). binwidth width bins. Can specified numeric value function takes x scale transformation input returns single numeric value. specifying function along grouping structure, function called per group. default use number bins bins, covering range data. always override value, exploring multiple widths find best illustrate stories data. bin width date variable number days time; bin width time variable number seconds. bins Number bins. Overridden binwidth. Defaults 30. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. geom, stat Use override default connection geom_histogram()/geom_freqpoly() stat_bin(). information overriding connections, see stat geom arguments work. center, boundary bin position specifiers. one, center boundary, may specified single plot. center specifies center one bins. boundary specifies boundary two bins. Note either range data, things shifted appropriate integer multiple binwidth. example, center integers use binwidth = 1 center = 0, even 0 outside range data. Alternatively, alignment can specified binwidth = 1 boundary = 0.5, even 0.5 outside range data. breaks Alternatively, can supply numeric vector giving bin boundaries. Overrides binwidth, bins, center, boundary. Can also function takes group-wise values input returns bin boundaries. closed One \"right\" \"left\" indicating whether right left edges bins included bin. pad TRUE, adds empty bins either end x. ensures frequency polygons touch 0. Defaults FALSE.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Histograms and frequency polygons — geom_freqpoly","text":"stat_bin() suitable continuous x data. x data discrete, probably want use stat_count(). default, underlying computation (stat_bin()) uses 30 bins; good default, idea get experimenting different number bins. can also experiment modifying binwidth center boundary arguments. binwidth overrides bins one change time. may need look options uncover full story behind data. addition geom_histogram(), can create histogram plot using scale_x_binned() geom_bar(). method default plots tick marks bar.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Histograms and frequency polygons — geom_freqpoly","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Histograms and frequency polygons — geom_freqpoly","text":"geom_histogram() uses aesthetics geom_bar(); geom_freqpoly() uses aesthetics geom_line().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Histograms and frequency polygons — geom_freqpoly","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(count) number points bin. after_stat(density) density points bin, scaled integrate 1. after_stat(ncount) count, scaled maximum 1. after_stat(ndensity) density, scaled maximum 1. after_stat(width) widths bins.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Histograms and frequency polygons — geom_freqpoly","text":"weight binning, weights individual data points (supplied) longer available.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_histogram.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Histograms and frequency polygons — geom_freqpoly","text":"","code":"ggplot(diamonds, aes(carat)) + geom_histogram() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. ggplot(diamonds, aes(carat)) + geom_histogram(binwidth = 0.01) ggplot(diamonds, aes(carat)) + geom_histogram(bins = 200) # Map values to y to flip the orientation ggplot(diamonds, aes(y = carat)) + geom_histogram() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # For histograms with tick marks between each bin, use `geom_bar()` with # `scale_x_binned()`. ggplot(diamonds, aes(carat)) + geom_bar() + scale_x_binned() # Rather than stacking histograms, it's easier to compare frequency # polygons ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500) ggplot(diamonds, aes(price, colour = cut)) + geom_freqpoly(binwidth = 500) # To make it easier to compare distributions with very different counts, # put density on the y axis instead of the default count ggplot(diamonds, aes(price, after_stat(density), colour = cut)) + geom_freqpoly(binwidth = 500) if (require(\"ggplot2movies\")) { # Often we don't want the height of the bar to represent the # count of observations, but the sum of some other variable. # For example, the following plot shows the number of movies # in each rating. m <- ggplot(movies, aes(rating)) m + geom_histogram(binwidth = 0.1) # If, however, we want to see the number of votes cast in each # category, we need to weight by the votes variable m + geom_histogram(aes(weight = votes), binwidth = 0.1) + ylab(\"votes\") # For transformed scales, binwidth applies to the transformed data. # The bins have constant width on the transformed scale. m + geom_histogram() + scale_x_log10() m + geom_histogram(binwidth = 0.05) + scale_x_log10() # For transformed coordinate systems, the binwidth applies to the # raw data. The bins have constant width on the original scale. # Using log scales does not work here, because the first # bar is anchored at zero, and so when transformed becomes negative # infinity. This is not a problem when transforming the scales, because # no observations have 0 ratings. m + geom_histogram(boundary = 0) + coord_trans(x = \"log10\") # Use boundary = 0, to make sure we don't take sqrt of negative values m + geom_histogram(boundary = 0) + coord_trans(x = \"sqrt\") # You can also transform the y axis. Remember that the base of the bars # has value 0, so log transformations are not appropriate m <- ggplot(movies, aes(x = rating)) m + geom_histogram(binwidth = 0.5) + scale_y_sqrt() } # You can specify a function for calculating binwidth, which is # particularly useful when faceting along variables with # different ranges because the function will be called once per facet ggplot(economics_long, aes(value)) + facet_wrap(~variable, scales = 'free_x') + geom_histogram(binwidth = function(x) 2 * IQR(x) / (length(x)^(1/3)))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":null,"dir":"Reference","previous_headings":"","what":"Jittered points — geom_jitter","title":"Jittered points — geom_jitter","text":"jitter geom convenient shortcut geom_point(position = \"jitter\"). adds small amount random variation location point, useful way handling overplotting caused discreteness smaller datasets.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Jittered points — geom_jitter","text":"","code":"geom_jitter( mapping = NULL, data = NULL, stat = \"identity\", position = \"jitter\", ..., width = NULL, height = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Jittered points — geom_jitter","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. width, height Amount vertical horizontal jitter. jitter added positive negative directions, total spread twice value specified . omitted, defaults 40% resolution data: means jitter values occupy 80% implied bins. Categorical data aligned integers, width height 0.5 spread data possible see distinction categories. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Jittered points — geom_jitter","text":"geom_point() understands following aesthetics (required aesthetics bold): x y alpha colour fill group shape size stroke Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_jitter.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Jittered points — geom_jitter","text":"","code":"p <- ggplot(mpg, aes(cyl, hwy)) p + geom_point() p + geom_jitter() # Add aesthetic mappings p + geom_jitter(aes(colour = class)) # Use smaller width/height to emphasise categories ggplot(mpg, aes(cyl, hwy)) + geom_jitter() ggplot(mpg, aes(cyl, hwy)) + geom_jitter(width = 0.25) # Use larger width/height to completely smooth away discreteness ggplot(mpg, aes(cty, hwy)) + geom_jitter() ggplot(mpg, aes(cty, hwy)) + geom_jitter(width = 0.5, height = 0.5)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":null,"dir":"Reference","previous_headings":"","what":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"Various ways representing vertical interval defined x, ymin ymax. case draws single graphical object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"","code":"geom_crossbar( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., fatten = 2.5, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_errorbar( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_linerange( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) geom_pointrange( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., fatten = 4, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. fatten multiplicative factor used increase size middle bar geom_crossbar() middle point geom_pointrange(). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"geom_linerange() understands following aesthetics (required aesthetics bold): x y ymin xmin ymax xmax alpha colour group linetype linewidth Note geom_pointrange() also understands size size points. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_linerange.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Vertical intervals: lines, crossbars & errorbars — geom_crossbar","text":"","code":"# Create a simple example dataset df <- data.frame( trt = factor(c(1, 1, 2, 2)), resp = c(1, 5, 3, 4), group = factor(c(1, 2, 1, 2)), upper = c(1.1, 5.3, 3.3, 4.2), lower = c(0.8, 4.6, 2.4, 3.6) ) p <- ggplot(df, aes(trt, resp, colour = group)) p + geom_linerange(aes(ymin = lower, ymax = upper)) p + geom_pointrange(aes(ymin = lower, ymax = upper)) p + geom_crossbar(aes(ymin = lower, ymax = upper), width = 0.2) p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) # Flip the orientation by changing mapping ggplot(df, aes(resp, trt, colour = group)) + geom_linerange(aes(xmin = lower, xmax = upper)) # Draw lines connecting group means p + geom_line(aes(group = group)) + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) # If you want to dodge bars and errorbars, you need to manually # specify the dodge width p <- ggplot(df, aes(trt, resp, fill = group)) p + geom_col(position = \"dodge\") + geom_errorbar(aes(ymin = lower, ymax = upper), position = \"dodge\", width = 0.25) # Because the bars and errorbars have different widths # we need to specify how wide the objects we are dodging are dodge <- position_dodge(width=0.9) p + geom_col(position = dodge) + geom_errorbar(aes(ymin = lower, ymax = upper), position = dodge, width = 0.25) # When using geom_errorbar() with position_dodge2(), extra padding will be # needed between the error bars to keep them aligned with the bars. p + geom_col(position = \"dodge2\") + geom_errorbar( aes(ymin = lower, ymax = upper), position = position_dodge2(width = 0.5, padding = 0.5) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":null,"dir":"Reference","previous_headings":"","what":"Polygons from a reference map — geom_map","title":"Polygons from a reference map — geom_map","text":"Display polygons map. meant annotation, affect position scales. Note function predates geom_sf() framework work sf geometry columns input. However, can used conjunction geom_sf() layers /coord_sf() (see examples).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Polygons from a reference map — geom_map","text":"","code":"geom_map( mapping = NULL, data = NULL, stat = \"identity\", ..., map, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Polygons from a reference map — geom_map","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. map Data frame contains map coordinates. typically created using fortify() spatial object. must contain columns x long, y lat, region id. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Polygons from a reference map — geom_map","text":"geom_map() understands following aesthetics (required aesthetics bold): map_id alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_map.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Polygons from a reference map — geom_map","text":"","code":"# First, a made-up example containing a few polygons, to explain # how `geom_map()` works. It requires two data frames: # One contains the coordinates of each polygon (`positions`), and is # provided via the `map` argument. The other contains the # other the values associated with each polygon (`values`). An id # variable links the two together. ids <- factor(c(\"1.1\", \"2.1\", \"1.2\", \"2.2\", \"1.3\", \"2.3\")) values <- data.frame( id = ids, value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5) ) positions <- data.frame( id = rep(ids, each = 4), x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3), y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2) ) ggplot(values) + geom_map(aes(map_id = id), map = positions) + expand_limits(positions) ggplot(values, aes(fill = value)) + geom_map(aes(map_id = id), map = positions) + expand_limits(positions) ggplot(values, aes(fill = value)) + geom_map(aes(map_id = id), map = positions) + expand_limits(positions) + ylim(0, 3) # Now some examples with real maps if (require(maps)) { crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests) # Equivalent to crimes %>% tidyr::pivot_longer(Murder:Rape) vars <- lapply(names(crimes)[-1], function(j) { data.frame(state = crimes$state, variable = j, value = crimes[[j]]) }) crimes_long <- do.call(\"rbind\", vars) states_map <- map_data(\"state\") # without geospatial coordinate system, the resulting plot # looks weird ggplot(crimes, aes(map_id = state)) + geom_map(aes(fill = Murder), map = states_map) + expand_limits(x = states_map$long, y = states_map$lat) # in combination with `coord_sf()` we get an appropriate result ggplot(crimes, aes(map_id = state)) + geom_map(aes(fill = Murder), map = states_map) + # crs = 5070 is a Conus Albers projection for North America, # see: https://epsg.io/5070 # default_crs = 4326 tells coord_sf() that the input map data # are in longitude-latitude format coord_sf( crs = 5070, default_crs = 4326, xlim = c(-125, -70), ylim = c(25, 52) ) ggplot(crimes_long, aes(map_id = state)) + geom_map(aes(fill = value), map = states_map) + coord_sf( crs = 5070, default_crs = 4326, xlim = c(-125, -70), ylim = c(25, 52) ) + facet_wrap(~variable) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":null,"dir":"Reference","previous_headings":"","what":"Connect observations — geom_path","title":"Connect observations — geom_path","text":"geom_path() connects observations order appear data. geom_line() connects order variable x axis. geom_step() creates stairstep plot, highlighting exactly changes occur. group aesthetic determines cases connected together.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Connect observations — geom_path","text":"","code":"geom_path( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., lineend = \"butt\", linejoin = \"round\", linemitre = 10, arrow = NULL, arrow.fill = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_line( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, ... ) geom_step( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", direction = \"hv\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Connect observations — geom_path","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). arrow Arrow specification, created grid::arrow(). arrow.fill fill colour use arrow head (closed). NULL means use colour aesthetic. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. direction direction stairs: 'vh' vertical horizontal, 'hv' horizontal vertical, 'mid' step half-way adjacent x-values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Connect observations — geom_path","text":"alternative parameterisation geom_segment(), line corresponds single case provides start end coordinates.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Connect observations — geom_path","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Connect observations — geom_path","text":"geom_path() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"missing-value-handling","dir":"Reference","previous_headings":"","what":"Missing value handling","title":"Connect observations — geom_path","text":"geom_path(), geom_line(), geom_step() handle NA follows: NA occurs middle line, breaks line. warning shown, regardless whether na.rm TRUE FALSE. NA occurs start end line na.rm FALSE (default), NA removed warning. NA occurs start end line na.rm TRUE, NA removed silently, without warning.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_path.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Connect observations — geom_path","text":"","code":"# geom_line() is suitable for time series ggplot(economics, aes(date, unemploy)) + geom_line() # separate by colour and use \"timeseries\" legend key glyph ggplot(economics_long, aes(date, value01, colour = variable)) + geom_line(key_glyph = \"timeseries\") # You can get a timeseries that run vertically by setting the orientation ggplot(economics, aes(unemploy, date)) + geom_line(orientation = \"y\") # geom_step() is useful when you want to highlight exactly when # the y value changes recent <- economics[economics$date > as.Date(\"2013-01-01\"), ] ggplot(recent, aes(date, unemploy)) + geom_line() ggplot(recent, aes(date, unemploy)) + geom_step() # geom_path lets you explore how two variables are related over time, # e.g. unemployment and personal savings rate m <- ggplot(economics, aes(unemploy/pop, psavert)) m + geom_path() m + geom_path(aes(colour = as.numeric(date))) # Changing parameters ---------------------------------------------- ggplot(economics, aes(date, unemploy)) + geom_line(colour = \"red\") # Use the arrow parameter to add an arrow to the line # See ?arrow for more details c <- ggplot(economics, aes(x = date, y = pop)) c + geom_line(arrow = arrow()) c + geom_line( arrow = arrow(angle = 15, ends = \"both\", type = \"closed\") ) # Control line join parameters df <- data.frame(x = 1:3, y = c(4, 1, 9)) base <- ggplot(df, aes(x, y)) base + geom_path(linewidth = 10) base + geom_path(linewidth = 10, lineend = \"round\") base + geom_path(linewidth = 10, linejoin = \"mitre\", lineend = \"butt\") # You can use NAs to break the line. df <- data.frame(x = 1:5, y = c(1, 2, NA, 4, 5)) ggplot(df, aes(x, y)) + geom_point() + geom_line() #> Warning: Removed 1 row containing missing values or values outside the scale range #> (`geom_point()`). # \\donttest{ # Setting line type vs colour/size # Line type needs to be applied to a line as a whole, so it can # not be used with colour or size that vary across a line x <- seq(0.01, .99, length.out = 100) df <- data.frame( x = rep(x, 2), y = c(qlogis(x), 2 * qlogis(x)), group = rep(c(\"a\",\"b\"), each = 100) ) p <- ggplot(df, aes(x=x, y=y, group=group)) # These work p + geom_line(linetype = 2) p + geom_line(aes(colour = group), linetype = 2) p + geom_line(aes(colour = x)) # But this doesn't should_stop(p + geom_line(aes(colour = x), linetype=2)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":null,"dir":"Reference","previous_headings":"","what":"Points — geom_point","title":"Points — geom_point","text":"point geom used create scatterplots. scatterplot useful displaying relationship two continuous variables. can used compare one continuous one categorical variable, two categorical variables, variation like geom_jitter(), geom_count(), geom_bin_2d() usually appropriate. bubblechart scatterplot third variable mapped size points.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Points — geom_point","text":"","code":"geom_point( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Points — geom_point","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"overplotting","dir":"Reference","previous_headings":"","what":"Overplotting","title":"Points — geom_point","text":"biggest potential problem scatterplot overplotting: whenever points, points may plotted top one another. can severely distort visual appearance plot. one solution problem, techniques can help. can add additional information geom_smooth(), geom_quantile() geom_density_2d(). unique x values, geom_boxplot() may also useful. Alternatively, can summarise number points location display way, using geom_count(), geom_hex(), geom_density2d(). Another technique make points transparent (e.g. geom_point(alpha = 0.05)) small (e.g. geom_point(shape = \".\")).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Points — geom_point","text":"geom_point() understands following aesthetics (required aesthetics bold): x y alpha colour fill group shape size stroke fill aesthetic applies shapes 21-25. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_point.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Points — geom_point","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point() # Add aesthetic mappings p + geom_point(aes(colour = factor(cyl))) p + geom_point(aes(shape = factor(cyl))) # A \"bubblechart\": p + geom_point(aes(size = qsec)) # Set aesthetics to fixed value ggplot(mtcars, aes(wt, mpg)) + geom_point(colour = \"red\", size = 3) # \\donttest{ # Varying alpha is useful for large datasets d <- ggplot(diamonds, aes(carat, price)) d + geom_point(alpha = 1/10) d + geom_point(alpha = 1/20) d + geom_point(alpha = 1/100) # } # For shapes that have a border (like 21), you can colour the inside and # outside separately. Use the stroke aesthetic to modify the width of the # border ggplot(mtcars, aes(wt, mpg)) + geom_point(shape = 21, colour = \"black\", fill = \"white\", size = 5, stroke = 5) # \\donttest{ # You can create interesting shapes by layering multiple points of # different sizes p <- ggplot(mtcars, aes(mpg, wt, shape = factor(cyl))) p + geom_point(aes(colour = factor(cyl)), size = 4) + geom_point(colour = \"grey90\", size = 1.5) p + geom_point(colour = \"black\", size = 4.5) + geom_point(colour = \"pink\", size = 4) + geom_point(aes(shape = factor(cyl))) # geom_point warns when missing values have been dropped from the data set # and not plotted, you can turn this off by setting na.rm = TRUE set.seed(1) mtcars2 <- transform(mtcars, mpg = ifelse(runif(32) < 0.2, NA, mpg)) ggplot(mtcars2, aes(wt, mpg)) + geom_point() #> Warning: Removed 4 rows containing missing values or values outside the scale #> range (`geom_point()`). ggplot(mtcars2, aes(wt, mpg)) + geom_point(na.rm = TRUE) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":null,"dir":"Reference","previous_headings":"","what":"Polygons — geom_polygon","title":"Polygons — geom_polygon","text":"Polygons similar paths (drawn geom_path()) except start end points connected inside coloured fill. group aesthetic determines cases connected together polygon. R 3.6 onwards possible draw polygons holes providing subgroup aesthetic differentiates outer ring points describing holes polygon.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Polygons — geom_polygon","text":"","code":"geom_polygon( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", rule = \"evenodd\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Polygons — geom_polygon","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. rule Either \"evenodd\" \"winding\". polygons holes drawn (using subgroup aesthetic) argument defines hole coordinates interpreted. See examples grid::pathGrob() explanation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Polygons — geom_polygon","text":"geom_polygon() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth subgroup Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_polygon.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Polygons — geom_polygon","text":"","code":"# When using geom_polygon, you will typically need two data frames: # one contains the coordinates of each polygon (positions), and the # other the values associated with each polygon (values). An id # variable links the two together ids <- factor(c(\"1.1\", \"2.1\", \"1.2\", \"2.2\", \"1.3\", \"2.3\")) values <- data.frame( id = ids, value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5) ) positions <- data.frame( id = rep(ids, each = 4), x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3), y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2) ) # Currently we need to manually merge the two together datapoly <- merge(values, positions, by = c(\"id\")) p <- ggplot(datapoly, aes(x = x, y = y)) + geom_polygon(aes(fill = value, group = id)) p # Which seems like a lot of work, but then it's easy to add on # other features in this coordinate system, e.g.: set.seed(1) stream <- data.frame( x = cumsum(runif(50, max = 0.1)), y = cumsum(runif(50,max = 0.1)) ) p + geom_line(data = stream, colour = \"grey30\", linewidth = 5) # And if the positions are in longitude and latitude, you can use # coord_map to produce different map projections. if (packageVersion(\"grid\") >= \"3.6\") { # As of R version 3.6 geom_polygon() supports polygons with holes # Use the subgroup aesthetic to differentiate holes from the main polygon holes <- do.call(rbind, lapply(split(datapoly, datapoly$id), function(df) { df$x <- df$x + 0.5 * (mean(df$x) - df$x) df$y <- df$y + 0.5 * (mean(df$y) - df$y) df })) datapoly$subid <- 1L holes$subid <- 2L datapoly <- rbind(datapoly, holes) p <- ggplot(datapoly, aes(x = x, y = y)) + geom_polygon(aes(fill = value, group = id, subgroup = subid)) p }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":null,"dir":"Reference","previous_headings":"","what":"A quantile-quantile plot — geom_qq_line","title":"A quantile-quantile plot — geom_qq_line","text":"geom_qq() stat_qq() produce quantile-quantile plots. geom_qq_line() stat_qq_line() compute slope intercept line connecting points specified quartiles theoretical sample distributions.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A quantile-quantile plot — geom_qq_line","text":"","code":"geom_qq_line( mapping = NULL, data = NULL, geom = \"path\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), line.p = c(0.25, 0.75), fullrange = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_qq_line( mapping = NULL, data = NULL, geom = \"path\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), line.p = c(0.25, 0.75), fullrange = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_qq( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_qq( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., distribution = stats::qnorm, dparams = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A quantile-quantile plot — geom_qq_line","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. distribution Distribution function use, x specified dparams Additional parameters passed distribution function. line.p Vector quantiles use fitting Q-Q line, defaults defaults c(.25, .75). fullrange q-q line span full range plot, just data na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"A quantile-quantile plot — geom_qq_line","text":"stat_qq() understands following aesthetics (required aesthetics bold): sample group x y Learn setting aesthetics vignette(\"ggplot2-specs\"). stat_qq_line() understands following aesthetics (required aesthetics bold): sample group x y Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"A quantile-quantile plot — geom_qq_line","text":"calculated 'stat' part layers can accessed delayed evaluation. Variables computed stat_qq(): after_stat(sample) Sample quantiles. after_stat(theoretical) Theoretical quantiles. Variables computed stat_qq_line(): after_stat(x) x-coordinates endpoints line segment connecting points chosen quantiles theoretical sample distributions. after_stat(y) y-coordinates endpoints.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_qq.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A quantile-quantile plot — geom_qq_line","text":"","code":"# \\donttest{ df <- data.frame(y = rt(200, df = 5)) p <- ggplot(df, aes(sample = y)) p + stat_qq() + stat_qq_line() # Use fitdistr from MASS to estimate distribution params params <- as.list(MASS::fitdistr(df$y, \"t\")$estimate) #> Warning: NaNs produced #> Warning: NaNs produced #> Warning: NaNs produced ggplot(df, aes(sample = y)) + stat_qq(distribution = qt, dparams = params[\"df\"]) + stat_qq_line(distribution = qt, dparams = params[\"df\"]) # Using to explore the distribution of a variable ggplot(mtcars, aes(sample = mpg)) + stat_qq() + stat_qq_line() ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) + stat_qq() + stat_qq_line() # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":null,"dir":"Reference","previous_headings":"","what":"Quantile regression — geom_quantile","title":"Quantile regression — geom_quantile","text":"fits quantile regression data draws fitted quantiles lines. continuous analogue geom_boxplot().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Quantile regression — geom_quantile","text":"","code":"geom_quantile( mapping = NULL, data = NULL, stat = \"quantile\", position = \"identity\", ..., lineend = \"butt\", linejoin = \"round\", linemitre = 10, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_quantile( mapping = NULL, data = NULL, geom = \"quantile\", position = \"identity\", ..., quantiles = c(0.25, 0.5, 0.75), formula = NULL, method = \"rq\", method.args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Quantile regression — geom_quantile","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). linemitre Line mitre limit (number greater 1). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_quantile() stat_quantile(). information overriding connections, see stat geom arguments work. quantiles conditional quantiles y calculate display formula formula relating y variables x variables method Quantile regression method use. Available options \"rq\" (quantreg::rq()) \"rqss\" (quantreg::rqss()). method.args List additional arguments passed modelling function defined method.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Quantile regression — geom_quantile","text":"geom_quantile() understands following aesthetics (required aesthetics bold): x y alpha colour group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Quantile regression — geom_quantile","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(quantile) Quantile distribution.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_quantile.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Quantile regression — geom_quantile","text":"","code":"m <- ggplot(mpg, aes(displ, 1 / hwy)) + geom_point() m + geom_quantile() #> Smoothing formula not specified. Using: y ~ x m + geom_quantile(quantiles = 0.5) #> Smoothing formula not specified. Using: y ~ x q10 <- seq(0.05, 0.95, by = 0.05) m + geom_quantile(quantiles = q10) #> Smoothing formula not specified. Using: y ~ x # You can also use rqss to fit smooth quantiles m + geom_quantile(method = \"rqss\") #> Smoothing formula not specified. Using: y ~ qss(x, lambda = 1) # Note that rqss doesn't pick a smoothing constant automatically, so # you'll need to tweak lambda yourself m + geom_quantile(method = \"rqss\", lambda = 0.1) #> Smoothing formula not specified. Using: y ~ qss(x, lambda = 0.1) # Set aesthetics to fixed value m + geom_quantile(colour = \"red\", linewidth = 2, alpha = 0.5) #> Smoothing formula not specified. Using: y ~ x"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":null,"dir":"Reference","previous_headings":"","what":"Ribbons and area plots — geom_ribbon","title":"Ribbons and area plots — geom_ribbon","text":"x value, geom_ribbon() displays y interval defined ymin ymax. geom_area() special case geom_ribbon(), ymin fixed 0 y used instead ymax.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Ribbons and area plots — geom_ribbon","text":"","code":"geom_ribbon( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, outline.type = \"both\" ) geom_area( mapping = NULL, data = NULL, stat = \"align\", position = \"stack\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, ..., outline.type = \"upper\" ) stat_align( mapping = NULL, data = NULL, geom = \"area\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Ribbons and area plots — geom_ribbon","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). outline.type Type outline area; \"\" draws upper lower lines, \"upper\"/\"lower\" draws respective lines . \"full\" draws closed polygon around area. geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Ribbons and area plots — geom_ribbon","text":"area plot continuous analogue stacked bar chart (see geom_bar()), can used show composition whole varies range x. Choosing order different components stacked important, becomes increasing hard see individual pattern move stack. See position_stack() details stacking algorithm. facilitate stacking, default stat = \"align\" interpolates groups common set x-coordinates. turn interpolation, stat = \"identity\" can used instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Ribbons and area plots — geom_ribbon","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Ribbons and area plots — geom_ribbon","text":"geom_ribbon() understands following aesthetics (required aesthetics bold): x y ymin xmin ymax xmax alpha colour fill group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_ribbon.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Ribbons and area plots — geom_ribbon","text":"","code":"# Generate data huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron)) h <- ggplot(huron, aes(year)) h + geom_ribbon(aes(ymin=0, ymax=level)) h + geom_area(aes(y = level)) # Orientation cannot be deduced by mapping, so must be given explicitly for # flipped orientation h + geom_area(aes(x = level, y = year), orientation = \"y\") # Add aesthetic mappings h + geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = \"grey70\") + geom_line(aes(y = level)) # The underlying stat_align() takes care of unaligned data points df <- data.frame( g = c(\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"), x = c(1, 3, 5, 2, 4, 6), y = c(2, 5, 1, 3, 6, 7) ) a <- ggplot(df, aes(x, y, fill = g)) + geom_area() # Two groups have points on different X values. a + geom_point(size = 8) + facet_grid(g ~ .) # stat_align() interpolates and aligns the value so that the areas can stack # properly. a + geom_point(stat = \"align\", position = \"stack\", size = 8) # To turn off the alignment, the stat can be set to \"identity\" ggplot(df, aes(x, y, fill = g)) + geom_area(stat = \"identity\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":null,"dir":"Reference","previous_headings":"","what":"Rug plots in the margins — geom_rug","title":"Rug plots in the margins — geom_rug","text":"rug plot compact visualisation designed supplement 2d display two 1d marginal distributions. Rug plots display individual cases best used smaller datasets.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Rug plots in the margins — geom_rug","text":"","code":"geom_rug( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., outside = FALSE, sides = \"bl\", length = unit(0.03, \"npc\"), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Rug plots in the margins — geom_rug","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. outside logical controls whether move rug tassels outside plot area. Default (FALSE). also need use coord_cartesian(clip = \"\"). set TRUE, also consider changing sides argument \"tr\". See examples. sides string controls sides plot rugs appear . can set string containing \"trbl\", top, right, bottom, left. length grid::unit() object sets length rug lines. Use scale expansion avoid overplotting data. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Rug plots in the margins — geom_rug","text":"default, rug lines drawn length corresponds 3% total plot size. Since default scale expansion continuous variables 5% ends scale, rug overlap data points default settings.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Rug plots in the margins — geom_rug","text":"geom_rug() understands following aesthetics (required aesthetics bold): alpha colour group linetype linewidth x y Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_rug.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Rug plots in the margins — geom_rug","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() p p + geom_rug() p + geom_rug(sides=\"b\") # Rug on bottom only p + geom_rug(sides=\"trbl\") # All four sides # Use jittering to avoid overplotting for smaller datasets ggplot(mpg, aes(displ, cty)) + geom_point() + geom_rug() ggplot(mpg, aes(displ, cty)) + geom_jitter() + geom_rug(alpha = 1/2, position = \"jitter\") # move the rug tassels to outside the plot # remember to set clip = \"off\". p + geom_rug(outside = TRUE) + coord_cartesian(clip = \"off\") # set sides to top right, and then move the margins p + geom_rug(outside = TRUE, sides = \"tr\") + coord_cartesian(clip = \"off\") + theme(plot.margin = margin(1, 1, 1, 1, \"cm\")) # increase the line length and # expand axis to avoid overplotting p + geom_rug(length = unit(0.05, \"npc\")) + scale_y_continuous(expand = c(0.1, 0.1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":null,"dir":"Reference","previous_headings":"","what":"Line segments and curves — geom_segment","title":"Line segments and curves — geom_segment","text":"geom_segment() draws straight line points (x, y) (xend, yend). geom_curve() draws curved line. See underlying drawing function grid::curveGrob() parameters control curve.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Line segments and curves — geom_segment","text":"","code":"geom_segment( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., arrow = NULL, arrow.fill = NULL, lineend = \"butt\", linejoin = \"round\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_curve( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., curvature = 0.5, angle = 90, ncp = 5, arrow = NULL, arrow.fill = NULL, lineend = \"butt\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Line segments and curves — geom_segment","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. arrow specification arrow heads, created grid::arrow(). arrow.fill fill colour use arrow head (closed). NULL means use colour aesthetic. lineend Line end style (round, butt, square). linejoin Line join style (round, mitre, bevel). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). curvature numeric value giving amount curvature. Negative values produce left-hand curves, positive values produce right-hand curves, zero produces straight line. angle numeric value 0 180, giving amount skew control points curve. Values less 90 skew curve towards start point values greater 90 skew curve towards end point. ncp number control points used draw curve. control points creates smoother curve.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Line segments and curves — geom_segment","text":"geoms draw single segment/curve per case. See geom_path() need connect points across multiple cases.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Line segments and curves — geom_segment","text":"geom_segment() understands following aesthetics (required aesthetics bold): x y xend yend alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_segment.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Line segments and curves — geom_segment","text":"","code":"b <- ggplot(mtcars, aes(wt, mpg)) + geom_point() df <- data.frame(x1 = 2.62, x2 = 3.57, y1 = 21.0, y2 = 15.0) b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2, colour = \"curve\"), data = df) + geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2, colour = \"segment\"), data = df) b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2), data = df, curvature = -0.2) b + geom_curve(aes(x = x1, y = y1, xend = x2, yend = y2), data = df, curvature = 1) b + geom_curve( aes(x = x1, y = y1, xend = x2, yend = y2), data = df, arrow = arrow(length = unit(0.03, \"npc\")) ) if (requireNamespace('maps', quietly = TRUE)) { ggplot(seals, aes(long, lat)) + geom_segment(aes(xend = long + delta_long, yend = lat + delta_lat), arrow = arrow(length = unit(0.1,\"cm\"))) + borders(\"state\") } # Use lineend and linejoin to change the style of the segments df2 <- expand.grid( lineend = c('round', 'butt', 'square'), linejoin = c('round', 'mitre', 'bevel'), stringsAsFactors = FALSE ) df2 <- data.frame(df2, y = 1:9) ggplot(df2, aes(x = 1, y = y, xend = 2, yend = y, label = paste(lineend, linejoin))) + geom_segment( lineend = df2$lineend, linejoin = df2$linejoin, size = 3, arrow = arrow(length = unit(0.3, \"inches\")) ) + geom_text(hjust = 'outside', nudge_x = -0.2) + xlim(0.5, 2) # You can also use geom_segment to recreate plot(type = \"h\") : set.seed(1) counts <- as.data.frame(table(x = rpois(100,5))) counts$x <- as.numeric(as.character(counts$x)) with(counts, plot(x, Freq, type = \"h\", lwd = 10)) ggplot(counts, aes(x, Freq)) + geom_segment(aes(xend = x, yend = 0), linewidth = 10, lineend = \"butt\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":null,"dir":"Reference","previous_headings":"","what":"Smoothed conditional means — geom_smooth","title":"Smoothed conditional means — geom_smooth","text":"Aids eye seeing patterns presence overplotting. geom_smooth() stat_smooth() effectively aliases: use arguments. Use stat_smooth() want display results non-standard geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Smoothed conditional means — geom_smooth","text":"","code":"geom_smooth( mapping = NULL, data = NULL, stat = \"smooth\", position = \"identity\", ..., method = NULL, formula = NULL, se = TRUE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_smooth( mapping = NULL, data = NULL, geom = \"smooth\", position = \"identity\", ..., method = NULL, formula = NULL, se = TRUE, n = 80, span = 0.75, fullrange = FALSE, xseq = NULL, level = 0.95, method.args = list(), na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Smoothed conditional means — geom_smooth","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. method Smoothing method (function) use, accepts either NULL character vector, e.g. \"lm\", \"glm\", \"gam\", \"loess\" function, e.g. MASS::rlm mgcv::gam, stats::lm, stats::loess. \"auto\" also accepted backwards compatibility. equivalent NULL. method = NULL smoothing method chosen based size largest group (across panels). stats::loess() used less 1,000 observations; otherwise mgcv::gam() used formula = y ~ s(x, bs = \"cs\") method = \"REML\". Somewhat anecdotally, loess gives better appearance, \\(O(N^{2})\\) memory, work larger datasets. fewer 1,000 observations want use gam() model method = NULL use, set method = \"gam\", formula = y ~ s(x, bs = \"cs\"). formula Formula use smoothing function, eg. y ~ x, y ~ poly(x, 2), y ~ log(x). NULL default, case method = NULL implies formula = y ~ x fewer 1,000 observations formula = y ~ s(x, bs = \"cs\") otherwise. se Display confidence band around smooth? (TRUE default, see level control.) na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_smooth() stat_smooth(). information overriding connections, see stat geom arguments work. n Number points evaluate smoother. span Controls amount smoothing default loess smoother. Smaller numbers produce wigglier lines, larger numbers produce smoother lines. used loess, .e. method = \"loess\", method = NULL (default) fewer 1,000 observations. fullrange TRUE, smoothing line gets expanded range plot, potentially beyond data. extend line additional padding created expansion. xseq numeric vector values smoother evaluated. NULL (default), xseq internally evaluated sequence n equally spaced points continuous data. level Level confidence band use (0.95 default). method.args List additional arguments passed modelling function defined method.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Smoothed conditional means — geom_smooth","text":"Calculation performed (currently undocumented) predictdf() generic methods. methods standard error bounds computed using predict() method – exceptions loess(), uses t-based approximation, glm(), normal confidence band constructed link scale back-transformed response scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Smoothed conditional means — geom_smooth","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Smoothed conditional means — geom_smooth","text":"geom_smooth() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth weight ymax ymin Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Smoothed conditional means — geom_smooth","text":"calculated 'stat' part layers can accessed delayed evaluation. stat_smooth() provides following variables, depend orientation: after_stat(y) after_stat(x) Predicted value. after_stat(ymin) after_stat(xmin) Lower pointwise confidence band around mean. after_stat(ymax) after_stat(xmax) Upper pointwise confidence band around mean. after_stat(se) Standard error.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_smooth.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Smoothed conditional means — geom_smooth","text":"","code":"ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth() #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # If you need the fitting to be done along the y-axis set the orientation ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(orientation = \"y\") #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Use span to control the \"wiggliness\" of the default loess smoother. # The span is the fraction of points used to fit each local regression: # small numbers make a wigglier curve, larger numbers make a smoother curve. ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(span = 0.3) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Instead of a loess smooth, you can use any other modelling function: ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = lm, se = FALSE) #> `geom_smooth()` using formula = 'y ~ x' ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = lm, formula = y ~ splines::bs(x, 3), se = FALSE) # Smooths are automatically fit to each group (defined by categorical # aesthetics or the group aesthetic) and for each facet. ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + geom_smooth(se = FALSE, method = lm) #> `geom_smooth()` using formula = 'y ~ x' ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(span = 0.8) + facet_wrap(~drv) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # \\donttest{ binomial_smooth <- function(...) { geom_smooth(method = \"glm\", method.args = list(family = \"binomial\"), ...) } # To fit a logistic regression, you need to coerce the values to # a numeric vector lying between 0 and 1. ggplot(rpart::kyphosis, aes(Age, Kyphosis)) + geom_jitter(height = 0.05) + binomial_smooth() #> `geom_smooth()` using formula = 'y ~ x' #> Warning: Failed to fit group 2. #> Caused by error: #> ! y values must be 0 <= y <= 1 ggplot(rpart::kyphosis, aes(Age, as.numeric(Kyphosis) - 1)) + geom_jitter(height = 0.05) + binomial_smooth() #> `geom_smooth()` using formula = 'y ~ x' ggplot(rpart::kyphosis, aes(Age, as.numeric(Kyphosis) - 1)) + geom_jitter(height = 0.05) + binomial_smooth(formula = y ~ splines::ns(x, 2)) # But in this case, it's probably better to fit the model yourself # so you can exercise more control and see whether or not it's a good model. # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":null,"dir":"Reference","previous_headings":"","what":"Line segments parameterised by location, direction and distance — geom_spoke","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"polar parameterisation geom_segment(). useful variables describe direction distance. angles start east increase counterclockwise.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"","code":"geom_spoke( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"geom_spoke() understands following aesthetics (required aesthetics bold): x y angle radius alpha colour group linetype linewidth Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_spoke.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Line segments parameterised by location, direction and distance — geom_spoke","text":"","code":"df <- expand.grid(x = 1:10, y=1:10) set.seed(1) df$angle <- runif(100, 0, 2*pi) df$speed <- runif(100, 0, sqrt(0.1 * df$x)) ggplot(df, aes(x, y)) + geom_point() + geom_spoke(aes(angle = angle), radius = 0.5) ggplot(df, aes(x, y)) + geom_point() + geom_spoke(aes(angle = angle, radius = speed))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":null,"dir":"Reference","previous_headings":"","what":"Text — geom_label","title":"Text — geom_label","text":"Text geoms useful labeling plots. can used scatterplots combination geoms, example, labeling points annotating height bars. geom_text() adds text plot. geom_label() draws rectangle behind text, making easier read.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Text — geom_label","text":"","code":"geom_label( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, label.padding = unit(0.25, \"lines\"), label.r = unit(0.15, \"lines\"), label.size = 0.25, size.unit = \"mm\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_text( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE, size.unit = \"mm\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Text — geom_label","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. jointy specified nudge_x nudge_y. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. parse TRUE, labels parsed expressions displayed described ?plotmath. nudge_x, nudge_y Horizontal vertical adjustment nudge labels . Useful offsetting text points, particularly discrete scales. jointly specified position. label.padding Amount padding around label. Defaults 0.25 lines. label.r Radius rounded corners. Defaults 0.15 lines. label.size Size label border, mm. size.unit size aesthetic interpreted: millimetres (\"mm\", default), points (\"pt\"), centimetres (\"cm\"), inches (\"\"), picas (\"pc\"). na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). check_overlap TRUE, text overlaps previous text layer plotted. check_overlap happens draw time order data. Therefore data arranged label column calling geom_text(). Note argument supported geom_label().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Text — geom_label","text":"Note resize plot, text labels stay size, even though size plot area changes. happens \"width\" \"height\" text element 0. Obviously, text labels height width, physical units, data units. reason, stacking dodging text work default, axis limits automatically expanded include text. geom_text() geom_label() add labels row data, even coordinates x, y set single values call geom_label() geom_text(). add labels specified points use annotate() annotate(geom = \"text\", ...) annotate(geom = \"label\", ...). automatically position non-overlapping text labels see ggrepel package.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Text — geom_label","text":"geom_text() understands following aesthetics (required aesthetics bold): x y label alpha angle colour family fontface group hjust lineheight size vjust Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"geom-label-","dir":"Reference","previous_headings":"","what":"geom_label()","title":"Text — geom_label","text":"Currently geom_label() support check_overlap argument. Also, considerably slower geom_text(). fill aesthetic controls background colour label.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"alignment","dir":"Reference","previous_headings":"","what":"Alignment","title":"Text — geom_label","text":"can modify text alignment vjust hjust aesthetics. can either number 0 (right/bottom) 1 (top/left) character (\"left\", \"middle\", \"right\", \"bottom\", \"center\", \"top\"). two special alignments: \"inward\" \"outward\". Inward always aligns text towards center, outward aligns away center.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_text.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Text — geom_label","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars))) p + geom_text() # Avoid overlaps p + geom_text(check_overlap = TRUE) # Labels with background p + geom_label() # Change size of the label p + geom_text(size = 10) # Set aesthetics to fixed value p + geom_point() + geom_text(hjust = 0, nudge_x = 0.05) p + geom_point() + geom_text(vjust = 0, nudge_y = 0.5) p + geom_point() + geom_text(angle = 45) if (FALSE) { # \\dontrun{ # Doesn't work on all systems p + geom_text(family = \"Times New Roman\") } # } # Add aesthetic mappings p + geom_text(aes(colour = factor(cyl))) p + geom_text(aes(colour = factor(cyl))) + scale_colour_discrete(l = 40) p + geom_label(aes(fill = factor(cyl)), colour = \"white\", fontface = \"bold\") # Scale size of text, and change legend key glyph from a to point p + geom_text(aes(size = wt), key_glyph = \"point\") # Scale height of text, rather than sqrt(height) p + geom_text(aes(size = wt), key_glyph = \"point\") + scale_radius(range = c(3,6)) # You can display expressions by setting parse = TRUE. The # details of the display are described in ?plotmath, but note that # geom_text uses strings, not expressions. p + geom_text( aes(label = paste(wt, \"^(\", cyl, \")\", sep = \"\")), parse = TRUE ) # Add a text annotation p + geom_text() + annotate( \"text\", label = \"plot mpg vs. wt\", x = 2, y = 15, size = 8, colour = \"red\" ) # \\donttest{ # Aligning labels and bars -------------------------------------------------- df <- data.frame( x = factor(c(1, 1, 2, 2)), y = c(1, 3, 2, 1), grp = c(\"a\", \"b\", \"a\", \"b\") ) # ggplot2 doesn't know you want to give the labels the same virtual width # as the bars: ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = \"dodge\") + geom_text(aes(label = y), position = \"dodge\") #> Warning: Width not defined #> ℹ Set with `position_dodge(width = ...)` # So tell it: ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = \"dodge\") + geom_text(aes(label = y), position = position_dodge(0.9)) # You can't nudge and dodge text, so instead adjust the y position ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = \"dodge\") + geom_text( aes(label = y, y = y + 0.05), position = position_dodge(0.9), vjust = 0 ) # To place text in the middle of each bar in a stacked barplot, you # need to set the vjust parameter of position_stack() ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp)) + geom_text(aes(label = y), position = position_stack(vjust = 0.5)) # Justification ------------------------------------------------------------- df <- data.frame( x = c(1, 1, 2, 2, 1.5), y = c(1, 2, 1, 2, 1.5), text = c(\"bottom-left\", \"top-left\", \"bottom-right\", \"top-right\", \"center\") ) ggplot(df, aes(x, y)) + geom_text(aes(label = text)) ggplot(df, aes(x, y)) + geom_text(aes(label = text), vjust = \"inward\", hjust = \"inward\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":null,"dir":"Reference","previous_headings":"","what":"Rectangles — geom_raster","title":"Rectangles — geom_raster","text":"geom_rect() geom_tile() thing, parameterised differently: geom_tile() uses center tile size (x, y, width, height), geom_rect() can use locations corners (xmin, xmax, ymin ymax). geom_raster() high performance special case tiles size, pattern fills applied.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Rectangles — geom_raster","text":"","code":"geom_raster( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., hjust = 0.5, vjust = 0.5, interpolate = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_rect( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., linejoin = \"mitre\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_tile( mapping = NULL, data = NULL, stat = \"identity\", position = \"identity\", ..., linejoin = \"mitre\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Rectangles — geom_raster","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. hjust, vjust horizontal vertical justification grob. justification value number 0 1. Defaults 0.5 , centering pixel data location. interpolate TRUE interpolate linearly, FALSE (default) interpolate. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). linejoin Line join style (round, mitre, bevel).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Rectangles — geom_raster","text":"Please note width height aesthetics true position aesthetics therefore subject scale transformation. transformation aesthetics applied.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Rectangles — geom_raster","text":"geom_rect() understands following aesthetics (required aesthetics bold): x width xmin xmax y height ymin ymax alpha colour fill group linetype linewidth geom_tile() understands x/width y/height combinations. Note geom_raster() ignores colour. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_tile.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Rectangles — geom_raster","text":"","code":"# The most common use for rectangles is to draw a surface. You always want # to use geom_raster here because it's so much faster, and produces # smaller output when saving to PDF ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) # Interpolation smooths the surface & is most helpful when rendering images. ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density), interpolate = TRUE) # If you want to draw arbitrary rectangles, use geom_tile() or geom_rect() df <- data.frame( x = rep(c(2, 5, 7, 9, 12), 2), y = rep(c(1, 2), each = 5), z = factor(rep(1:5, each = 2)), w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2) ) ggplot(df, aes(x, y)) + geom_tile(aes(fill = z), colour = \"grey50\") ggplot(df, aes(x, y, width = w)) + geom_tile(aes(fill = z), colour = \"grey50\") ggplot(df, aes(xmin = x - w / 2, xmax = x + w / 2, ymin = y, ymax = y + 1)) + geom_rect(aes(fill = z), colour = \"grey50\") # \\donttest{ # Justification controls where the cells are anchored df <- expand.grid(x = 0:5, y = 0:5) set.seed(1) df$z <- runif(nrow(df)) # default is compatible with geom_tile() ggplot(df, aes(x, y, fill = z)) + geom_raster() # zero padding ggplot(df, aes(x, y, fill = z)) + geom_raster(hjust = 0, vjust = 0) # Inspired by the image-density plots of Ken Knoblauch cars <- ggplot(mtcars, aes(mpg, factor(cyl))) cars + geom_point() cars + stat_bin_2d(aes(fill = after_stat(count)), binwidth = c(3,1)) cars + stat_bin_2d(aes(fill = after_stat(density)), binwidth = c(3,1)) cars + stat_density( aes(fill = after_stat(density)), geom = \"raster\", position = \"identity\" ) cars + stat_density( aes(fill = after_stat(count)), geom = \"raster\", position = \"identity\" ) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":null,"dir":"Reference","previous_headings":"","what":"Violin plot — geom_violin","title":"Violin plot — geom_violin","text":"violin plot compact display continuous distribution. blend geom_boxplot() geom_density(): violin plot mirrored density plot displayed way boxplot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Violin plot — geom_violin","text":"","code":"geom_violin( mapping = NULL, data = NULL, stat = \"ydensity\", position = \"dodge\", ..., draw_quantiles = NULL, trim = TRUE, bounds = c(-Inf, Inf), scale = \"area\", na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) stat_ydensity( mapping = NULL, data = NULL, geom = \"violin\", position = \"dodge\", ..., bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", trim = TRUE, scale = \"area\", drop = TRUE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, bounds = c(-Inf, Inf) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Violin plot — geom_violin","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. draw_quantiles (NULL) (default), draw horizontal lines given quantiles density estimate. trim TRUE (default), trim tails violins range data. FALSE, trim tails. bounds Known lower upper bounds estimated data. Default c(-Inf, Inf) means (finite) bounds. bound finite, boundary effect default density estimation corrected reflecting tails outside bounds around closest edge. Data points outside bounds removed warning. scale \"area\" (default), violins area (trimming tails). \"count\", areas scaled proportionally number observations. \"width\", violins maximum width. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). geom, stat Use override default connection geom_violin() stat_ydensity(). information overriding connections, see stat geom arguments work. bw smoothing bandwidth used. numeric, standard deviation smoothing kernel. character, rule choose bandwidth, listed stats::bw.nrd(). Note automatic calculation bandwidth take weights account. adjust multiplicate bandwidth adjustment. makes possible adjust bandwidth still using bandwidth estimator. example, adjust = 1/2 means use half default bandwidth. kernel Kernel. See list available kernels density(). drop Whether discard groups less 2 observations (TRUE, default) keep groups position adjustment purposes (FALSE).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Violin plot — geom_violin","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Violin plot — geom_violin","text":"geom_violin() understands following aesthetics (required aesthetics bold): x y alpha colour fill group linetype linewidth weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Violin plot — geom_violin","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(density) Density estimate. after_stat(scaled) Density estimate, scaled maximum 1. after_stat(count) Density * number points - probably useless violin plots. after_stat(violinwidth) Density scaled violin plot, according area, counts constant maximum width. after_stat(n) Number points. after_stat(width) Width violin bounding box.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Violin plot — geom_violin","text":"Hintze, J. L., Nelson, R. D. (1998) Violin Plots: Box Plot-Density Trace Synergism. American Statistician 52, 181-184.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/geom_violin.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Violin plot — geom_violin","text":"","code":"p <- ggplot(mtcars, aes(factor(cyl), mpg)) p + geom_violin() # Orientation follows the discrete axis ggplot(mtcars, aes(mpg, factor(cyl))) + geom_violin() # \\donttest{ p + geom_violin() + geom_jitter(height = 0, width = 0.1) # Scale maximum width proportional to sample size: p + geom_violin(scale = \"count\") # Scale maximum width to 1 for all violins: p + geom_violin(scale = \"width\") # Default is to trim violins to the range of the data. To disable: p + geom_violin(trim = FALSE) # Use a smaller bandwidth for closer density fit (default is 1). p + geom_violin(adjust = .5) # Add aesthetic mappings # Note that violins are automatically dodged when any aesthetic is # a factor p + geom_violin(aes(fill = cyl)) p + geom_violin(aes(fill = factor(cyl))) p + geom_violin(aes(fill = factor(vs))) #> Warning: Groups with fewer than two datapoints have been dropped. #> ℹ Set `drop = FALSE` to consider such groups for position adjustment #> purposes. p + geom_violin(aes(fill = factor(am))) # Set aesthetics to fixed value p + geom_violin(fill = \"grey80\", colour = \"#3366FF\") # Show quartiles p + geom_violin(draw_quantiles = c(0.25, 0.5, 0.75)) # Scales vs. coordinate transforms ------- if (require(\"ggplot2movies\")) { # Scale transformations occur before the density statistics are computed. # Coordinate transformations occur afterwards. Observe the effect on the # number of outliers. m <- ggplot(movies, aes(y = votes, x = rating, group = cut_width(rating, 0.5))) m + geom_violin() m + geom_violin() + scale_y_log10() m + geom_violin() + coord_trans(y = \"log10\") m + geom_violin() + scale_y_log10() + coord_trans(y = \"log10\") # Violin plots with continuous x: # Use the group aesthetic to group observations in violins ggplot(movies, aes(year, budget)) + geom_violin() ggplot(movies, aes(year, budget)) + geom_violin(aes(group = cut_width(year, 10)), scale = \"width\") } #> Warning: Removed 53573 rows containing non-finite outside the scale range #> (`stat_ydensity()`). #> Warning: Groups with fewer than two datapoints have been dropped. #> ℹ Set `drop = FALSE` to consider such groups for position adjustment #> purposes. # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract alt text from a plot — get_alt_text","title":"Extract alt text from a plot — get_alt_text","text":"function returns text can used alt-text webpages etc. Currently use alt label, added + labs(alt = <...>), return empty string, future might try generate alt text information stored plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract alt text from a plot — get_alt_text","text":"","code":"get_alt_text(p, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract alt text from a plot — get_alt_text","text":"p ggplot object ... Arguments passed methods.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Extract alt text from a plot — get_alt_text","text":"text string","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_alt_text.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Extract alt text from a plot — get_alt_text","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Returns an empty string get_alt_text(p) #> [1] \"\" # A user provided alt text p <- p + labs( alt = paste(\"A scatterplot showing the negative correlation between engine\", \"displacement as a function of highway miles per gallon\") ) get_alt_text(p) #> [1] \"A scatterplot showing the negative correlation between engine displacement as a function of highway miles per gallon\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":null,"dir":"Reference","previous_headings":"","what":"Resolve and get geom defaults — get_geom_defaults","title":"Resolve and get geom defaults — get_geom_defaults","text":"Resolve get geom defaults","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Resolve and get geom defaults — get_geom_defaults","text":"","code":"get_geom_defaults(geom, theme = theme_get())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Resolve and get geom defaults — get_geom_defaults","text":"geom definition geom: function creates layer, e.g. geom_path(). layer created function string naming geom class snake case without geom_-prefix, e.g. \"contour_filled\". geom class object. theme theme object. Defaults current global theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Resolve and get geom defaults — get_geom_defaults","text":"list aesthetics","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_geom_defaults.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Resolve and get geom defaults — get_geom_defaults","text":"","code":"# Using a function get_geom_defaults(geom_raster) #> fill alpha #> 1 #333333FF NA # Using a layer includes static aesthetics as default get_geom_defaults(geom_tile(fill = \"white\")) #> fill colour linewidth linetype alpha width height #> 1 white NA 0.2 1 NA NA NA # Using a class name get_geom_defaults(\"density_2d\") #> colour linewidth linetype alpha #> 1 #3366FF 0.5 1 NA # Using a class get_geom_defaults(GeomPoint) #> shape colour size fill alpha stroke #> 1 19 black 1.5 NA NA 0.5 # Changed theme get_geom_defaults(\"point\", theme(geom = element_geom(ink = \"purple\"))) #> shape colour size fill alpha stroke #> 1 19 purple 1.5 NA NA 0.5"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract tick information from guides — get_guide_data","title":"Extract tick information from guides — get_guide_data","text":"get_guide_data() builds plot extracts information guide keys. information typically contains positions, values /labels, depending aesthetic queried guide used.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract tick information from guides — get_guide_data","text":"","code":"get_guide_data(plot = get_last_plot(), aesthetic, panel = 1L)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract tick information from guides — get_guide_data","text":"plot ggplot ggplot_build object. aesthetic string describes single aesthetic extract guide information. example: \"colour\", \"size\", \"x\" \"y.sec\". panel integer giving panel number return position guide information.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Extract tick information from guides — get_guide_data","text":"One following: data.frame representing guide key, guide unique aesthetic. list coord support position axes multiple guides match aesthetic. NULL guide key found.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_guide_data.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Extract tick information from guides — get_guide_data","text":"","code":"# A standard plot p <- ggplot(mtcars) + aes(mpg, disp, colour = drat, size = drat) + geom_point() + facet_wrap(vars(cyl), scales = \"free_x\") # Guide information for legends get_guide_data(p, \"size\") #> size .value .label #> 1 2.662822 3.0 3.0 #> 2 3.919819 3.5 3.5 #> 3 4.779645 4.0 4.0 #> 4 5.477285 4.5 4.5 # Note that legend guides can be merged merged <- p + guides(colour = \"legend\") get_guide_data(merged, \"size\") #> colour .value .label size #> 1 #1A3855 3.0 3.0 2.662822 #> 2 #28557C 3.5 3.5 3.919819 #> 3 #3874A5 4.0 4.0 4.779645 #> 4 #4894D0 4.5 4.5 5.477285 # Guide information for positions get_guide_data(p, \"x\", panel = 2) #> x .value .label y #> 1 0.0959596 18 18 0 #> 2 0.3484848 19 19 0 #> 3 0.6010101 20 20 0 #> 4 0.8535354 21 21 0 # Coord polar doesn't support proper guides, so we get a list polar <- p + coord_polar() get_guide_data(polar, \"theta\", panel = 2) #> $theta.range #> [1] 17.8 21.4 #> #> $theta.major #> [1] 18 19 20 21 #> #> $theta.minor #> [1] 18.0 18.5 19.0 19.5 20.0 20.5 21.0 #> #> $theta.labels #> [1] \"18\" \"19\" \"20\" \"21\" #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_last_plot.html","id":null,"dir":"Reference","previous_headings":"","what":"Retrieve the last plot to be modified or created. — get_last_plot","title":"Retrieve the last plot to be modified or created. — get_last_plot","text":"Retrieve last plot modified created.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_last_plot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Retrieve the last plot to be modified or created. — get_last_plot","text":"","code":"get_last_plot() last_plot()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":null,"dir":"Reference","previous_headings":"","what":"Accessing a plot's facet strip labels — get_strip_labels","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"functions retrieves labels facet strips labeller applied.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"","code":"get_strip_labels(plot = get_last_plot())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"plot ggplot build ggplot object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"NULL labels, otherwise list data.frames containing labels.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_strip_labels.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Accessing a plot's facet strip labels — get_strip_labels","text":"","code":"# Basic plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() get_strip_labels(p) # empty facets #> NULL get_strip_labels(p + facet_wrap(year ~ cyl)) #> $facets #> year cyl #> 1 1999 4 #> 2 1999 6 #> 3 1999 8 #> 4 2008 4 #> 5 2008 5 #> 6 2008 6 #> 7 2008 8 #> get_strip_labels(p + facet_grid(year ~ cyl)) #> $cols #> cyl #> 1 4 #> 2 5 #> 3 6 #> 4 8 #> #> $rows #> year #> 1 1999 #> 2 2008 #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Get, set, and modify the active theme — get_theme","title":"Get, set, and modify the active theme — get_theme","text":"current/active theme (see theme()) automatically applied every plot draw. Use get_theme() get current theme, set_theme() completely override . update_theme() replace_theme() shorthands changing individual elements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get, set, and modify the active theme — get_theme","text":"","code":"get_theme() theme_get() set_theme(new) theme_set(new) update_theme(...) theme_update(...) replace_theme(...) theme_replace(...) e1 %+replace% e2"},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get, set, and modify the active theme — get_theme","text":"new new theme (list theme elements) ... named list theme settings e1, e2 Theme element combine","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get, set, and modify the active theme — get_theme","text":"set_theme(), update_theme(), replace_theme() invisibly return previous theme can easily save , later restore .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"adding-on-to-a-theme","dir":"Reference","previous_headings":"","what":"Adding on to a theme","title":"Get, set, and modify the active theme — get_theme","text":"+ %+replace% can used modify elements themes. + updates elements e1 differ elements specified (NULL) e2. Thus operator can used incrementally add modify attributes ggplot theme. contrast, %+replace% replaces entire element; element theme specified e2 present resulting theme (.e. NULL). Thus operator can used overwrite entire theme. update_theme() uses + operator, unspecified values theme element default values set theme. replace_theme() uses %+replace% completely replace element, unspecified values overwrite current value theme NULL. summary, main differences set_theme(), update_theme(), replace_theme() : set_theme() completely overrides current theme. update_theme() modifies particular element current theme using + operator. replace_theme() modifies particular element current theme using %+replace% operator.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/get_theme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Get, set, and modify the active theme — get_theme","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p # Use set_theme() to completely override the current theme. # update_theme() and replace_theme() are similar except they # apply directly to the current/active theme. # update_theme() modifies a particular element of the current theme. # Here we have the old theme so we can later restore it. # Note that the theme is applied when the plot is drawn, not # when it is created. old <- set_theme(theme_bw()) p set_theme(old) update_theme(panel.grid.minor = element_line(colour = \"red\")) p set_theme(old) replace_theme(panel.grid.minor = element_line(colour = \"red\")) p set_theme(old) p # Modifying theme objects ----------------------------------------- # You can use + and %+replace% to modify a theme object. # They differ in how they deal with missing arguments in # the theme elements. add_el <- theme_grey() + theme(text = element_text(family = \"Times\")) add_el$text #> List of 11 #> $ family : chr \"Times\" #> $ face : chr \"plain\" #> $ colour : chr \"black\" #> $ size : num 11 #> $ hjust : num 0.5 #> $ vjust : num 0.5 #> $ angle : num 0 #> $ lineheight : num 0.9 #> $ margin : 'margin' num [1:4] 0points 0points 0points 0points #> ..- attr(*, \"unit\")= int 8 #> $ debug : logi FALSE #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\" rep_el <- theme_grey() %+replace% theme(text = element_text(family = \"Times\")) rep_el$text #> List of 11 #> $ family : chr \"Times\" #> $ face : NULL #> $ colour : NULL #> $ size : NULL #> $ hjust : NULL #> $ vjust : NULL #> $ angle : NULL #> $ lineheight : NULL #> $ margin : NULL #> $ debug : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":null,"dir":"Reference","previous_headings":"","what":"Add components to a plot — +.gg","title":"Add components to a plot — +.gg","text":"+ key constructing sophisticated ggplot2 graphics. allows start simple, get complex, checking work step.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Add components to a plot — +.gg","text":"","code":"# S3 method for class 'gg' e1 + e2 e1 %+% e2"},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Add components to a plot — +.gg","text":"e1 object class ggplot() theme(). e2 plot component, described .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"what-can-you-add-","dir":"Reference","previous_headings":"","what":"What can you add?","title":"Add components to a plot — +.gg","text":"can add following types objects: aes() object replaces default aesthetics. layer created geom_ stat_ function adds new layer. scale overrides existing scale. theme() modifies current theme. coord overrides current coordinate system. facet specification overrides current faceting. replace current default data frame, must use %+%, due S3 method precedence issues. can also supply list, case element list added turn.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg-add.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Add components to a plot — +.gg","text":"","code":"base <- ggplot(mpg, aes(displ, hwy)) + geom_point() base + geom_smooth() #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # To override the data, you must use %+% base %+% subset(mpg, fl == \"p\") # Alternatively, you can add multiple components with a list. # This can be useful to return from a function. base + list(subset(mpg, fl == \"p\"), geom_smooth()) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_dep.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Give a deprecation error, warning, or message, depending on version number. — gg_dep","text":"","code":"gg_dep(version, msg)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_dep.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Give a deprecation error, warning, or message, depending on version number. — gg_dep","text":"version last version ggplot2 function good (words, last version deprecated). msg message print.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":null,"dir":"Reference","previous_headings":"","what":"Interpreter for graphical parameters — gg_par","title":"Interpreter for graphical parameters — gg_par","text":"wrapper grid::gpar() applies ggplot2's interpretation graphical parameters.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Interpreter for graphical parameters — gg_par","text":"","code":"gg_par(..., stroke = NULL, pointsize = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Interpreter for graphical parameters — gg_par","text":"... Named arguments passed gpar(). stroke Linewidth points. Populates lwd grid parameter. pointsize Size points. Populates fontsize grid parameter.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/gg_par.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Interpreter for graphical parameters — gg_par","text":"object class 'gpar'.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new ggplot — ggplot","title":"Create a new ggplot — ggplot","text":"ggplot() initializes ggplot object. can used declare input data frame graphic specify set plot aesthetics intended common throughout subsequent layers unless specifically overridden.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new ggplot — ggplot","text":"","code":"ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new ggplot — ggplot","text":"data Default dataset use plot. already data.frame, converted one fortify(). specified, must supplied layer added plot. mapping Default list aesthetic mappings use plot. specified, must supplied layer added plot. ... arguments passed methods. currently used. environment Used prior tidy evaluation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new ggplot — ggplot","text":"ggplot() used construct initial plot object, almost always followed plus sign (+) add components plot. three common patterns used invoke ggplot(): ggplot(data = df, mapping = aes(x, y, aesthetics)) ggplot(data = df) ggplot() first pattern recommended layers use data set aesthetics, although method can also used adding layer using data another data frame. second pattern specifies default data frame use plot, aesthetics defined front. useful one data frame used predominantly plot, aesthetics vary one layer another. third pattern initializes skeleton ggplot object, fleshed layers added. useful multiple data frames used produce different layers, often case complex graphics. data = mapping = specifications arguments optional (often omitted practice), long data mapping values passed function right order. examples , however, left place clarity.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new ggplot — ggplot","text":"","code":"# Create a data frame with some sample data, then create a data frame # containing the mean value for each group in the sample data. set.seed(1) sample_df <- data.frame( group = factor(rep(letters[1:3], each = 10)), value = rnorm(30) ) group_means_df <- setNames( aggregate(value ~ group, sample_df, mean), c(\"group\", \"group_mean\") ) # The following three code blocks create the same graphic, each using one # of the three patterns specified above. In each graphic, the sample data # are plotted in the first layer and the group means data frame is used to # plot larger red points on top of the sample data in the second layer. # Pattern 1 # Both the `data` and `mapping` arguments are passed into the `ggplot()` # call. Those arguments are omitted in the first `geom_point()` layer # because they get passed along from the `ggplot()` call. Note that the # second `geom_point()` layer re-uses the `x = group` aesthetic through # that mechanism but overrides the y-position aesthetic. ggplot(data = sample_df, mapping = aes(x = group, y = value)) + geom_point() + geom_point( mapping = aes(y = group_mean), data = group_means_df, colour = 'red', size = 3 ) # Pattern 2 # Same plot as above, passing only the `data` argument into the `ggplot()` # call. The `mapping` arguments are now required in each `geom_point()` # layer because there is no `mapping` argument passed along from the # `ggplot()` call. ggplot(data = sample_df) + geom_point(mapping = aes(x = group, y = value)) + geom_point( mapping = aes(x = group, y = group_mean), data = group_means_df, colour = 'red', size = 3 ) # Pattern 3 # Same plot as above, passing neither the `data` or `mapping` arguments # into the `ggplot()` call. Both those arguments are now required in # each `geom_point()` layer. This pattern can be particularly useful when # creating more complex graphics with many layers using data from multiple # data frames. ggplot() + geom_point(mapping = aes(x = group, y = value), data = sample_df) + geom_point( mapping = aes(x = group, y = group_mean), data = group_means_df, colour = 'red', size = 3 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Base ggproto classes for ggplot2 — ggplot2-ggproto","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"creating new geom, stat, position, scale another package, need extend ggplot2::Geom, ggplot2::Stat, ggplot2::Position, ggplot2::Scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"geoms","dir":"Reference","previous_headings":"","what":"Geoms","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"geom_*() functions (like geom_point()) return layer contains Geom* object (like GeomPoint). Geom* object responsible rendering data plot. Geom* objects ggproto() object, descended top-level Geom, implements various methods fields. Compared Stat Position, Geom little different execution setup compute functions split . setup_data runs position adjustments, draw_layer() run render time, much later. create new type Geom object, typically want override one following: Either draw_panel(self, data, panel_params, coord) draw_group(self, data, panel_params, coord). draw_panel called per panel, draw_group called per group. Use draw_panel row data represents single element. Use draw_group group represents element (e.g. smooth, violin). data data frame scaled aesthetics. panel_params set per-panel parameters coord. Generally, consider panel_params opaque data structure pass along whenever call coord method. must always call coord$transform(data, panel_params) get (position) scaled data plotting. work non-linear coordinate systems, typically need convert primitive geom (e.g. point, path polygon), pass corresponding draw method munching. Must return grob. Use zeroGrob() nothing draw. draw_key: Renders single legend key. required_aes: character vector aesthetics needed render geom. default_aes: list (generated aes() default values aesthetics. setup_data: Converts width height xmin xmax, ymin ymax values. can potentially set values well. See also new geoms section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"coordinate-systems","dir":"Reference","previous_headings":"","what":"Coordinate systems","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"coord_*() functions (like coord_trans()) return Coord* object (like CoordTrans). Coord* objects ggproto() object, descended top-level Coord. create new type Coord object, typically want implement one following: aspect: Returns desired aspect ratio plot. labels: Returns list containing labels x y. render_fg: Renders foreground elements. render_bg: Renders background elements. render_axis_h: Renders horizontal axes. render_axis_v: Renders vertical axes. backtransform_range(panel_params): Extracts panel range provided panel_params (created setup_panel_params(), see ) back-transforms data coordinates. back-transformation can needed coords coord_trans() range transformed coordinates differs range untransformed coordinates. Returns list two ranges, x y, correspond variables mapped x y aesthetics, even coords coord_flip() x aesthetic shown along y direction vice versa. range(panel_params): Extracts panel range provided panel_params (created setup_panel_params(), see ) returns . Unlike backtransform_range(), function perform back-transformation instead returns final transformed coordinates. Returns list two ranges, x y, correspond variables mapped x y aesthetics, even coords coord_flip() x aesthetic shown along y direction vice versa. transform: Transforms x y coordinates. distance: Calculates distance. is_linear: Returns TRUE coordinate system linear; FALSE otherwise. is_free: Returns TRUE coordinate system supports free positional scales; FALSE otherwise. setup_panel_params(scale_x, scale_y, params): Determines appropriate x y ranges panel, also calculates anything else needed render panel axes, tick positions labels major minor ticks. Returns information named list. setup_data(data, params): Allows coordinate system manipulate plot data. return list data frames. setup_layout(layout, params): Allows coordinate system manipulate layout data frame assigns data panels scales. See also new coords section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"facets","dir":"Reference","previous_headings":"","what":"Facets","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"facet_* functions returns Facet object object Facet subclass. object describes assign data different panels, apply positional scales lay panels, rendered. Extending facets can range simple modifications current facets, laborious rewrites lot gtable() manipulation. examples , please see extension vignette. Facet subclasses, like extendible ggproto classes, range methods can modified. required new subclasses, need modified need arises. required methods : compute_layout: Based layer data compute mapping panels, axes, potentially parameters faceting variable level etc. method must return data.frame containing least columns PANEL, SCALE_X, SCALE_Y containing integer keys mapping PANEL axes use. addition data.frame can contain whatever information necessary assign observations correct panel well determining position panel. map_data: method supplied data layer turn expected supply PANEL column mapping row panel defined layout. Additionally method can also add subtract data points needed e.g. case adding margins facet_grid(). draw_panels: panels assembled gtable object. method receives, among others, list grobs defining content panel generated Geoms Coord objects. responsibility method decorate panels axes strips needed, well position relative gtable. automatic functions work correctly, panel, axis, strip grob name must prefixed \"panel\", \"axis\", \"strip\" respectively. addition methods described , also possible override default behaviour one following methods: setup_params: init_scales: Given master scale x y, create panel specific scales panel defined layout. default simply clone master scale. train_scales: Based layer data train set panel scales. default train data related panel. finish_data: Make last-minute modifications layer data rendered Geoms. default modify . draw_back: Add grob background defined Coord object (usually axis grid) layer stack. default return empty grob panel. draw_front: except returned grob placed layer stack foreground defined Coord object (usually empty). default , , return empty grob. draw_labels: Given gtable returned draw_panels, add axis titles gtable. default add one title side depending position existence axes. extension methods receive content params field params argument, constructor function generally put relevant information field. exception shrink parameter used determine scales retrained Stat transformations applied. See also new facets section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"stats","dir":"Reference","previous_headings":"","what":"Stats","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"stat_*() functions (like stat_bin()) return layer contains Stat* object (like StatBin). Stat* object responsible rendering data plot. Stat* objects ggproto() object, descended top-level Stat, implements various methods fields. create new type Stat object, typically want override one following: One : compute_layer(self, data, scales, ...), compute_panel(self, data, scales, ...), compute_group(self, data, scales, ...). compute_layer() called per layer, compute_panel() called per panel, compute_group() called per group. must return data frame. usually best start overriding compute_group: find substantial performance optimisations, override higher . need read source code default methods see else . data data frame containing variables named according aesthetics mapped . scales list containing x y scales. functions called facets trained, global scales, local individual panels.... contains parameters returned setup_params(). finish_layer(data, params): called layer. Used modify data scales applied, data handed geom rendering. default modify data. Use hook stat needs access actual aesthetic values rather values mapped aesthetic. setup_params(data, params): called layer. Used setup defaults need complete dataset, inform user important choices. return list parameters. setup_data(data, params): called layer, setup_params(). return modified data. Default methods removes rows containing missing value required aesthetics (warning !na.rm). required_aes: character vector aesthetics needed render geom. default_aes: list (generated aes() default values aesthetics. dropped_aes vecor aesthetic names safe drop statistical transformation. classic example weight aesthetic consumed computation stat. See also new stats section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"guides","dir":"Reference","previous_headings":"","what":"Guides","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"guide_*() functions, guide_legend() return object responsible displaying objects plotting panel related actual values. Guide* object ggproto() object, descended top-level Guide, implements methods drawing. create new type Guide object, typically want override one following: Properties: available_aes character vector aesthetics guide supports. value \"\" indicates non-position aesthetics. params named list parameters guide needs function. following roles: params provides defaults guide. names(params) determines valid arguments new_guide(). parameters required render guide. : title, name, position, direction, order hash. build stages, params holds information guide. elements named list characters, giving name theme elements retrieved automatically, example \"legend.text\". hashables expression can evaluated context params. hash evaluated expression determines merge compatibility guides, stored params$hash. Methods: extract_key() Returns data.frame (mapped) breaks labels extracted scale, stored params$key. extract_decor() Returns data.frame containing structured information extracted scale, stored params$decor. decor guide-specific meaning: bar guide_colourbar(), specifies axis.line guide_axis(). extract_params() Updates params , unstructured information scale. example inheriting guide's title scale$name field. transform() Updates params$key based coordinates. applies position guides, rescales aesthetic [0, 1] range. merge() Combines information multiple guides params$hash. ensures e.g. guide_legend() can display shape colour guide. process_layers() Extract information layers. acts mostly filter layers include (typically) forwarded get_layer_key(). get_layer_key() can used gather information legend keys displayed. setup_params() Set parameters beginning drawing stages. can used overrule user-supplied parameters perform checks params property. override_elements() Take populated theme elements derived elements property allows overriding theme settings. build_title() Render guide's title. build_labels() Render guide's labels. build_decor() Render params$decor, different every guide. build_ticks() Render tick marks. measure_grobs() Measure dimensions graphical objects produced build_*() methods used layout assembly. arrange_layout() Set layout graphical objects produced build_*() methods arranged. assemble_drawing() Take graphical objects produced build_*() methods, measurements measure_grobs() layout arrange_layout() finalise guide. add_title Adds title gtable, taking account size title well gtable size.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"positions","dir":"Reference","previous_headings":"","what":"Positions","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"position_*() functions (like position_dodge()) return Position* object (like PositionDodge). Position* object responsible adjusting position overlapping geoms. way position_* functions work slightly different geom_* stat_* functions, position_* function actually \"instantiates\" Position* object creating descendant, returns . Position* objects ggproto() object, descended top-level Position, implements following methods: compute_layer(self, data, params, panel) called per layer. panel currently internal data structure, method overridden. compute_panel(self, data, params, scales) called per panel return modified data frame. data data frame containing variables named according aesthetics mapped . scales list containing x y scales. functions called facets trained, global scales, local individual panels. params contains parameters returned setup_params(). setup_params(data, params): called layer. Used setup defaults need complete dataset, inform user important choices. return list parameters. setup_data(data, params): called layer, setup_params(). return modified data. Default checks required aesthetics present. following fields required_aes: character vector giving aesthetics must present position adjustment work. See also new positions section online ggplot2 book.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-ggproto.html","id":"scales","dir":"Reference","previous_headings":"","what":"Scales","title":"Base ggproto classes for ggplot2 — ggplot2-ggproto","text":"scale_* functions like scale_x_continuous() return Scale* object like ScaleContinuous. Scale* objects ggproto() object, descended top-level Scale. Properties documented continuous_scale() discrete_scale(): call call continuous_scale() discrete_scale() constructed scale. range One continuous_range() discrete_range(). Methods: is_discrete() Returns TRUE scale discrete scale is_empty() Returns TRUE scale contains information (.e., information calculate limits). clone() Returns copy scale can trained independently without affecting original scale. transform() Transforms vector values using self$trans. occurs Stat calculated. train() Update self$range observed (transformed) data values vector (possibly) new values. reset() Reset self$range observed data values. discrete position scales, continuous range reset. map() Map transformed data values output value determined self$rescale() self$palette (except position scales, use default implementation method). output corresponds transformed data value aesthetic space (e.g., color, line width, size). rescale() Rescale transformed data range 0, 1. useful position scales. continuous scales, rescale() uses rescaler provided constructor. rescale() apply self$oob() input, means discrete values outside limits NA, values outside range values less 0 greater 1. allows guides control --bounds values displayed. transform_df(), train_df(), map_df() _df variants accept data frame, apply transform, train, map methods (respectively) columns whose names self$aesthetics. get_limits() Calculates final scale limits transformed data space based combination self$limits /range observed values (self$range). get_breaks() Calculates final scale breaks transformed data space based combination self$breaks, self$trans$breaks() (continuous scales), limits. Breaks outside limits assigned value NA (continuous scales) dropped (discrete scales). get_labels() Calculates labels given set (transformed) breaks based combination self$labels breaks. get_breaks_minor() continuous scales, calculates final scale minor breaks transformed data space based rescaled breaks, value self$minor_breaks, value self$trans$minor_breaks(). Discrete scales always return NULL. get_transformation() Returns scale's transformation object. make_title() Hook modify title calculated guide construction (non-position scales) Layout calculates x y labels (position scales). methods valid position (x y) scales: dimension() continuous scales, dimension concept limits. discrete scales, dimension() returns continuous range, limits placed integer positions. dimension() optionally expands range given expansion length 4 (see expansion()). break_info() Returns list() calculated values needed Coord transform values transformed data space. Axis grid guides also use values draw guides. called (usually expanded) continuous range, returned self$dimension() (even discrete scales). list components major_source (self$get_breaks() continuous scales, seq_along(self$get_breaks()) discrete scales), major (rescaled value major_source, ignoring self$rescaler), minor (rescaled value minor_source, ignoring self$rescaler), range (range passed break_info()), labels (label values, one element breaks). axis_order() One c(\"primary\", \"secondary\") c(\"secondary\", \"primary\") make_sec_title() Hook modify title second axis calculated Layout calculates x y labels.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-package.html","id":null,"dir":"Reference","previous_headings":"","what":"ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics — ggplot2-package","title":"ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics — ggplot2-package","text":"system 'declaratively' creating graphics, based \"Grammar Graphics\". provide data, tell 'ggplot2' map variables aesthetics, graphical primitives use, takes care details.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot2-package.html","id":"author","dir":"Reference","previous_headings":"","what":"Author","title":"ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics — ggplot2-package","text":"Maintainer: Thomas Lin Pedersen thomas.pedersen@posit.co (ORCID) Authors: Hadley Wickham hadley@posit.co (ORCID) Winston Chang (ORCID) Lionel Henry Kohske Takahashi Claus Wilke (ORCID) Kara Woo (ORCID) Hiroaki Yutani (ORCID) Dewey Dunnington (ORCID) Teun van den Brand (ORCID) contributors: Posit, PBC [copyright holder, funder]","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplotGrob.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate a ggplot2 plot grob. — ggplotGrob","title":"Generate a ggplot2 plot grob. — ggplotGrob","text":"Generate ggplot2 plot grob.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplotGrob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate a ggplot2 plot grob. — ggplotGrob","text":"","code":"ggplotGrob(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplotGrob.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate a ggplot2 plot grob. — ggplotGrob","text":"x ggplot2 object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":null,"dir":"Reference","previous_headings":"","what":"Add custom objects to ggplot — ggplot_add","title":"Add custom objects to ggplot — ggplot_add","text":"generic allows add methods adding custom objects ggplot +.gg.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Add custom objects to ggplot — ggplot_add","text":"","code":"ggplot_add(object, plot, object_name)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Add custom objects to ggplot — ggplot_add","text":"object object add plot plot ggplot object add object object_name name object add","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Add custom objects to ggplot — ggplot_add","text":"modified ggplot object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Add custom objects to ggplot — ggplot_add","text":"Custom methods ggplot_add() intended update plot variable using information custom object. can become convenient writing extensions build pre-existing grammar like layers, facets, coords themes. ggplot_add() function never intended used directly, triggered object added plot via + operator. Please note full plot object exposed point, comes responsibility returning plot intact.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_add.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Add custom objects to ggplot — ggplot_add","text":"","code":"# making a new method for the generic # in this example, we apply a text element to the text theme setting ggplot_add.element_text <- function(object, plot, object_name) { plot + theme(text = object) } # we can now use `+` to add our object to a plot ggplot(mpg, aes(displ, cty)) + geom_point() + element_text(colour = \"red\") #> Error in ggplot_add(object, p, objectname): Can't add `element_text(colour = \"red\")` to a object. # clean-up rm(ggplot_add.element_text)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":null,"dir":"Reference","previous_headings":"","what":"Build ggplot for rendering. — ggplot_build","title":"Build ggplot for rendering. — ggplot_build","text":"ggplot_build() takes plot object, performs steps necessary produce object can rendered. function outputs two pieces: list data frames (one layer), panel object, contain information axis limits, breaks etc.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Build ggplot for rendering. — ggplot_build","text":"","code":"ggplot_build(plot) get_layer_data(plot = get_last_plot(), i = 1L) layer_data(plot = get_last_plot(), i = 1L) get_panel_scales(plot = get_last_plot(), i = 1L, j = 1L) layer_scales(plot = get_last_plot(), i = 1L, j = 1L) get_layer_grob(plot = get_last_plot(), i = 1L) layer_grob(plot = get_last_plot(), i = 1L)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Build ggplot for rendering. — ggplot_build","text":"plot ggplot object integer. get_layer_data(), data return (order added plot). get_layer_grob(), grob return (order added plot). get_panel_scales(), row facet return scales . j integer. get_panel_scales(), column facet return scales .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_build.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Build ggplot for rendering. — ggplot_build","text":"get_layer_data(), get_layer_grob(), get_panel_scales() helper functions return data, grob, scales associated given layer. useful tests.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":null,"dir":"Reference","previous_headings":"","what":"Build a plot with all the usual bits and pieces. — ggplot_gtable","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"function builds grobs necessary displaying plot, stores special data structure called gtable(). object amenable programmatic manipulation, want (e.g.) make legend box 2 cm wide, combine multiple plots single display, preserving aspect ratios across plots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"","code":"ggplot_gtable(data)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"data plot data generated ggplot_build()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggplot_gtable.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Build a plot with all the usual bits and pieces. — ggplot_gtable","text":"gtable() object","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new ggproto object — ggproto","title":"Create a new ggproto object — ggproto","text":"Construct new object ggproto(), test .ggproto(), access parent methods/fields ggproto_parent().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new ggproto object — ggproto","text":"","code":"ggproto(`_class` = NULL, `_inherit` = NULL, ...) ggproto_parent(parent, self) is.ggproto(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new ggproto object — ggproto","text":"_class Class name assign object. stored class attribute object. optional: NULL (default), class name added object. _inherit ggproto object inherit . NULL, inherit object. ... list named members ggproto object. can functions become methods class regular objects. parent, self Access parent class parent object self. x object test.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create a new ggproto object — ggproto","text":"ggproto implements protype based OO system blurs lines classes instances. inspired proto package, important differences. Notably, cleanly supports cross-package inheritance, faster performance. cases, creating new OO system used single package good idea. However, least-bad solution ggplot2 required fewest changes already complex code base.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"calling-methods","dir":"Reference","previous_headings":"","what":"Calling methods","title":"Create a new ggproto object — ggproto","text":"ggproto methods can take optional self argument: present, regular method; absent, \"static\" method (.e. use fields). Imagine ggproto object Adder, method addx = function(self, n) n + self$x. , call function, use Adder$addx(10) – self passed automatically wrapper function. self located anywhere function signature, although customarily comes first.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"calling-methods-in-a-parent","dir":"Reference","previous_headings":"","what":"Calling methods in a parent","title":"Create a new ggproto object — ggproto","text":"explicitly call methods parent, use ggproto_parent(Parent, self).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"working-with-ggproto-classes","dir":"Reference","previous_headings":"","what":"Working with ggproto classes","title":"Create a new ggproto object — ggproto","text":"ggproto objects constructed build top environments, ramifications. Environments follow 'copy modify' semantics one might accustomed regular objects. Instead 'modify place' semantics.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggproto.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new ggproto object — ggproto","text":"","code":"Adder <- ggproto(\"Adder\", x = 0, add = function(self, n) { self$x <- self$x + n self$x } ) is.ggproto(Adder) #> [1] TRUE Adder$add(10) #> [1] 10 Adder$add(10) #> [1] 20 Doubler <- ggproto(\"Doubler\", Adder, add = function(self, n) { ggproto_parent(Adder, self)$add(n * 2) } ) Doubler$x #> [1] 20 Doubler$add(10) #> [1] 40"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":null,"dir":"Reference","previous_headings":"","what":"Save a ggplot (or other grid object) with sensible defaults — ggsave","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"ggsave() convenient function saving plot. defaults saving last plot displayed, using size current graphics device. also guesses type graphics device extension.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"","code":"ggsave( filename, plot = get_last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c(\"in\", \"cm\", \"mm\", \"px\"), dpi = 300, limitsize = TRUE, bg = NULL, create.dir = FALSE, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"filename File name create disk. plot Plot save, defaults last plot displayed. device Device use. Can either device function (e.g. png), one \"eps\", \"ps\", \"tex\" (pictex), \"pdf\", \"jpeg\", \"tiff\", \"png\", \"bmp\", \"svg\" \"wmf\" (windows ). NULL (default), device guessed based filename extension. path Path directory save plot : path filename combined create fully qualified file name. Defaults working directory. scale Multiplicative scaling factor. width, height Plot size units expressed units argument. supplied, uses size current graphics device. units One following units width height arguments expressed: \"\", \"cm\", \"mm\" \"px\". dpi Plot resolution. Also accepts string input: \"retina\" (320), \"print\" (300), \"screen\" (72). applies converting pixel units, typical raster output types. limitsize TRUE (default), ggsave() save images larger 50x50 inches, prevent common error specifying dimensions pixels. bg Background colour. NULL, uses plot.background fill value plot theme. create.dir Whether create new directories non-existing directory specified filename path (TRUE) return error (FALSE, default). FALSE run interactive session, prompt appear asking create new directory necessary. ... arguments passed graphics device function, specified device.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"Note: Filenames page numbers can generated including C integer format expression, %03d (default file name R graphics devices, see e.g. png()). Thus, filename = \"figure%03d.png\" produce successive filenames figure001.png, figure002.png, figure003.png, etc. write filename containing % sign, use %%. example, filename = \"figure-100%%.png\" produce filename figure-100%.png.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"saving-images-without-ggsave-","dir":"Reference","previous_headings":"","what":"Saving images without ggsave()","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"cases ggsave() simplest way save plot, sometimes may wish save plot writing directly graphics device. , can open regular R graphics device png() pdf(), print plot, close device using dev.(). technique illustrated examples section.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsave.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Save a ggplot (or other grid object) with sensible defaults — ggsave","text":"","code":"if (FALSE) { # \\dontrun{ ggplot(mtcars, aes(mpg, wt)) + geom_point() # here, the device is inferred from the filename extension ggsave(\"mtcars.pdf\") ggsave(\"mtcars.png\") # setting dimensions of the plot ggsave(\"mtcars.pdf\", width = 4, height = 4) ggsave(\"mtcars.pdf\", width = 20, height = 20, units = \"cm\") # passing device-specific arguments to '...' ggsave(\"mtcars.pdf\", colormodel = \"cmyk\") # delete files with base::unlink() unlink(\"mtcars.pdf\") unlink(\"mtcars.png\") # specify device when saving to a file with unknown extension # (for example a server supplied temporary file) file <- tempfile() ggsave(file, device = \"pdf\") unlink(file) # save plot to file without using ggsave p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() png(\"mtcars.png\") print(p) dev.off() } # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":null,"dir":"Reference","previous_headings":"","what":"Visualise sf objects — CoordSf","title":"Visualise sf objects — CoordSf","text":"set geom, stat, coord used visualise simple feature (sf) objects. simple plots, need geom_sf() uses stat_sf() adds coord_sf() . geom_sf() unusual geom draw different geometric objects depending simple features present data: can get points, lines, polygons. text labels, can use geom_sf_text() geom_sf_label().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Visualise sf objects — CoordSf","text":"","code":"coord_sf( xlim = NULL, ylim = NULL, expand = TRUE, crs = NULL, default_crs = NULL, datum = sf::st_crs(4326), label_graticule = waiver(), label_axes = waiver(), lims_method = \"cross\", ndiscr = 100, default = FALSE, clip = \"on\" ) geom_sf( mapping = aes(), data = NULL, stat = \"sf\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) geom_sf_label( mapping = aes(), data = NULL, stat = \"sf_coordinates\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, label.padding = unit(0.25, \"lines\"), label.r = unit(0.15, \"lines\"), label.size = 0.25, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, fun.geometry = NULL ) geom_sf_text( mapping = aes(), data = NULL, stat = \"sf_coordinates\", position = \"identity\", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, check_overlap = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, fun.geometry = NULL ) stat_sf( mapping = NULL, data = NULL, geom = \"rect\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Visualise sf objects — CoordSf","text":"xlim, ylim Limits x y axes. limits specified units default CRS. default, means projected coordinates (default_crs = NULL). limit specifications translate exact region shown plot can confusing non-linear rotated coordinate systems used default crs. First, different methods can preferable different conditions. See parameter lims_method details. Second, specifying limits along one direction can affect automatically generated limits along direction. Therefore, best always specify limits x y. Third, specifying limits via position scales xlim()/ylim() strongly discouraged, can result data points dropped plot even though visible final plot region. expand TRUE, default, adds small expansion factor limits ensure data axes overlap. FALSE, limits taken exactly data xlim/ylim. Giving logical vector separately control expansion four directions (top, left, bottom right). expand argument recycled length 4 necessary. Alternatively, can named logical vector control single direction, e.g. expand = c(bottom = FALSE). crs coordinate reference system (CRS) data projected plotting. specified, use CRS defined first sf layer plot. default_crs default CRS used non-sf layers (carry CRS information) scale limits. default value NULL means setting crs used. implies non-sf layers scale limits assumed specified projected coordinates. useful alternative setting default_crs = sf::st_crs(4326), means x y positions interpreted longitude latitude, respectively, World Geodetic System 1984 (WGS84). datum CRS provides datum use generating graticules. label_graticule Character vector indicating graticule lines labeled . Meridians run north-south, letters \"N\" \"S\" indicate labeled north south end points, respectively. Parallels run east-west, letters \"E\" \"W\" indicate labeled east west end points, respectively. Thus, label_graticule = \"SW\" label meridians south end parallels west end, whereas label_graticule = \"EW\" label parallels ends meridians . meridians parallels can general intersect side plot panel, choice label_graticule labels guaranteed reside one particular side plot panel. Also, label_graticule can cause labeling artifacts, particular graticule line coincides edge plot panel. circumstances, label_axes generally yield better results used instead. parameter can used alone combination label_axes. label_axes Character vector named list character values specifying graticule lines (meridians parallels) labeled side plot. Meridians indicated \"E\" (East) parallels \"N\" (North). Default \"--EN\", specifies (clockwise top) labels top, none right, meridians bottom, parallels left. Alternatively, setting specified list(bottom = \"E\", left = \"N\"). parameter can used alone combination label_graticule. lims_method Method specifying scale limits converted limits plot region. effect default_crs = NULL. non-linear CRS (e.g., perspective centered around North pole), available methods yield widely differing results, may want try various options. Methods currently implemented include \"cross\" (default), \"box\", \"orthogonal\", \"geometry_bbox\". method \"cross\", limits along one direction (e.g., longitude) applied midpoint direction (e.g., latitude). method avoids excessively large limits rotated coordinate systems means sometimes limits need expanded little extreme data points included final plot region. contrast, method \"box\", box generated limits along directions, limits projected coordinates chosen entire box visible. method can yield plot regions large. Finally, method \"orthogonal\" applies limits separately along axis, method \"geometry_bbox\" ignores limit information except bounding boxes objects geometry aesthetic. ndiscr Number segments use discretising graticule lines; try increasing number graticules look incorrect. default default coordinate system? FALSE (default), replacing coordinate system another one creates message alerting user coordinate system replaced. TRUE, warning suppressed. clip drawing clipped extent plot panel? setting \"\" (default) means yes, setting \"\" means . cases, default \"\" changed, setting clip = \"\" can cause unexpected results. allows drawing data points anywhere plot, including plot margins. limits set via xlim ylim data points fall outside limits, data points may show places axes, legend, plot title, plot margins. mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also set one \"polygon\", \"line\", \"point\" override default legend. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. parse TRUE, labels parsed expressions displayed described ?plotmath. nudge_x, nudge_y Horizontal vertical adjustment nudge labels . Useful offsetting text points, particularly discrete scales. jointly specified position. label.padding Amount padding around label. Defaults 0.25 lines. label.r Radius rounded corners. Defaults 0.15 lines. label.size Size label border, mm. fun.geometry function takes sfc object returns sfc_POINT length input. NULL, function(x) sf::st_point_on_surface(sf::st_zm(x)) used. Note function may warn incorrectness result data projected, can ignore except really care exact locations. check_overlap TRUE, text overlaps previous text layer plotted. check_overlap happens draw time order data. Therefore data arranged label column calling geom_text(). Note argument supported geom_label(). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"geometry-aesthetic","dir":"Reference","previous_headings":"","what":"Geometry aesthetic","title":"Visualise sf objects — CoordSf","text":"geom_sf() uses unique aesthetic: geometry, giving column class sfc containing simple features data. three ways supply geometry aesthetic: nothing: default geom_sf() assumes stored geometry column. Explicitly pass sf object data argument. use primary geometry column, matter called. Supply using aes(geometry = my_column) Unlike aesthetics, geometry never inherited plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"crs","dir":"Reference","previous_headings":"","what":"CRS","title":"Visualise sf objects — CoordSf","text":"coord_sf() ensures layers use common CRS. can either specify using crs param, coord_sf() take first layer defines CRS.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"combining-sf-layers-and-regular-geoms","dir":"Reference","previous_headings":"","what":"Combining sf layers and regular geoms","title":"Visualise sf objects — CoordSf","text":"regular geoms, geom_point(), geom_path(), geom_text(), geom_polygon() etc. work fine coord_sf(). However using geoms, two problems arise. First, CRS used x y coordinates used non-sf geoms? CRS applied non-sf geoms set default_crs parameter, defaults NULL, means positions non-sf geoms interpreted projected coordinates coordinate system set crs parameter. setting allows complete control exactly items placed plot canvas, may require understanding projections work generate data projected coordinates. alternative, can set default_crs = sf::st_crs(4326), World Geodetic System 1984 (WGS84). means x y positions interpreted longitude latitude, respectively. can also specify valid CRS default CRS non-sf geoms. second problem arises non-sf geoms straight lines interpreted projected space default_crs set NULL. approach coord_sf() takes break straight lines small pieces (.e., segmentize ) transform pieces projected coordinates. default setting x y interpreted longitude latitude, approach means horizontal lines follow parallels vertical lines follow meridians. need different approach handling straight lines, manually segmentize project coordinates generate plot projected coordinates.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggsf.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Visualise sf objects — CoordSf","text":"","code":"if (requireNamespace(\"sf\", quietly = TRUE)) { nc <- sf::st_read(system.file(\"shape/nc.shp\", package = \"sf\"), quiet = TRUE) ggplot(nc) + geom_sf(aes(fill = AREA)) # If not supplied, coord_sf() will take the CRS from the first layer # and automatically transform all other layers to use that CRS. This # ensures that all data will correctly line up nc_3857 <- sf::st_transform(nc, 3857) ggplot() + geom_sf(data = nc) + geom_sf(data = nc_3857, colour = \"red\", fill = NA) # Unfortunately if you plot other types of feature you'll need to use # show.legend to tell ggplot2 what type of legend to use nc_3857$mid <- sf::st_centroid(nc_3857$geometry) ggplot(nc_3857) + geom_sf(colour = \"white\") + geom_sf(aes(geometry = mid, size = AREA), show.legend = \"point\") # You can also use layers with x and y aesthetics. To have these interpreted # as longitude/latitude you need to set the default CRS in coord_sf() ggplot(nc_3857) + geom_sf() + annotate(\"point\", x = -80, y = 35, colour = \"red\", size = 4) + coord_sf(default_crs = sf::st_crs(4326)) # To add labels, use geom_sf_label(). ggplot(nc_3857[1:3, ]) + geom_sf(aes(fill = AREA)) + geom_sf_label(aes(label = NAME)) } # Thanks to the power of sf, a geom_sf nicely handles varying projections # setting the aspect ratio correctly. if (requireNamespace('maps', quietly = TRUE)) { library(maps) world1 <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE)) ggplot() + geom_sf(data = world1) world2 <- sf::st_transform( world1, \"+proj=laea +y_0=0 +lon_0=155 +lat_0=-90 +ellps=WGS84 +no_defs\" ) ggplot() + geom_sf(data = world2) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":null,"dir":"Reference","previous_headings":"","what":"Complete themes — ggtheme","title":"Complete themes — ggtheme","text":"complete themes control non-data display. Use theme() just need tweak display existing theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Complete themes — ggtheme","text":"","code":"theme_grey( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_gray( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_bw( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_linedraw( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_light( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_dark( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_minimal( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_classic( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_void( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_test( base_size = 11, base_family = \"\", header_family = NULL, base_line_size = base_size/22, base_rect_size = base_size/22 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Complete themes — ggtheme","text":"base_size base font size, given pts. base_family base font family header_family font family titles headers. default, NULL, uses theme inheritance set font. setting affects axis titles, legend titles, plot title tag text. base_line_size base size line elements base_rect_size base size rect elements","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Complete themes — ggtheme","text":"theme_gray() signature ggplot2 theme grey background white gridlines, designed put data forward yet make comparisons easy. theme_bw() classic dark--light ggplot2 theme. May work better presentations displayed projector. theme_linedraw() theme black lines various widths white backgrounds, reminiscent line drawing. Serves purpose similar theme_bw(). Note theme thin lines (<< 1 pt) journals may refuse. theme_light() theme similar theme_linedraw() light grey lines axes, direct attention towards data. theme_dark() dark cousin theme_light(), similar line sizes dark background. Useful make thin coloured lines pop . theme_minimal() minimalistic theme background annotations. theme_classic() classic-looking theme, x y axis lines gridlines. theme_void() completely empty theme. theme_test() theme visual unit tests. ideally never change except new features.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/ggtheme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Complete themes — ggtheme","text":"","code":"mtcars2 <- within(mtcars, { vs <- factor(vs, labels = c(\"V-shaped\", \"Straight\")) am <- factor(am, labels = c(\"Automatic\", \"Manual\")) cyl <- factor(cyl) gear <- factor(gear) }) p1 <- ggplot(mtcars2) + geom_point(aes(x = wt, y = mpg, colour = gear)) + labs( title = \"Fuel economy declines as weight increases\", subtitle = \"(1973-74)\", caption = \"Data from the 1974 Motor Trend US magazine.\", tag = \"Figure 1\", x = \"Weight (1000 lbs)\", y = \"Fuel economy (mpg)\", colour = \"Gears\" ) p1 + theme_gray() # the default p1 + theme_bw() p1 + theme_linedraw() p1 + theme_light() p1 + theme_dark() p1 + theme_minimal() p1 + theme_classic() p1 + theme_void() # Theme examples with panels # \\donttest{ p2 <- p1 + facet_grid(vs ~ am) p2 + theme_gray() # the default p2 + theme_bw() p2 + theme_linedraw() p2 + theme_light() p2 + theme_dark() p2 + theme_minimal() p2 + theme_classic() p2 + theme_void() # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/graphical-units.html","id":null,"dir":"Reference","previous_headings":"","what":"Graphical units — graphical-units","title":"Graphical units — graphical-units","text":"Multiply size mm constants order convert units grid uses internally lwd fontsize.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/graphical-units.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Graphical units — graphical-units","text":"","code":".pt .stroke"},{"path":"https://ggplot2.tidyverse.org/dev/reference/graphical-units.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Graphical units — graphical-units","text":"object class numeric length 1. object class numeric length 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":null,"dir":"Reference","previous_headings":"","what":"Axis guide — guide_axis","title":"Axis guide — guide_axis","text":"Axis guides visual representation position scales like created scale_(x|y)_continuous() scale_(x|y)_discrete().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Axis guide — guide_axis","text":"","code":"guide_axis( title = waiver(), theme = NULL, check.overlap = FALSE, angle = waiver(), n.dodge = 1, minor.ticks = FALSE, cap = \"none\", order = 0, position = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Axis guide — guide_axis","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. check.overlap silently remove overlapping labels, (recursively) prioritizing first, last, middle labels. angle Compared setting angle theme() / element_text(), also uses heuristics automatically pick hjust vjust probably want. Can one following: NULL take angles hjust/vjust directly theme. waiver() allow reasonable defaults special cases. number representing text angle degrees. n.dodge number rows (vertical axes) columns (horizontal axes) used render labels. useful displaying labels otherwise overlap. minor.ticks Whether draw minor ticks (TRUE) draw minor ticks (FALSE, default). cap character cut axis line back last breaks. Can \"none\" (default) draw axis line along whole panel, \"upper\" \"lower\" draw axis upper lower break, \"\" draw line extreme breaks. TRUE FALSE shorthand \"\" \"none\" respectively. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Axis guide — guide_axis","text":"","code":"# plot with overlapping text p <- ggplot(mpg, aes(cty * 100, hwy * 100)) + geom_point() + facet_wrap(vars(class)) # axis guides can be customized in the scale_* functions or # using guides() p + scale_x_continuous(guide = guide_axis(n.dodge = 2)) p + guides(x = guide_axis(angle = 90)) # can also be used to add a duplicate guide p + guides(x = guide_axis(n.dodge = 2), y.sec = guide_axis())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":null,"dir":"Reference","previous_headings":"","what":"Axis with logarithmic tick marks — guide_axis_logticks","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"axis guide replaces placement ticks marks intervals log10 space.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"","code":"guide_axis_logticks( long = 2.25, mid = 1.5, short = 0.75, prescale.base = NULL, negative.small = 0.1, short.theme = element_line(), expanded = TRUE, cap = \"none\", theme = NULL, prescale_base = deprecated(), negative_small = deprecated(), short_theme = deprecated(), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"long, mid, short grid::unit() object rel() object setting (relative) length long, middle short ticks. Numeric values interpreted rel() objects. rel() values used multiply values axis.ticks.length theme setting. prescale.base Base logarithm used transform data manually. default, NULL, use scale transformation calculate positions. set prescale.base data already log-transformed. using log-transform position scale coord_trans(), keep default NULL argument. negative.small scale limits include 0 negative numbers, smallest absolute value marked tick? short.theme theme element customising display shortest ticks. Must line blank element, inherits axis.minor.ticks setting relevant position. expanded Whether ticks cover range scale expansion (TRUE, default), restricted scale limits (FALSE). cap character cut axis line back last breaks. Can \"none\" (default) draw axis line along whole panel, \"upper\" \"lower\" draw axis upper lower break, \"\" draw line extreme breaks. TRUE FALSE shorthand \"\" \"none\" respectively. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. prescale_base, negative_small, short_theme ... Arguments passed guide_axis check.overlap silently remove overlapping labels, (recursively) prioritizing first, last, middle labels. angle Compared setting angle theme() / element_text(), also uses heuristics automatically pick hjust vjust probably want. Can one following: NULL take angles hjust/vjust directly theme. waiver() allow reasonable defaults special cases. number representing text angle degrees. n.dodge number rows (vertical axes) columns (horizontal axes) used render labels. useful displaying labels otherwise overlap. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right. title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_logticks.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Axis with logarithmic tick marks — guide_axis_logticks","text":"","code":"# A standard plot p <- ggplot(msleep, aes(bodywt, brainwt)) + geom_point(na.rm = TRUE) # The logticks axis works well with log scales p + scale_x_log10(guide = \"axis_logticks\") + scale_y_log10(guide = \"axis_logticks\") # Or with log-transformed coordinates p + coord_trans(x = \"log10\", y = \"log10\") + guides(x = \"axis_logticks\", y = \"axis_logticks\") # When data is transformed manually, one should provide `prescale.base` # Keep in mind that this axis uses log10 space for placement, not log2 p + aes(x = log2(bodywt), y = log10(brainwt)) + guides( x = guide_axis_logticks(prescale.base = 2), y = guide_axis_logticks(prescale.base = 10) ) # A plot with both positive and negative extremes, pseudo-log transformed set.seed(42) p2 <- ggplot(data.frame(x = rcauchy(1000)), aes(x = x)) + geom_density() + scale_x_continuous( breaks = c(-10^(4:0), 0, 10^(0:4)), transform = \"pseudo_log\" ) # The log ticks are mirrored when 0 is included p2 + guides(x = \"axis_logticks\") # To control the tick density around 0, one can set `negative.small` p2 + guides(x = guide_axis_logticks(negative.small = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":null,"dir":"Reference","previous_headings":"","what":"Stacked axis guides — guide_axis_stack","title":"Stacked axis guides — guide_axis_stack","text":"guide can stack position guides represent position scales, like created scale_(x|y)_continuous() scale_(x|y)_discrete().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Stacked axis guides — guide_axis_stack","text":"","code":"guide_axis_stack( first = \"axis\", ..., title = waiver(), theme = NULL, spacing = NULL, order = 0, position = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Stacked axis guides — guide_axis_stack","text":"first position guide given one following: string, example \"axis\". call guide function, example guide_axis(). ... Additional guides stack given manner first. title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. spacing unit() objects determines far separate guides spaced apart. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Stacked axis guides — guide_axis_stack","text":"first guide placed closest panel subsequent guides provided ... follow given order.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_stack.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Stacked axis guides — guide_axis_stack","text":"","code":"#' # A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() + theme(axis.line = element_line()) # A normal axis first, then a capped axis p + guides(x = guide_axis_stack(\"axis\", guide_axis(cap = \"both\")))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":null,"dir":"Reference","previous_headings":"","what":"Angle axis guide — guide_axis_theta","title":"Angle axis guide — guide_axis_theta","text":"specialised guide used coord_radial() represent theta position scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Angle axis guide — guide_axis_theta","text":"","code":"guide_axis_theta( title = waiver(), theme = NULL, angle = waiver(), minor.ticks = FALSE, cap = \"none\", order = 0, position = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Angle axis guide — guide_axis_theta","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. angle Compared setting angle theme() / element_text(), also uses heuristics automatically pick hjust vjust probably want. Can one following: NULL take angles hjust/vjust directly theme. waiver() allow reasonable defaults special cases. number representing text angle degrees. minor.ticks Whether draw minor ticks (TRUE) draw minor ticks (FALSE, default). cap character cut axis line back last breaks. Can \"none\" (default) draw axis line along whole panel, \"upper\" \"lower\" draw axis upper lower break, \"\" draw line extreme breaks. TRUE FALSE shorthand \"\" \"none\" respectively. order positive integer length 1 specifies order guide among multiple guides. controls order guides merged multiple guides position. 0 (default), order determined secret algorithm. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Angle axis guide — guide_axis_theta","text":"axis labels guide insensitive hjust vjust settings. distance tick marks labels determined largest margin size set theme.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_axis_theta.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Angle axis guide — guide_axis_theta","text":"","code":"# A plot using coord_radial p <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + coord_radial() # The `angle` argument can be used to set relative angles p + guides(theta = guide_axis_theta(angle = 0))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":null,"dir":"Reference","previous_headings":"","what":"A binned version of guide_legend — guide_bins","title":"A binned version of guide_legend — guide_bins","text":"guide version guide_legend() guide binned scales. differs places ticks correctly keys, sports small axis better show binning. Like guide_legend() can used non-position aesthetics though colour fill defaults guide_coloursteps(), merge aesthetics together guide mapped way.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A binned version of guide_legend — guide_bins","text":"","code":"guide_bins( title = waiver(), theme = NULL, position = NULL, direction = NULL, override.aes = list(), reverse = FALSE, order = 0, show.limits = NULL, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A binned version of guide_legend — guide_bins","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. position character string indicating legend placed relative plot panels. direction character string indicating direction guide. One \"horizontal\" \"vertical\". override.aes list specifying aesthetic parameters legend key. See details examples. reverse logical. TRUE order legends reversed. order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. show.limits Logical. limits scale shown labels ticks. Default NULL meaning take value scale. argument ignored labels given vector values. one limits also given breaks shown irrespective value show.limits. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"A binned version of guide_legend — guide_bins","text":"guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"use-with-discrete-scale","dir":"Reference","previous_headings":"","what":"Use with discrete scale","title":"A binned version of guide_legend — guide_bins","text":"guide intended show binned data work together ggplot2's binning scales. However, sometimes desirable perform binning separate step, either part stat (e.g. stat_contour_filled()) prior visualisation. want use guide discrete data levels must follow naming scheme implemented base::cut(). means bin must encoded \"(, ]\" giving lower bound bin giving upper bound (\"[, )\" also accepted). use base::cut() perform binning everything work expected, , recoding may needed.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_bins.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A binned version of guide_legend — guide_bins","text":"","code":"p <- ggplot(mtcars) + geom_point(aes(disp, mpg, size = hp)) + scale_size_binned() # Standard look p # Remove the axis or style it p + guides(size = guide_bins( theme = theme(legend.axis.line = element_blank()) )) p + guides(size = guide_bins(show.limits = TRUE)) my_arrow <- arrow(length = unit(1.5, \"mm\"), ends = \"both\") p + guides(size = guide_bins( theme = theme(legend.axis.line = element_line(arrow = my_arrow)) )) # Guides are merged together if possible ggplot(mtcars) + geom_point(aes(disp, mpg, size = hp, colour = hp)) + scale_size_binned() + scale_colour_binned(guide = \"bins\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":null,"dir":"Reference","previous_headings":"","what":"Continuous colour bar guide — guide_colourbar","title":"Continuous colour bar guide — guide_colourbar","text":"Colour bar guide shows continuous colour scales mapped onto values. Colour bar available scale_fill scale_colour. information, see inspiration function: Matlab's colorbar function.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Continuous colour bar guide — guide_colourbar","text":"","code":"guide_colourbar( title = waiver(), theme = NULL, nbin = NULL, display = \"raster\", raster = deprecated(), alpha = NA, draw.ulim = TRUE, draw.llim = TRUE, position = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... ) guide_colorbar( title = waiver(), theme = NULL, nbin = NULL, display = \"raster\", raster = deprecated(), alpha = NA, draw.ulim = TRUE, draw.llim = TRUE, position = NULL, direction = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Continuous colour bar guide — guide_colourbar","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. nbin numeric specifying number bins drawing colourbar. smoother colourbar results larger value. display string indicating method display colourbar. Can one following: \"raster\" display bitmap image. \"rectangles\" display series rectangles. \"gradient\" display linear gradient. Note devices able render rasters gradients. raster logical. TRUE colourbar rendered raster object. FALSE colourbar rendered set rectangles. Note graphics devices capable rendering raster image. alpha numeric 0 1 setting colour transparency bar. Use NA preserve alpha encoded colour (default). draw.ulim logical specifying upper limit tick marks visible. draw.llim logical specifying lower limit tick marks visible. position character string indicating legend placed relative plot panels. direction character string indicating direction guide. One \"horizontal\" \"vertical.\" reverse logical. TRUE colourbar reversed. default, highest value top lowest value bottom order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. available_aes vector character strings listing aesthetics colourbar can drawn. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Continuous colour bar guide — guide_colourbar","text":"guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Continuous colour bar guide — guide_colourbar","text":"Guides can specified scale_* guides(). guide=\"legend\" scale_* syntactic sugar guide=guide_legend() (e.g. scale_colour_manual(guide = \"legend\")). specify guide scale detail, see guides().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_colourbar.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Continuous colour bar guide — guide_colourbar","text":"","code":"df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) p2 <- p1 + geom_point(aes(size = value)) # Basic form p1 + scale_fill_continuous(guide = \"colourbar\") p1 + scale_fill_continuous(guide = guide_colourbar()) p1 + guides(fill = guide_colourbar()) # Control styles # bar size p1 + guides(fill = guide_colourbar(theme = theme( legend.key.width = unit(0.5, \"lines\"), legend.key.height = unit(10, \"lines\") ))) # no label p1 + guides(fill = guide_colourbar(theme = theme( legend.text = element_blank() ))) # no tick marks p1 + guides(fill = guide_colourbar(theme = theme( legend.ticks = element_blank() ))) # label position p1 + guides(fill = guide_colourbar(theme = theme( legend.text.position = \"left\" ))) # label theme p1 + guides(fill = guide_colourbar(theme = theme( legend.text = element_text(colour = \"blue\", angle = 0) ))) # small number of bins p1 + guides(fill = guide_colourbar(nbin = 3)) # large number of bins p1 + guides(fill = guide_colourbar(nbin = 100)) # make top- and bottom-most ticks invisible p1 + scale_fill_continuous( limits = c(0,20), breaks = c(0, 5, 10, 15, 20), guide = guide_colourbar(nbin = 100, draw.ulim = FALSE, draw.llim = FALSE) ) # guides can be controlled independently p2 + scale_fill_continuous(guide = \"colourbar\") + scale_size(guide = \"legend\") p2 + guides(fill = \"colourbar\", size = \"legend\") p2 + scale_fill_continuous(guide = guide_colourbar(theme = theme( legend.direction = \"horizontal\" ))) + scale_size(guide = guide_legend(theme = theme( legend.direction = \"vertical\" )))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":null,"dir":"Reference","previous_headings":"","what":"Discretized colourbar guide — guide_coloursteps","title":"Discretized colourbar guide — guide_coloursteps","text":"guide version guide_colourbar() binned colour fill scales. shows areas breaks single constant colour instead gradient known colourbar counterpart.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discretized colourbar guide — guide_coloursteps","text":"","code":"guide_coloursteps( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, position = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... ) guide_colorsteps( title = waiver(), theme = NULL, alpha = NA, even.steps = TRUE, show.limits = NULL, direction = NULL, position = NULL, reverse = FALSE, order = 0, available_aes = c(\"colour\", \"color\", \"fill\"), ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discretized colourbar guide — guide_coloursteps","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. alpha numeric 0 1 setting colour transparency bar. Use NA preserve alpha encoded colour (default). even.steps rendered size bins equal, proportional length data space? Defaults TRUE show.limits Logical. limits scale shown labels ticks. Default NULL meaning take value scale. argument ignored labels given vector values. one limits also given breaks shown irrespective value show.limits. direction character string indicating direction guide. One \"horizontal\" \"vertical.\" position character string indicating legend placed relative plot panels. reverse logical. TRUE colourbar reversed. default, highest value top lowest value bottom order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. available_aes vector character strings listing aesthetics colourbar can drawn. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Discretized colourbar guide — guide_coloursteps","text":"guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"use-with-discrete-scale","dir":"Reference","previous_headings":"","what":"Use with discrete scale","title":"Discretized colourbar guide — guide_coloursteps","text":"guide intended show binned data work together ggplot2's binning scales. However, sometimes desirable perform binning separate step, either part stat (e.g. stat_contour_filled()) prior visualisation. want use guide discrete data levels must follow naming scheme implemented base::cut(). means bin must encoded \"(, ]\" giving lower bound bin giving upper bound (\"[, )\" also accepted). use base::cut() perform binning everything work expected, , recoding may needed.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_coloursteps.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Discretized colourbar guide — guide_coloursteps","text":"","code":"df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 p <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) # Coloursteps guide is the default for binned colour scales p + scale_fill_binned() # By default each bin in the guide is the same size irrespectively of how # their sizes relate in data space p + scale_fill_binned(breaks = c(10, 25, 50)) # This can be changed with the `even.steps` argument p + scale_fill_binned( breaks = c(10, 25, 50), guide = guide_coloursteps(even.steps = FALSE) ) # By default the limits is not shown, but this can be changed p + scale_fill_binned(guide = guide_coloursteps(show.limits = TRUE)) # (can also be set in the scale) p + scale_fill_binned(show.limits = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":null,"dir":"Reference","previous_headings":"","what":"Custom guides — guide_custom","title":"Custom guides — guide_custom","text":"special guide can used display graphical object (grob) along regular guides. guide associated scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Custom guides — guide_custom","text":"","code":"guide_custom( grob, width = grobWidth(grob), height = grobHeight(grob), title = NULL, theme = NULL, position = NULL, order = 0 )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Custom guides — guide_custom","text":"grob grob display. width, height allocated width height display grob, given grid::unit()s. title character string expression indicating title guide. NULL (default), title shown. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. position character string indicating legend placed relative plot panels. order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_custom.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Custom guides — guide_custom","text":"","code":"# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Define a graphical object circle <- grid::circleGrob() # Rendering a grob as a guide p + guides(custom = guide_custom(circle, title = \"My circle\")) # Controlling the size of the grob defined in relative units p + guides(custom = guide_custom( circle, title = \"My circle\", width = unit(2, \"cm\"), height = unit(2, \"cm\")) ) # Size of grobs in absolute units is taken directly without the need to # set these manually p + guides(custom = guide_custom( title = \"My circle\", grob = grid::circleGrob(r = unit(1, \"cm\")) ))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":null,"dir":"Reference","previous_headings":"","what":"Legend guide — guide_legend","title":"Legend guide — guide_legend","text":"Legend type guide shows key (.e., geoms) mapped onto values. Legend guides various scales integrated possible.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Legend guide — guide_legend","text":"","code":"guide_legend( title = waiver(), theme = NULL, position = NULL, direction = NULL, override.aes = list(), nrow = NULL, ncol = NULL, reverse = FALSE, order = 0, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Legend guide — guide_legend","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. theme theme object style guide individually differently plot's theme settings. theme argument guide overrides, combined , plot's theme. position character string indicating legend placed relative plot panels. direction character string indicating direction guide. One \"horizontal\" \"vertical\". override.aes list specifying aesthetic parameters legend key. See details examples. nrow, ncol desired number rows column legends respectively. reverse logical. TRUE order legends reversed. order positive integer less 99 specifies order guide among multiple guides. controls order multiple guides displayed, contents guide . 0 (default), order determined secret algorithm. ... ignored.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Legend guide — guide_legend","text":"Guides can specified scale_* guides(). guide = \"legend\" scale_* syntactic sugar guide = guide_legend() (e.g. scale_color_manual(guide = \"legend\")). specify guide scale detail, see guides().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_legend.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Legend guide — guide_legend","text":"","code":"# \\donttest{ df <- expand.grid(X1 = 1:10, X2 = 1:10) df$value <- df$X1 * df$X2 p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value)) p2 <- p1 + geom_point(aes(size = value)) # Basic form p1 + scale_fill_continuous(guide = guide_legend()) # Control styles # title position p1 + guides(fill = guide_legend( title = \"LEFT\", theme(legend.title.position = \"left\") )) # title text styles via element_text p1 + guides(fill = guide_legend(theme = theme( legend.title = element_text(size = 15, face = \"italic\", colour = \"red\") ))) # label position p1 + guides(fill = guide_legend(theme = theme( legend.text.position = \"left\", legend.text = element_text(hjust = 1) ))) # label styles p1 + scale_fill_continuous( breaks = c(5, 10, 15), labels = paste(\"long\", c(5, 10, 15)), guide = guide_legend(theme = theme( legend.direction = \"horizontal\", legend.title.position = \"top\", legend.text.position = \"bottom\", legend.text = element_text(hjust = 0.5, vjust = 1, angle = 90) )) ) # Set aesthetic of legend key # very low alpha value make it difficult to see legend key p3 <- ggplot(mtcars, aes(vs, am, colour = factor(cyl))) + geom_jitter(alpha = 1/5, width = 0.01, height = 0.01) p3 # override.aes overwrites the alpha p3 + guides(colour = guide_legend(override.aes = list(alpha = 1))) # multiple row/col legends df <- data.frame(x = 1:20, y = 1:20, color = letters[1:20]) p <- ggplot(df, aes(x, y)) + geom_point(aes(colour = color)) p + guides(col = guide_legend(nrow = 8)) p + guides(col = guide_legend(ncol = 8)) p + guides(col = guide_legend(nrow = 8, theme = theme(legend.byrow = TRUE))) # reversed order legend p + guides(col = guide_legend(reverse = TRUE)) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_none.html","id":null,"dir":"Reference","previous_headings":"","what":"Empty guide — guide_none","title":"Empty guide — guide_none","text":"guide draws nothing.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_none.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Empty guide — guide_none","text":"","code":"guide_none(title = waiver(), position = waiver())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guide_none.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Empty guide — guide_none","text":"title character string expression indicating title guide. NULL, title shown. default (waiver()), name scale object name specified labs() used title. position guide drawn: one top, bottom, left, right.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":null,"dir":"Reference","previous_headings":"","what":"Set guides for each scale — guides","title":"Set guides for each scale — guides","text":"Guides scale can set scale--scale guide argument, en masse guides().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set guides for each scale — guides","text":"","code":"guides(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set guides for each scale — guides","text":"... List scale name-guide pairs. guide can either string (.e. \"colorbar\" \"legend\"), call guide function (.e. guide_colourbar() guide_legend()) specifying additional arguments.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Set guides for each scale — guides","text":"list containing mapping scale guide.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/guides.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set guides for each scale — guides","text":"","code":"# \\donttest{ # ggplot object dat <- data.frame(x = 1:5, y = 1:5, p = 1:5, q = factor(1:5), r = factor(1:5)) p <- ggplot(dat, aes(x, y, colour = p, size = q, shape = r)) + geom_point() # without guide specification p #> Warning: Using size for a discrete variable is not advised. # Show colorbar guide for colour. # All these examples below have a same effect. p + guides(colour = \"colorbar\", size = \"legend\", shape = \"legend\") #> Warning: Using size for a discrete variable is not advised. p + guides(colour = guide_colorbar(), size = guide_legend(), shape = guide_legend()) #> Warning: Using size for a discrete variable is not advised. p + scale_colour_continuous(guide = \"colorbar\") + scale_size_discrete(guide = \"legend\") + scale_shape(guide = \"legend\") #> Warning: Using size for a discrete variable is not advised. # Remove some guides p + guides(colour = \"none\") #> Warning: Using size for a discrete variable is not advised. p + guides(colour = \"colorbar\",size = \"none\") #> Warning: Using size for a discrete variable is not advised. # Guides are integrated where possible p + guides( colour = guide_legend(\"title\"), size = guide_legend(\"title\"), shape = guide_legend(\"title\") ) #> Warning: Using size for a discrete variable is not advised. # same as g <- guide_legend(\"title\") p + guides(colour = g, size = g, shape = g) #> Warning: Using size for a discrete variable is not advised. p + theme(legend.position = \"bottom\") #> Warning: Using size for a discrete variable is not advised. # position of guides # Set order for multiple guides ggplot(mpg, aes(displ, cty)) + geom_point(aes(size = hwy, colour = cyl, shape = drv)) + guides( colour = guide_colourbar(order = 1), shape = guide_legend(order = 2), size = guide_legend(order = 3) ) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":null,"dir":"Reference","previous_headings":"","what":"A selection of summary functions from Hmisc — hmisc","title":"A selection of summary functions from Hmisc — hmisc","text":"wrappers around functions Hmisc designed make easier use stat_summary(). See Hmisc documentation details: Hmisc::smean.cl.boot() Hmisc::smean.cl.normal() Hmisc::smean.sdl() Hmisc::smedian.hilow()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A selection of summary functions from Hmisc — hmisc","text":"","code":"mean_cl_boot(x, ...) mean_cl_normal(x, ...) mean_sdl(x, ...) median_hilow(x, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"A selection of summary functions from Hmisc — hmisc","text":"x numeric vector ... arguments passed respective Hmisc function.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"A selection of summary functions from Hmisc — hmisc","text":"data frame columns y, ymin, ymax.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/hmisc.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"A selection of summary functions from Hmisc — hmisc","text":"","code":"if (requireNamespace(\"Hmisc\", quietly = TRUE)) { set.seed(1) x <- rnorm(100) mean_cl_boot(x) mean_cl_normal(x) mean_sdl(x) median_hilow(x) } #> y ymin ymax #> 1 0.1139092 -1.671298 1.797468"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":null,"dir":"Reference","previous_headings":"","what":"Ignoring and exposing data — ignoring_data","title":"Ignoring and exposing data — ignoring_data","text":".ignore_data() function used hide columns scale interactions ggplot_build(). .expose_data() function used restore hidden columns.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Ignoring and exposing data — ignoring_data","text":"","code":".ignore_data(data) .expose_data(data)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Ignoring and exposing data — ignoring_data","text":"data list s.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Ignoring and exposing data — ignoring_data","text":"modified list s","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/ignoring_data.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Ignoring and exposing data — ignoring_data","text":"","code":"data <- list( data.frame(x = 1:3, y = I(1:3)), data.frame(w = I(1:3), z = 1:3) ) ignored <- .ignore_data(data) str(ignored) #> List of 2 #> $ :'data.frame':\t3 obs. of 2 variables: #> ..$ x : int [1:3] 1 2 3 #> ..$ .ignored:'data.frame':\t3 obs. of 1 variable: #> .. ..$ y: 'AsIs' int [1:3] 1 2 3 #> $ :'data.frame':\t3 obs. of 2 variables: #> ..$ z : int [1:3] 1 2 3 #> ..$ .ignored:'data.frame':\t3 obs. of 1 variable: #> .. ..$ w: 'AsIs' int [1:3] 1 2 3 .expose_data(ignored) #> [[1]] #> x y #> 1 1 1 #> 2 2 2 #> 3 3 3 #> #> [[2]] #> z w #> 1 1 1 #> 2 2 2 #> 3 3 3 #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.Coord.html","id":null,"dir":"Reference","previous_headings":"","what":"Is this object a coordinate system? — is.Coord","title":"Is this object a coordinate system? — is.Coord","text":"object coordinate system?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.Coord.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Is this object a coordinate system? — is.Coord","text":"","code":"is.Coord(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.facet.html","id":null,"dir":"Reference","previous_headings":"","what":"Is this object a faceting specification? — is.facet","title":"Is this object a faceting specification? — is.facet","text":"object faceting specification?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.facet.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Is this object a faceting specification? — is.facet","text":"","code":"is.facet(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.facet.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Is this object a faceting specification? — is.facet","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Reports whether x is a ggplot object — is.ggplot","title":"Reports whether x is a ggplot object — is.ggplot","text":"Reports whether x ggplot object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reports whether x is a ggplot object — is.ggplot","text":"","code":"is.ggplot(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reports whether x is a ggplot object — is.ggplot","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.rel.html","id":null,"dir":"Reference","previous_headings":"","what":"Reports whether x is a rel object — is.rel","title":"Reports whether x is a rel object — is.rel","text":"Reports whether x rel object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.rel.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reports whether x is a rel object — is.rel","text":"","code":"is.rel(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.rel.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reports whether x is a rel object — is.rel","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Reports whether x is a theme object — is.theme","title":"Reports whether x is a theme object — is.theme","text":"Reports whether x theme object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Reports whether x is a theme object — is.theme","text":"","code":"is.theme(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/is.theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Reports whether x is a theme object — is.theme","text":"x object test","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":null,"dir":"Reference","previous_headings":"","what":"Label with mathematical expressions — label_bquote","title":"Label with mathematical expressions — label_bquote","text":"label_bquote() offers flexible way labelling facet rows columns plotmath expressions. Backquoted variables replaced value facet.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Label with mathematical expressions — label_bquote","text":"","code":"label_bquote(rows = NULL, cols = NULL, default)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Label with mathematical expressions — label_bquote","text":"rows Backquoted labelling expression rows. cols Backquoted labelling expression columns. default Unused, kept compatibility.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/label_bquote.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Label with mathematical expressions — label_bquote","text":"","code":"# The variables mentioned in the plotmath expression must be # backquoted and referred to by their names. p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() p + facet_grid(vs ~ ., labeller = label_bquote(alpha ^ .(vs))) p + facet_grid(. ~ vs, labeller = label_bquote(cols = .(vs) ^ .(vs))) p + facet_grid(. ~ vs + am, labeller = label_bquote(cols = .(am) ^ .(vs)))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":null,"dir":"Reference","previous_headings":"","what":"Construct labelling specification — labeller","title":"Construct labelling specification — labeller","text":"function makes easy assign different labellers different factors. labeller can function can named character vector serve lookup table.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Construct labelling specification — labeller","text":"","code":"labeller( ..., .rows = NULL, .cols = NULL, keep.as.numeric = deprecated(), .multi_line = TRUE, .default = label_value )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Construct labelling specification — labeller","text":"... Named arguments form variable = labeller. labeller passed as_labeller() can lookup table, function taking returning character vectors, simply labeller function. .rows, .cols Labeller whole margin (either rows columns). passed as_labeller(). margin-wide labeller set, make sure mention ... variable belonging margin. keep..numeric supplied labellers -labeller functions able work character labels. .multi_line Whether display labels multiple factors separate lines. passed labeller function. .default Default labeller variables specified. Also used lookup tables non-labeller functions.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Construct labelling specification — labeller","text":"labeller function supply facet_grid() facet_wrap() argument labeller.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Construct labelling specification — labeller","text":"case functions, labeller class labeller, directly applied data frame labels. Otherwise, applied columns data frame labels. data frame processed function specified .default argument. intended used functions taking character vector Hmisc::capitalize().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/labeller.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Construct labelling specification — labeller","text":"","code":"# \\donttest{ p1 <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point() # You can assign different labellers to variables: p1 + facet_grid( vs + am ~ gear, labeller = labeller(vs = label_both, am = label_value) ) # Or whole margins: p1 + facet_grid( vs + am ~ gear, labeller = labeller(.rows = label_both, .cols = label_value) ) # You can supply functions operating on strings: capitalize <- function(string) { substr(string, 1, 1) <- toupper(substr(string, 1, 1)) string } p2 <- ggplot(msleep, aes(x = sleep_total, y = awake)) + geom_point() p2 + facet_grid(vore ~ conservation, labeller = labeller(vore = capitalize)) # Or use character vectors as lookup tables: conservation_status <- c( cd = \"Conservation Dependent\", en = \"Endangered\", lc = \"Least concern\", nt = \"Near Threatened\", vu = \"Vulnerable\", domesticated = \"Domesticated\" ) ## Source: http://en.wikipedia.org/wiki/Wikipedia:Conservation_status p2 + facet_grid(vore ~ conservation, labeller = labeller( .default = capitalize, conservation = conservation_status )) # In the following example, we rename the levels to the long form, # then apply a wrap labeller to the columns to prevent cropped text idx <- match(msleep$conservation, names(conservation_status)) msleep$conservation2 <- conservation_status[idx] p3 <- ggplot(msleep, aes(x = sleep_total, y = awake)) + geom_point() p3 + facet_grid(vore ~ conservation2, labeller = labeller(conservation2 = label_wrap_gen(10)) ) # labeller() is especially useful to act as a global labeller. You # can set it up once and use it on a range of different plots with # different facet specifications. global_labeller <- labeller( vore = capitalize, conservation = conservation_status, conservation2 = label_wrap_gen(10), .default = label_both ) p2 + facet_grid(vore ~ conservation, labeller = global_labeller) p3 + facet_wrap(~conservation2, labeller = global_labeller) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":null,"dir":"Reference","previous_headings":"","what":"Useful labeller functions — labellers","title":"Useful labeller functions — labellers","text":"Labeller functions charge formatting strip labels facet grids wraps. accept multi_line argument control whether multiple factors (defined formulae ~first + second) displayed single line separated commas, line.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Useful labeller functions — labellers","text":"","code":"label_value(labels, multi_line = TRUE) label_both(labels, multi_line = TRUE, sep = \": \") label_context(labels, multi_line = TRUE, sep = \": \") label_parsed(labels, multi_line = TRUE) label_wrap_gen(width = 25, multi_line = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Useful labeller functions — labellers","text":"labels Data frame labels. Usually contains one element, faceting multiple factors entails multiple label variables. multi_line Whether display labels multiple factors separate lines. sep String separating variables values. width Maximum number characters wrapping strip.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Useful labeller functions — labellers","text":"label_value() displays value factor label_both() displays variable name factor value. label_context() context-dependent uses label_value() single factor faceting label_both() multiple factors involved. label_wrap_gen() uses base::strwrap() line wrapping. label_parsed() interprets labels plotmath expressions. label_bquote() offers flexible way constructing plotmath expressions. See examples bquote() details syntax argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"writing-new-labeller-functions","dir":"Reference","previous_headings":"","what":"Writing New Labeller Functions","title":"Useful labeller functions — labellers","text":"Note easy way write labeller function transform function operating character vectors as_labeller(). labeller function accepts data frame labels (character vectors) containing one column factor. Multiple factors occur formula type ~first + second. return value must rectangular list 'row' characterises single facet. list elements can either character vectors lists plotmath expressions. multiple elements returned, get displayed new lines (.e., facet gets multi-line strip labels). illustrate, say labeller returns list two character vectors length 3. rectangular list elements length. first facet get first elements vector display line. second facet gets second elements vector, . useful labeller, can retrieve type attribute incoming data frame labels. value attribute reflects kind strips labeller dealing : \"cols\" columns \"rows\" rows. Note facet_wrap() columns default rows strips switched switch option. facet attribute also provides metadata labels. takes values \"grid\" \"wrap\". compatibility labeller(), labeller function must labeller S3 class.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/labellers.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Useful labeller functions — labellers","text":"","code":"mtcars$cyl2 <- factor(mtcars$cyl, labels = c(\"alpha\", \"beta\", \"gamma\")) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() # The default is label_value p + facet_grid(. ~ cyl, labeller = label_value) # \\donttest{ # Displaying both the values and the variables p + facet_grid(. ~ cyl, labeller = label_both) # Displaying only the values or both the values and variables # depending on whether multiple factors are facetted over p + facet_grid(am ~ vs+cyl, labeller = label_context) # Interpreting the labels as plotmath expressions p + facet_grid(. ~ cyl2) p + facet_grid(. ~ cyl2, labeller = label_parsed) # Include optional argument in label function p + facet_grid(. ~ cyl, labeller = function(x) label_both(x, sep = \"=\")) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify axis, legend, and plot labels — labs","title":"Modify axis, legend, and plot labels — labs","text":"Good labels critical making plots accessible wider audience. Always ensure axis legend labels display full variable name. Use plot title subtitle explain main findings. common use caption provide information data source. tag can used adding identification tags differentiate multiple plots.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify axis, legend, and plot labels — labs","text":"","code":"labs( ..., title = waiver(), subtitle = waiver(), caption = waiver(), tag = waiver(), alt = waiver(), alt_insight = waiver() ) xlab(label) ylab(label) ggtitle(label, subtitle = waiver())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify axis, legend, and plot labels — labs","text":"... list new name-value pairs. name aesthetic. title text title. subtitle text subtitle plot displayed title. caption text caption displayed bottom-right plot default. tag text tag label displayed top-left plot default. alt, alt_insight Text used generation alt-text plot. See get_alt_text examples. alt can also function takes plot input returns text output. alt also accepts rlang lambda function notation. label title respective axis (xlab() ylab()) plot (ggtitle()).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Modify axis, legend, and plot labels — labs","text":"can also set axis legend labels individual scales (using first argument, name). changing scale options, recommended. plot already title, subtitle, caption, etc., want remove , can setting respective argument NULL. example, plot p subtitle, p + labs(subtitle = NULL) remove subtitle plot.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/labs.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify axis, legend, and plot labels — labs","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point() p + labs(colour = \"Cylinders\") p + labs(x = \"New x label\") # The plot title appears at the top-left, with the subtitle # display in smaller text underneath it p + labs(title = \"New plot title\") p + labs(title = \"New plot title\", subtitle = \"A subtitle\") # The caption appears in the bottom-right, and is often used for # sources, notes or copyright p + labs(caption = \"(based on data from ...)\") # The plot tag appears at the top-left, and is typically used # for labelling a subplot with a letter. p + labs(title = \"title\", tag = \"A\") # If you want to remove a label, set it to NULL. p + labs(title = \"title\") + labs(title = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new layer — layer","title":"Create a new layer — layer","text":"layer combination data, stat geom potential position adjustment. Usually layers created using geom_* stat_* calls can also created directly using function.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new layer — layer","text":"","code":"layer( geom = NULL, stat = NULL, data = NULL, mapping = NULL, position = NULL, params = list(), inherit.aes = TRUE, check.aes = TRUE, check.param = TRUE, show.legend = NA, key_glyph = NULL, layer_class = Layer )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new layer — layer","text":"geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. params Additional parameters geom stat. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). check.aes, check.param TRUE, default, check supplied parameters aesthetics understood geom stat. Use FALSE suppress checks. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. key_glyph legend key drawing function string providing function name minus draw_key_ prefix. See draw_key details. layer_class type layer object constructed. intended ggplot2 internal use .","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a new layer — layer","text":"","code":"# geom calls are just a short cut for layer ggplot(mpg, aes(displ, hwy)) + geom_point() # shortcut for ggplot(mpg, aes(displ, hwy)) + layer( geom = \"point\", stat = \"identity\", position = \"identity\", params = list(na.rm = FALSE) ) # use a function as data to plot a subset of global data ggplot(mpg, aes(displ, hwy)) + layer( geom = \"point\", stat = \"identity\", position = \"identity\", data = head, params = list(na.rm = FALSE) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":null,"dir":"Reference","previous_headings":"","what":"Layer geometry display — layer_geoms","title":"Layer geometry display — layer_geoms","text":"ggplot2, plot constructed adding layers . layer consists two important parts: geometry (geoms), statistical transformations (stats). 'geom' part layer important determines looks data. Geoms determine something displayed, displayed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":"specifying-geoms","dir":"Reference","previous_headings":"","what":"Specifying geoms","title":"Layer geometry display — layer_geoms","text":"five ways 'geom' part layer can specified. Many ways absolutely equivalent. Using stat_density(geom = \"line\") identical using geom_line(stat = \"density\"). Note layer(), need provide \"position\" argument well. give geoms string, take function name, remove geom_ prefix, geom_point becomes \"point\". well known geoms can used geom argument : \"point\", \"line\", \"area\", \"bar\" \"polygon\".","code":"# 1. The geom can have a layer constructor geom_area() # 2. A stat can default to a particular geom stat_density() # has `geom = \"area\"` as default # 3. It can be given to a stat as a string stat_function(geom = \"area\") # 4. The ggproto object of a geom can be given stat_bin(geom = GeomArea) # 5. It can be given to `layer()` directly layer( geom = \"area\", stat = \"smooth\", position = \"identity\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":"graphical-display","dir":"Reference","previous_headings":"","what":"Graphical display","title":"Layer geometry display — layer_geoms","text":"ggplot build top grid package. package understands various graphical primitives, points, lines, rectangles polygons positions, well graphical attributes, also termed aesthetics, colours, fills, linewidths linetypes. job geom part layer, translate data grid graphics can plotted. see aesthetics specified, run vignette(\"ggplot2-specs\"). see geom uses aesthetics, can find Aesthetics section documentation, example ?geom_line. almost anything can represented polygons try hard enough, always convenient manually. reason, geoms provide abstractions take hassle away. geom_ribbon() example special case geom_polygon(), two sets y-positions shared x-position. turn, geom_area() special case ribbon, one two sets y-positions set 0. addition abstraction, geoms sometimes also perform composition. boxplot particular arrangement lines, rectangles points people agreed upon summary data, performed geom_boxplot().","code":"# A hassle to build a polygon my_polygon <- data.frame( x = c(economics$date, rev(economics$date)), y = c(economics$uempmed, rev(economics$psavert)) ) ggplot(my_polygon, aes(x, y)) + geom_polygon() # More succinctly ggplot(economics, aes(date)) + geom_ribbon(aes(ymin = uempmed, ymax = psavert)) Boxplot data value <- fivenum(rnorm(100)) df <- data.frame( min = value[1], lower = value[2], middle = value[3], upper = value[4], max = value[5] ) # Drawing a boxplot manually ggplot(df, aes(x = 1, xend = 1)) + geom_rect( aes( xmin = 0.55, xmax = 1.45, ymin = lower, ymax = upper ), colour = \"black\", fill = \"white\" ) + geom_segment( aes( x = 0.55, xend = 1.45, y = middle, yend = middle ), size = 1 ) + geom_segment(aes(y = lower, yend = min)) + geom_segment(aes(y = upper, yend = max)) # More succinctly ggplot(df, aes(x = 1)) + geom_boxplot( aes(ymin = min, ymax = max, lower = lower, upper = upper, middle = middle), stat = \"identity\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_geoms.html","id":"under-the-hood","dir":"Reference","previous_headings":"","what":"Under the hood","title":"Layer geometry display — layer_geoms","text":"Internally, geoms represented ggproto classes occupy slot layer. classes inherit parental Geom ggproto object orchestrates geoms work. Briefly, geoms given opportunity draw data layer whole, facet panel, individual groups. information extending geoms, see Creating new geom section running vignette(\"extending-ggplot2\"). Additionally, see New geoms section online book.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":null,"dir":"Reference","previous_headings":"","what":"Layer position adjustments — layer_positions","title":"Layer position adjustments — layer_positions","text":"ggplot2, plot constructed adding layers . addition geoms stats, position adjustments third required part layer. 'position' part layer responsible dodging, jittering nudging groups data minimise overlap, otherwise tweaking positions. example add position = position_nudge(x = 1) layer, can offset every x-position 1. many layers, default position adjustment position_identity(), performs adjustment.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"specifying-positions","dir":"Reference","previous_headings":"","what":"Specifying positions","title":"Layer position adjustments — layer_positions","text":"4 ways 'position' part layer can specified. ways always equivalent. layers may understand position adjustment, require additional parameters passed position_*() function, may work correctly. example position_dodge() requires non-overlapping x intervals, whereas geom_point() dimensions calculate intervals . give positions string, take function name, remove position_ prefix, position_fill becomes \"fill\".","code":"1. A layer can have default position adjustments geom_jitter() # has `position = \"jitter\"` 2. It can be given to a layer as a string geom_point(position = \"jitter\") 3. The position function can be used to pass extra arguments geom_point(position = position_jitter(width = 1)) 4. It can be given to `layer()` directly layer( geom = \"point\", stat = \"identity\", position = \"jitter\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"pairing-geoms-with-positions","dir":"Reference","previous_headings":"","what":"Pairing geoms with positions","title":"Layer position adjustments — layer_positions","text":"geoms work better positions others. follows brief overview geoms position adjustments work well together.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"identity","dir":"Reference","previous_headings":"","what":"Identity","title":"Layer position adjustments — layer_positions","text":"position_identity() can work virtually geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"dodging","dir":"Reference","previous_headings":"","what":"Dodging","title":"Layer position adjustments — layer_positions","text":"position_dodge() pushes overlapping objects away one another requires group variable. position_dodge2() can work without group variables can handle variable widths. rule thumb, layers groups occupy range x-axis pair well dodging. layers width, may required specify manually position_dodge(width = ...). geoms pair well dodging geom_bar(), geom_boxplot(), geom_linerange(), geom_errorbar() geom_text().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"jittering","dir":"Reference","previous_headings":"","what":"Jittering","title":"Layer position adjustments — layer_positions","text":"position_jitter() adds random noise every point, can help overplotting. position_jitterdodge() , also dodges points. rule thumb, jittering works best points discrete x-positions. Jittering useful geom_point(), can also used geom_path() example.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"nudging","dir":"Reference","previous_headings":"","what":"Nudging","title":"Layer position adjustments — layer_positions","text":"position_nudge() can add offsets x- y-positions. can useful discrete positions want put object exactly middle. useful geom_text(), can used virtually geoms.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"stacking","dir":"Reference","previous_headings":"","what":"Stacking","title":"Layer position adjustments — layer_positions","text":"position_stack() useful displaying data top one another. can used geoms usually anchored x-axis, example geom_bar(), geom_area() geom_histogram().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"filling","dir":"Reference","previous_headings":"","what":"Filling","title":"Layer position adjustments — layer_positions","text":"position_fill() can used give proportions every x-position. Like stacking, filling useful geoms anchored x-axis, like geom_bar(), geom_area() geom_histogram().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_positions.html","id":"under-the-hood","dir":"Reference","previous_headings":"","what":"Under the hood","title":"Layer position adjustments — layer_positions","text":"Internally, positions represented ggproto classes occupy slot layer. classes inherit parental Position ggproto object orchestrates positions work. Briefly, positions given opportunity adjust data facet panel. information extending positions, see New positions section online book.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_sf.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a new sf layer that auto-maps geometry data — layer_sf","title":"Create a new sf layer that auto-maps geometry data — layer_sf","text":"layer_sf() function variant layer() meant used extension developers writing new sf-based geoms stats. sf layer checks whether data contains geometry column, one found automatically mapped geometry aesthetic.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_sf.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a new sf layer that auto-maps geometry data — layer_sf","text":"","code":"layer_sf( geom = NULL, stat = NULL, data = NULL, mapping = NULL, position = NULL, params = list(), inherit.aes = TRUE, check.aes = TRUE, check.param = TRUE, show.legend = NA )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_sf.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a new sf layer that auto-maps geometry data — layer_sf","text":"geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. stat statistical transformation use data layer. using geom_*() function construct layer, stat argument can used override default coupling geoms stats. stat argument accepts following: Stat ggproto subclass, example StatCount. string naming stat. give stat string, strip function name stat_ prefix. example, use stat_count(), give stat \"count\". information ways specify stat, see layer stat documentation. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. params Additional parameters geom stat. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). check.aes, check.param TRUE, default, check supplied parameters aesthetics understood geom stat. Use FALSE suppress checks. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":null,"dir":"Reference","previous_headings":"","what":"Layer statistical transformations — layer_stats","title":"Layer statistical transformations — layer_stats","text":"ggplot2, plot constructed adding layers . layer consists two important parts: geometry (geoms), statistical transformations (stats). 'stat' part layer important performs computation data displayed. Stats determine displayed, displayed. example, add stat_density() plot, kernel density estimation performed, can displayed 'geom' part layer. many geom_*() functions, stat_identity() used, performs extra computation data.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"specifying-stats","dir":"Reference","previous_headings":"","what":"Specifying stats","title":"Layer statistical transformations — layer_stats","text":"five ways 'stat' part layer can specified. Many ways absolutely equivalent. Using stat_density(geom = \"line\") identical using geom_line(stat = \"density\"). Note layer(), need provide \"position\" argument well. give stats string, take function name, remove stat_ prefix, stat_bin becomes \"bin\". well known stats can used stat argument : \"density\", \"bin\", \"count\", \"function\" \"smooth\".","code":"# 1. The stat can have a layer constructor stat_density() # 2. A geom can default to a particular stat geom_density() # has `stat = \"density\"` as default # 3. It can be given to a geom as a string geom_line(stat = \"density\") # 4. The ggproto object of a stat can be given geom_area(stat = StatDensity) # 5. It can be given to `layer()` directly: layer( geom = \"line\", stat = \"density\", position = \"identity\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"paired-geoms-and-stats","dir":"Reference","previous_headings":"","what":"Paired geoms and stats","title":"Layer statistical transformations — layer_stats","text":"geoms paired stats. cases, like geom_density(), just variant another geom, geom_area(), slightly different defaults. cases, relationship complex. case boxplots example, stat geom distinct roles. role stat compute five-number summary data. addition just displaying box five-number summary, geom also provides display options outliers widths boxplots. cases, freely exchange geoms stats: using stat_boxplot(geom = \"line\") geom_area(stat = \"boxplot\") give errors. stats geoms paired : geom_violin() stat_ydensity() geom_histogram() stat_bin() geom_contour() stat_contour() geom_function() stat_function() geom_bin_2d() stat_bin_2d() geom_boxplot() stat_boxplot() geom_count() stat_sum() geom_density() stat_density() geom_density_2d() stat_density_2d() geom_hex() stat_binhex() geom_quantile() stat_quantile() geom_smooth() stat_smooth()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"using-computed-variables","dir":"Reference","previous_headings":"","what":"Using computed variables","title":"Layer statistical transformations — layer_stats","text":"mentioned , role stats perform computation data. result, stats 'computed variables' determine compatibility geoms. computed variables documented Computed variables sections documentation, example ?stat_bin. thoroughly documented after_stat(), briefly mentioned computed stats can accessed aes(). example, ?stat_density documentation states , addition variable called density, stat computes variable named count. Instead scaling area integrates 1, count variable scales computed density values can interpreted counts. stat_density(aes(y = after_stat(count))) used, can display count-scaled densities instead regular densities. computed variables offer flexibility arbitrary geom-stat pairings can made. necessarily recommended, geom_line() can paired stat = \"boxplot\" line instructed use boxplot computed variables:","code":"ggplot(mpg, aes(factor(cyl))) + geom_line( # Stage gives 'displ' to the stat, and afterwards chooses 'middle' as # the y-variable to display aes(y = stage(displ, after_stat = middle), # Regroup after computing the stats to display a single line group = after_stat(1)), stat = \"boxplot\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/layer_stats.html","id":"under-the-hood","dir":"Reference","previous_headings":"","what":"Under the hood","title":"Layer statistical transformations — layer_stats","text":"Internally, stats represented ggproto classes occupy slot layer. classes inherit parental Stat ggproto object orchestrates stats work. Briefly, stats given opportunity perform computation either layer whole, facet panel, individual groups. information extending stats, see Creating new stat section running vignette(\"extending-ggplot2\"). Additionally, see New stats section online book.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":null,"dir":"Reference","previous_headings":"","what":"Generate correct scale type for specified limits — limits","title":"Generate correct scale type for specified limits — limits","text":"Generate correct scale type specified limits","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Generate correct scale type for specified limits — limits","text":"","code":"limits(lims, var, call = caller_env())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Generate correct scale type for specified limits — limits","text":"lims vector limits var name variable","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/limits.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Generate correct scale type for specified limits — limits","text":"","code":"ggplot2:::limits(c(1, 5), \"x\") #> #> Range: #> Limits: 1 -- 5 ggplot2:::limits(c(5, 1), \"x\") #> #> Range: #> Limits: -5 -- -1 ggplot2:::limits(c(\"A\", \"b\", \"c\"), \"x\") #> #> aesthetics: x xmin xmax xend xintercept xmin_final xmax_final xlower ... #> axis_order: function #> break_info: function #> break_positions: function #> breaks: waiver #> call: environment #> clone: function #> dimension: function #> drop: TRUE #> expand: waiver #> get_breaks: function #> get_breaks_minor: function #> get_labels: function #> get_limits: function #> get_transformation: function #> guide: waiver #> is_discrete: function #> is_empty: function #> labels: waiver #> limits: A b c #> make_sec_title: function #> make_title: function #> map: function #> map_df: function #> minor_breaks: waiver #> n.breaks.cache: NULL #> na.translate: TRUE #> na.value: NA #> name: waiver #> palette: function #> palette.cache: NULL #> position: bottom #> range: environment #> range_c: environment #> rescale: function #> reset: function #> sec_name: function #> train: function #> train_df: function #> transform: function #> transform_df: function #> super: ggplot2:::limits(c(\"A\", \"b\", \"c\"), \"fill\") #> #> aesthetics: fill #> axis_order: function #> break_info: function #> break_positions: function #> breaks: waiver #> call: environment #> clone: function #> dimension: function #> drop: TRUE #> expand: waiver #> get_breaks: function #> get_breaks_minor: function #> get_labels: function #> get_limits: function #> get_transformation: function #> guide: legend #> is_discrete: function #> is_empty: function #> labels: waiver #> limits: A b c #> make_sec_title: function #> make_title: function #> map: function #> map_df: function #> minor_breaks: waiver #> n.breaks.cache: NULL #> na.translate: TRUE #> na.value: grey50 #> name: waiver #> palette: function #> palette.cache: NULL #> position: left #> range: environment #> rescale: function #> reset: function #> train: function #> train_df: function #> transform: function #> transform_df: function #> super: ggplot2:::limits(as.Date(c(\"2008-01-01\", \"2009-01-01\")), \"x\") #> #> Range: #> Limits: 1.39e+04 -- 1.42e+04"},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":null,"dir":"Reference","previous_headings":"","what":"Set scale limits — lims","title":"Set scale limits — lims","text":"shortcut supplying limits argument individual scales. default, values outside limits specified replaced NA. warned remove data outside limits can produce unintended results. changing x y axis limits without dropping data observations, see coord_cartesian().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set scale limits — lims","text":"","code":"lims(...) xlim(...) ylim(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Set scale limits — lims","text":"... xlim() ylim(): Two numeric values, specifying left/lower limit right/upper limit scale. larger value given first, scale reversed. can leave one value NA want compute corresponding limit range data. lims(): name–value pair. name must aesthetic, value must either length-2 numeric, character, factor, date/time. numeric value create continuous scale. larger value comes first, scale reversed. can leave one value NA want compute corresponding limit range data. character factor value create discrete scale. date-time value create continuous date/time scale.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/lims.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Set scale limits — lims","text":"","code":"# Zoom into a specified area ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(15, 20) #> Warning: Removed 19 rows containing missing values or values outside the scale #> range (`geom_point()`). # reverse scale ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(20, 15) #> Warning: Removed 19 rows containing missing values or values outside the scale #> range (`geom_point()`). # with automatic lower limit ggplot(mtcars, aes(mpg, wt)) + geom_point() + xlim(NA, 20) #> Warning: Removed 14 rows containing missing values or values outside the scale #> range (`geom_point()`). # You can also supply limits that are larger than the data. # This is useful if you want to match scales across different plots small <- subset(mtcars, cyl == 4) big <- subset(mtcars, cyl > 4) ggplot(small, aes(mpg, wt, colour = factor(cyl))) + geom_point() + lims(colour = c(\"4\", \"6\", \"8\")) ggplot(big, aes(mpg, wt, colour = factor(cyl))) + geom_point() + lims(colour = c(\"4\", \"6\", \"8\")) # There are two ways of setting the axis limits: with limits or # with coordinate systems. They work in two rather different ways. set.seed(1) last_month <- Sys.Date() - 0:59 df <- data.frame( date = last_month, price = c(rnorm(30, mean = 15), runif(30) + 0.2 * (1:30)) ) p <- ggplot(df, aes(date, price)) + geom_line() + stat_smooth() p #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' # Setting the limits with the scale discards all data outside the range. p + lims(x= c(Sys.Date() - 30, NA), y = c(10, 20)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' #> Warning: Removed 30 rows containing non-finite outside the scale range #> (`stat_smooth()`). #> Warning: Removed 30 rows containing missing values or values outside the scale #> range (`geom_line()`). # For changing x or y axis limits **without** dropping data # observations use [coord_cartesian()]. Setting the limits on the # coordinate system performs a visual zoom. p + coord_cartesian(xlim =c(Sys.Date() - 30, NA), ylim = c(10, 20)) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'"},{"path":"https://ggplot2.tidyverse.org/dev/reference/luv_colours.html","id":null,"dir":"Reference","previous_headings":"","what":"colors() in Luv space — luv_colours","title":"colors() in Luv space — luv_colours","text":"built-colors() translated Luv colour space.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/luv_colours.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"colors() in Luv space — luv_colours","text":"","code":"luv_colours"},{"path":"https://ggplot2.tidyverse.org/dev/reference/luv_colours.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"colors() in Luv space — luv_colours","text":"data frame 657 observations 4 variables: L,u,v Position Luv colour space col Colour name","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":null,"dir":"Reference","previous_headings":"","what":"Create a data frame of map data — map_data","title":"Create a data frame of map data — map_data","text":"Easily turn data maps package data frame suitable plotting ggplot2.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create a data frame of map data — map_data","text":"","code":"map_data(map, region = \".\", exact = FALSE, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create a data frame of map data — map_data","text":"map name map provided maps package. include maps::county(), maps::france(), maps::italy(), maps::nz(), maps::state(), maps::usa(), maps::world(), maps::world2(). region name(s) subregion(s) include. Defaults . includes subregions. See documentation maps::map() details. exact region treated regular expression (FALSE) fixed string (TRUE). ... arguments passed maps::map()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/map_data.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create a data frame of map data — map_data","text":"","code":"if (require(\"maps\")) { states <- map_data(\"state\") arrests <- USArrests names(arrests) <- tolower(names(arrests)) arrests$region <- tolower(rownames(USArrests)) choro <- merge(states, arrests, sort = FALSE, by = \"region\") choro <- choro[order(choro$order), ] ggplot(choro, aes(long, lat)) + geom_polygon(aes(group = group, fill = assault)) + coord_map(\"albers\", lat0 = 45.5, lat1 = 29.5) } if (require(\"maps\")) { ggplot(choro, aes(long, lat)) + geom_polygon(aes(group = group, fill = assault / murder)) + coord_map(\"albers\", lat0 = 45.5, lat1 = 29.5) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":null,"dir":"Reference","previous_headings":"","what":"Get the maximal width/length of a list of grobs — max_height","title":"Get the maximal width/length of a list of grobs — max_height","text":"Get maximal width/length list grobs","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Get the maximal width/length of a list of grobs — max_height","text":"","code":"max_height(grobs, value_only = FALSE) max_width(grobs, value_only = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Get the maximal width/length of a list of grobs — max_height","text":"grobs list grobs value_only return value simple numeric vector giving maximum cm","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/max_height.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Get the maximal width/length of a list of grobs — max_height","text":"largest value. measured cm unit object numeric vector depending value_only","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":null,"dir":"Reference","previous_headings":"","what":"Calculate mean and standard error of the mean — mean_se","title":"Calculate mean and standard error of the mean — mean_se","text":"use stat_summary()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Calculate mean and standard error of the mean — mean_se","text":"","code":"mean_se(x, mult = 1)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Calculate mean and standard error of the mean — mean_se","text":"x numeric vector. mult number multiples standard error.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Calculate mean and standard error of the mean — mean_se","text":"data frame three columns: y mean. ymin mean minus multiples standard error. ymax mean plus multiples standard error.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mean_se.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Calculate mean and standard error of the mean — mean_se","text":"","code":"set.seed(1) x <- rnorm(100) mean_se(x) #> y ymin ymax #> 1 0.1088874 0.01906743 0.1987073"},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":null,"dir":"Reference","previous_headings":"","what":"Merge a parent element into a child element — merge_element","title":"Merge a parent element into a child element — merge_element","text":"generic element classes must provide implementation method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Merge a parent element into a child element — merge_element","text":"","code":"merge_element(new, old) # Default S3 method merge_element(new, old) # S3 method for class 'element_blank' merge_element(new, old) # S3 method for class 'element' merge_element(new, old)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Merge a parent element into a child element — merge_element","text":"new child element theme hierarchy old parent element theme hierarchy","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Merge a parent element into a child element — merge_element","text":"modified version new updated properties old","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/merge_element.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Merge a parent element into a child element — merge_element","text":"","code":"new <- element_text(colour = \"red\") old <- element_text(colour = \"blue\", size = 10) # Adopt size but ignore colour merge_element(new, old) #> List of 11 #> $ family : NULL #> $ face : NULL #> $ colour : chr \"red\" #> $ size : num 10 #> $ hjust : NULL #> $ vjust : NULL #> $ angle : NULL #> $ lineheight : NULL #> $ margin : NULL #> $ debug : NULL #> $ inherit.blank: logi FALSE #> - attr(*, \"class\")= chr [1:2] \"element_text\" \"element\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":null,"dir":"Reference","previous_headings":"","what":"Midwest demographics — midwest","title":"Midwest demographics — midwest","text":"Demographic information midwest counties 2000 US census","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Midwest demographics — midwest","text":"","code":"midwest"},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Midwest demographics — midwest","text":"data frame 437 rows 28 variables: PID Unique county identifier. county County name. state State county belongs . area Area county (units unknown). poptotal Total population. popdensity Population density (person/unit area). popwhite Number whites. popblack Number blacks. popamerindian Number American Indians. popasian Number Asians. popother Number races. percwhite Percent white. percblack Percent black. percamerindan Percent American Indian. percasian Percent Asian. percother Percent races. popadults Number adults. perchsd Percent high school diploma. percollege Percent college educated. percprof Percent professional degree. poppovertyknown Population known poverty status. percpovertyknown Percent population known poverty status. percbelowpoverty Percent people poverty line. percchildbelowpovert Percent children poverty line. percadultpoverty Percent adults poverty line. percelderlypoverty Percent elderly poverty line. inmetro County considered metro area. category Miscellaneous.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/midwest.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Midwest demographics — midwest","text":"Note: dataset included illustrative purposes. original descriptions documented current descriptions based speculation. accurate --date US census data, see acs package.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mpg.html","id":null,"dir":"Reference","previous_headings":"","what":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","title":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","text":"dataset contains subset fuel economy data EPA makes available https://fueleconomy.gov/. contains models new release every year 1999 2008 - used proxy popularity car.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/mpg.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","text":"","code":"mpg"},{"path":"https://ggplot2.tidyverse.org/dev/reference/mpg.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Fuel economy data from 1999 to 2008 for 38 popular models of cars — mpg","text":"data frame 234 rows 11 variables: manufacturer manufacturer name model model name displ engine displacement, litres year year manufacture cyl number cylinders trans type transmission drv type drive train, 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\" car","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":null,"dir":"Reference","previous_headings":"","what":"An updated and expanded version of the mammals sleep dataset — msleep","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"updated expanded version mammals sleep dataset. Updated sleep times weights taken V. M. Savage G. B. West. quantitative, theoretical framework understanding mammalian sleep. Proceedings National Academy Sciences, 104 (3):1051-1056, 2007.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"","code":"msleep"},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"data frame 83 rows 11 variables: name common name genus vore carnivore, omnivore herbivore? order conservation conservation status animal sleep_total total amount sleep, hours sleep_rem rem sleep, hours sleep_cycle length sleep cycle, hours awake amount time spent awake, hours brainwt brain weight kilograms bodywt body weight kilograms","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/msleep.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"An updated and expanded version of the mammals sleep dataset — msleep","text":"Additional variables order, conservation status vore added wikipedia.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":null,"dir":"Reference","previous_headings":"","what":"Guide constructor — new_guide","title":"Guide constructor — new_guide","text":"constructor function guides, performs standard compatibility checks guide provided arguments.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Guide constructor — new_guide","text":"","code":"new_guide(..., available_aes = \"any\", super)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Guide constructor — new_guide","text":"... Named arguments match parameters super$params theme elements super$elements. available_aes vector character strings listing aesthetics guide can drawn. super super class use constructed guide. Guide class object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/new_guide.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Guide constructor — new_guide","text":"Guide ggproto object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/old_guide.html","id":null,"dir":"Reference","previous_headings":"","what":"The previous S3 guide system — old_guide","title":"The previous S3 guide system — old_guide","text":"guide system overhauled use ggproto infrastructure accommodate guide extensions flexibility layers, scales ggplot2 objects. rewriting, old S3 system become defunct, meaning previous methods guides superseded ggproto methods. fallback option, generics, methods, previous S3 system used encapsulated GuideOld ggproto class.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/old_guide.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"The previous S3 guide system — old_guide","text":"","code":"guide_train(guide, scale, aesthetic = NULL) guide_merge(guide, new_guide) guide_geom(guide, layers, default_mapping = NULL) guide_transform(guide, coord, panel_params) guide_gengrob(guide, theme) old_guide(guide)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/old_guide.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"The previous S3 guide system — old_guide","text":"guide old guide object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify transparency for patterns — pattern_alpha","title":"Modify transparency for patterns — pattern_alpha","text":"generic allows add methods adding transparency pattern-like objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify transparency for patterns — pattern_alpha","text":"","code":"pattern_alpha(x, alpha)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify transparency for patterns — pattern_alpha","text":"x Object interpreted pattern. alpha numeric vector 0 1. NA, alpha values preserved.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/pattern_alpha.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Modify transparency for patterns — pattern_alpha","text":"x modified transparency","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":null,"dir":"Reference","previous_headings":"","what":"Dodge overlapping objects side-to-side — position_dodge","title":"Dodge overlapping objects side-to-side — position_dodge","text":"Dodging preserves vertical position geom adjusting horizontal position. position_dodge() requires grouping variable specified global geom_* layer. Unlike position_dodge(), position_dodge2() works without grouping variable layer. position_dodge2() works bars rectangles, particularly useful arranging box plots, can variable widths.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Dodge overlapping objects side-to-side — position_dodge","text":"","code":"position_dodge( width = NULL, preserve = \"total\", orientation = \"x\", reverse = FALSE ) position_dodge2( width = NULL, preserve = \"total\", padding = 0.1, reverse = FALSE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Dodge overlapping objects side-to-side — position_dodge","text":"width Dodging width, different width individual elements. useful want align narrow geoms wider geoms. See examples. preserve dodging preserve \"total\" width elements position, width \"single\" element? orientation Fallback orientation layer data indicate explicit orientation, like geom_point(). Can \"x\" (default) \"y\". reverse TRUE, reverse default stacking order. useful rotating plot legend. padding Padding elements position. Elements shrunk proportion allow space . Defaults 0.1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_dodge.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Dodge overlapping objects side-to-side — position_dodge","text":"","code":"ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = \"dodge2\") # By default, dodging with `position_dodge2()` preserves the total width of # the elements. You can choose to preserve the width of each element with: ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = \"single\")) # \\donttest{ ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(position=\"dodge2\") #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # see ?geom_bar for more examples # In this case a frequency polygon is probably a better choice ggplot(diamonds, aes(price, colour = cut)) + geom_freqpoly() #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # } # Dodging with various widths ------------------------------------- # To dodge items with different widths, you need to be explicit df <- data.frame( x = c(\"a\",\"a\",\"b\",\"b\"), y = 2:5, g = rep(1:2, 2) ) p <- ggplot(df, aes(x, y, group = g)) + geom_col(position = \"dodge\", fill = \"grey50\", colour = \"black\") p # A line range has no width: p + geom_linerange(aes(ymin = y - 1, ymax = y + 1), position = \"dodge\") #> Warning: Width not defined #> ℹ Set with `position_dodge(width = ...)` # So you must explicitly specify the width p + geom_linerange( aes(ymin = y - 1, ymax = y + 1), position = position_dodge(width = 0.9) ) # The same principle applies to error bars, which are usually # narrower than the bars p + geom_errorbar( aes(ymin = y - 1, ymax = y + 1), width = 0.2, position = \"dodge\" ) p + geom_errorbar( aes(ymin = y - 1, ymax = y + 1), width = 0.2, position = position_dodge(width = 0.9) ) # Box plots use position_dodge2 by default, and bars can use it too ggplot(mpg, aes(factor(year), displ)) + geom_boxplot(aes(colour = hwy < 30)) ggplot(mpg, aes(factor(year), displ)) + geom_boxplot(aes(colour = hwy < 30), varwidth = TRUE) ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = \"single\")) ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = position_dodge2(preserve = \"total\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_identity.html","id":null,"dir":"Reference","previous_headings":"","what":"Don't adjust position — position_identity","title":"Don't adjust position — position_identity","text":"adjust position","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_identity.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Don't adjust position — position_identity","text":"","code":"position_identity()"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":null,"dir":"Reference","previous_headings":"","what":"Jitter points to avoid overplotting — position_jitter","title":"Jitter points to avoid overplotting — position_jitter","text":"Counterintuitively adding random noise plot can sometimes make easier read. Jittering particularly useful small datasets least one discrete position.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Jitter points to avoid overplotting — position_jitter","text":"","code":"position_jitter(width = NULL, height = NULL, seed = NA)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Jitter points to avoid overplotting — position_jitter","text":"width, height Amount vertical horizontal jitter. jitter added positive negative directions, total spread twice value specified . omitted, defaults 40% resolution data: means jitter values occupy 80% implied bins. Categorical data aligned integers, width height 0.5 spread data possible see distinction categories. seed random seed make jitter reproducible. Useful need apply jitter twice, e.g., point corresponding label. random seed reset jittering. NA (default value), seed initialised random value; makes sure two subsequent calls start different seed. Use NULL use current random seed also avoid resetting (behaviour ggplot 2.2.1 earlier).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitter.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Jitter points to avoid overplotting — position_jitter","text":"","code":"# Jittering is useful when you have a discrete position, and a relatively # small number of points # take up as much space as a boxplot or a bar ggplot(mpg, aes(class, hwy)) + geom_boxplot(colour = \"grey50\") + geom_jitter() # If the default jittering is too much, as in this plot: ggplot(mtcars, aes(am, vs)) + geom_jitter() # You can adjust it in two ways ggplot(mtcars, aes(am, vs)) + geom_jitter(width = 0.1, height = 0.1) ggplot(mtcars, aes(am, vs)) + geom_jitter(position = position_jitter(width = 0.1, height = 0.1)) # Create a jitter object for reproducible jitter: jitter <- position_jitter(width = 0.1, height = 0.1, seed = 0) ggplot(mtcars, aes(am, vs)) + geom_point(position = jitter) + geom_point(position = jitter, color = \"red\", aes(am + 0.2, vs + 0.2))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":null,"dir":"Reference","previous_headings":"","what":"Simultaneously dodge and jitter — position_jitterdodge","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"primarily used aligning points generated geom_point() dodged boxplots (e.g., geom_boxplot() fill aesthetic supplied).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"","code":"position_jitterdodge( jitter.width = NULL, jitter.height = 0, dodge.width = 0.75, reverse = FALSE, seed = NA )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"jitter.width degree jitter x direction. Defaults 40% resolution data. jitter.height degree jitter y direction. Defaults 0. dodge.width amount dodge x direction. Defaults 0.75, default position_dodge() width. reverse TRUE, reverse default stacking order. useful rotating plot legend. seed random seed make jitter reproducible. Useful need apply jitter twice, e.g., point corresponding label. random seed reset jittering. NA (default value), seed initialised random value; makes sure two subsequent calls start different seed. Use NULL use current random seed also avoid resetting (behaviour ggplot 2.2.1 earlier).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_jitterdodge.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Simultaneously dodge and jitter — position_jitterdodge","text":"","code":"set.seed(596) dsub <- diamonds[sample(nrow(diamonds), 1000), ] ggplot(dsub, aes(x = cut, y = carat, fill = clarity)) + geom_boxplot(outlier.size = 0) + geom_point(pch = 21, position = position_jitterdodge())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":null,"dir":"Reference","previous_headings":"","what":"Nudge points a fixed distance — position_nudge","title":"Nudge points a fixed distance — position_nudge","text":"position_nudge() generally useful adjusting position items discrete scales small amount. Nudging built geom_text() useful moving labels small distance labelling.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Nudge points a fixed distance — position_nudge","text":"","code":"position_nudge(x = 0, y = 0)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Nudge points a fixed distance — position_nudge","text":"x, y Amount vertical horizontal distance move.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_nudge.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Nudge points a fixed distance — position_nudge","text":"","code":"df <- data.frame( x = c(1,3,2,5), y = c(\"a\",\"c\",\"d\",\"c\") ) ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y)) ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y), position = position_nudge(y = -0.1)) # Or, in brief ggplot(df, aes(x, y)) + geom_point() + geom_text(aes(label = y), nudge_y = -0.1)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":null,"dir":"Reference","previous_headings":"","what":"Stack overlapping objects on top of each another — position_stack","title":"Stack overlapping objects on top of each another — position_stack","text":"position_stack() stacks bars top ; position_fill() stacks bars standardises stack constant height.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Stack overlapping objects on top of each another — position_stack","text":"","code":"position_stack(vjust = 1, reverse = FALSE) position_fill(vjust = 1, reverse = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Stack overlapping objects on top of each another — position_stack","text":"vjust Vertical adjustment geoms position (like points lines), dimension (like bars areas). Set 0 align bottom, 0.5 middle, 1 (default) top. reverse TRUE, reverse default stacking order. useful rotating plot legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Stack overlapping objects on top of each another — position_stack","text":"position_fill() position_stack() automatically stack values reverse order group aesthetic, bar charts usually defined fill aesthetic (default group aesthetic formed combination discrete aesthetics except x y). default ensures bar colours align default legend. three ways override defaults depending want: Change order levels underlying factor. change stacking order, order keys legend. Set legend breaks change order keys without affecting stacking. Manually set group aesthetic change stacking order without affecting legend. Stacking positive negative values performed separately positive values stack upwards x-axis negative values stack downward. stacking performed scale transformations, stacking non-linear scales gives distortions easily lead misinterpretations data. therefore discouraged use position adjustments combination scale transformations, logarithmic square root scales.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/position_stack.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Stack overlapping objects on top of each another — position_stack","text":"","code":"# Stacking and filling ------------------------------------------------------ # Stacking is the default behaviour for most area plots. # Fill makes it easier to compare proportions ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar() ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) + geom_bar(position = \"fill\") ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500) ggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500, position = \"fill\") # Stacking is also useful for time series set.seed(1) series <- data.frame( time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)), type = rep(c('a', 'b', 'c', 'd'), 4), value = rpois(16, 10) ) ggplot(series, aes(time, value)) + geom_area(aes(fill = type)) # Stacking order ------------------------------------------------------------ # The stacking order is carefully designed so that the plot matches # the legend. # You control the stacking order by setting the levels of the underlying # factor. See the forcats package for convenient helpers. series$type2 <- factor(series$type, levels = c('c', 'b', 'd', 'a')) ggplot(series, aes(time, value)) + geom_area(aes(fill = type2)) # You can change the order of the levels in the legend using the scale ggplot(series, aes(time, value)) + geom_area(aes(fill = type)) + scale_fill_discrete(breaks = c('a', 'b', 'c', 'd')) # If you've flipped the plot, use reverse = TRUE so the levels # continue to match ggplot(series, aes(time, value)) + geom_area(aes(fill = type2), position = position_stack(reverse = TRUE)) + coord_flip() + theme(legend.position = \"top\") # Non-area plots ------------------------------------------------------------ # When stacking across multiple layers it's a good idea to always set # the `group` aesthetic in the ggplot() call. This ensures that all layers # are stacked in the same way. ggplot(series, aes(time, value, group = type)) + geom_line(aes(colour = type), position = \"stack\") + geom_point(aes(colour = type), position = \"stack\") ggplot(series, aes(time, value, group = type)) + geom_area(aes(fill = type)) + geom_line(aes(group = type), position = \"stack\") # You can also stack labels, but the default position is suboptimal. ggplot(series, aes(time, value, group = type)) + geom_area(aes(fill = type)) + geom_text(aes(label = type), position = \"stack\") # You can override this with the vjust parameter. A vjust of 0.5 # will center the labels inside the corresponding area ggplot(series, aes(time, value, group = type)) + geom_area(aes(fill = type)) + geom_text(aes(label = type), position = position_stack(vjust = 0.5)) # Negative values ----------------------------------------------------------- df <- data.frame( x = rep(c(\"a\", \"b\"), 2:3), y = c(1, 2, 1, 3, -1), grp = c(\"x\", \"y\", \"x\", \"y\", \"y\") ) ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = position_stack(reverse = TRUE)) + geom_hline(yintercept = 0) ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp)) + geom_hline(yintercept = 0) + geom_text(aes(label = grp), position = position_stack(vjust = 0.5))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/presidential.html","id":null,"dir":"Reference","previous_headings":"","what":"Terms of 12 presidents from Eisenhower to Trump — presidential","title":"Terms of 12 presidents from Eisenhower to Trump — presidential","text":"names president, start end date term, party 12 US presidents Eisenhower Trump. data public domain.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/presidential.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Terms of 12 presidents from Eisenhower to Trump — presidential","text":"","code":"presidential"},{"path":"https://ggplot2.tidyverse.org/dev/reference/presidential.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Terms of 12 presidents from Eisenhower to Trump — presidential","text":"data frame 12 rows 4 variables: name Last name president start Presidency start date end Presidency end date party Party president","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Explicitly draw plot — print.ggplot","title":"Explicitly draw plot — print.ggplot","text":"Generally, need print plot ggplot2 plot explicitly: default top-level print method . , however, need call print() explicitly want draw plot inside function loop.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Explicitly draw plot — print.ggplot","text":"","code":"# S3 method for class 'ggplot' print(x, newpage = is.null(vp), vp = NULL, ...) # S3 method for class 'ggplot' plot(x, newpage = is.null(vp), vp = NULL, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Explicitly draw plot — print.ggplot","text":"x plot display newpage draw new (empty) page first? vp viewport draw plot ... arguments used method","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Explicitly draw plot — print.ggplot","text":"Invisibly returns original plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Explicitly draw plot — print.ggplot","text":"","code":"colours <- list(~class, ~drv, ~fl) # Doesn't seem to do anything! for (colour in colours) { ggplot(mpg, aes_(~ displ, ~ hwy, colour = colour)) + geom_point() } #> Warning: `aes_()` was deprecated in ggplot2 3.0.0. #> ℹ Please use tidy evaluation idioms with `aes()` # Works when we explicitly print the plots for (colour in colours) { print(ggplot(mpg, aes_(~ displ, ~ hwy, colour = colour)) + geom_point()) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":null,"dir":"Reference","previous_headings":"","what":"Format or print a ggproto object — print.ggproto","title":"Format or print a ggproto object — print.ggproto","text":"ggproto object $print method, call method. Otherwise, print members object, optionally, members inherited objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Format or print a ggproto object — print.ggproto","text":"","code":"# S3 method for class 'ggproto' print(x, ..., flat = TRUE) # S3 method for class 'ggproto' format(x, ..., flat = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Format or print a ggproto object — print.ggproto","text":"x ggproto object print. ... ggproto object print method, arguments passed . Otherwise, arguments unused. flat TRUE (default), show flattened list local inherited members. FALSE, show inheritance hierarchy.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/print.ggproto.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Format or print a ggproto object — print.ggproto","text":"","code":"Dog <- ggproto( print = function(self, n) { cat(\"Woof!\\n\") } ) Dog #> Woof! cat(format(Dog), \"\\n\") #> #> print: function"},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Quick plot — qplot","title":"Quick plot — qplot","text":"qplot() now deprecated order encourage users learn ggplot() makes easier create complex graphics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Quick plot — qplot","text":"","code":"qplot( x, y, ..., data, facets = NULL, margins = FALSE, geom = \"auto\", xlim = c(NA, NA), ylim = c(NA, NA), log = \"\", main = NULL, xlab = NULL, ylab = NULL, asp = NA, stat = deprecated(), position = deprecated() ) quickplot( x, y, ..., data, facets = NULL, margins = FALSE, geom = \"auto\", xlim = c(NA, NA), ylim = c(NA, NA), log = \"\", main = NULL, xlab = NULL, ylab = NULL, asp = NA, stat = deprecated(), position = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Quick plot — qplot","text":"x, y, ... Aesthetics passed layer data Data frame use (optional). specified, create one, extracting vectors current environment. facets faceting formula use. Picks facet_wrap() facet_grid() depending whether formula one- two-sided margins See facet_grid(): display marginal facets? geom Character vector specifying geom(s) draw. Defaults \"point\" x y specified, \"histogram\" x specified. xlim, ylim X y axis limits log variables log transform (\"x\", \"y\", \"xy\") main, xlab, ylab Character vector (expression) giving plot title, x axis label, y axis label respectively. asp y/x aspect ratio stat, position","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/qplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Quick plot — qplot","text":"","code":"# Use data from data.frame qplot(mpg, wt, data = mtcars) #> Warning: `qplot()` was deprecated in ggplot2 3.4.0. qplot(mpg, wt, data = mtcars, colour = cyl) qplot(mpg, wt, data = mtcars, size = cyl) qplot(mpg, wt, data = mtcars, facets = vs ~ am) # \\donttest{ set.seed(1) qplot(1:10, rnorm(10), colour = runif(10)) qplot(1:10, letters[1:10]) mod <- lm(mpg ~ wt, data = mtcars) qplot(resid(mod), fitted(mod)) f <- function() { a <- 1:10 b <- a ^ 2 qplot(a, b) } f() # To set aesthetics, wrap in I() qplot(mpg, wt, data = mtcars, colour = I(\"red\")) # qplot will attempt to guess what geom you want depending on the input # both x and y supplied = scatterplot qplot(mpg, wt, data = mtcars) # just x supplied = histogram qplot(mpg, data = mtcars) #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # just y supplied = scatterplot, with x = seq_along(y) qplot(y = mpg, data = mtcars) # Use different geoms qplot(mpg, wt, data = mtcars, geom = \"path\") qplot(factor(cyl), wt, data = mtcars, geom = c(\"boxplot\", \"jitter\")) qplot(mpg, data = mtcars, geom = \"dotplot\") #> Bin width defaults to 1/30 of the range of the data. Pick better value #> with `binwidth`. # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/reexports.html","id":null,"dir":"Reference","previous_headings":"","what":"Objects exported from other packages — reexports","title":"Objects exported from other packages — reexports","text":"objects imported packages. Follow links see documentation. grid arrow, unit scales alpha","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/reexports.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Objects exported from other packages — reexports","text":"","code":"ggplot(mpg, aes(displ, hwy)) + geom_point(alpha = 0.5, colour = \"blue\") ggplot(mpg, aes(displ, hwy)) + geom_point(colour = alpha(\"blue\", 0.5))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":null,"dir":"Reference","previous_headings":"","what":"Define and register new theme elements — register_theme_elements","title":"Define and register new theme elements — register_theme_elements","text":"underlying structure ggplot2 theme defined via element tree, specifies theme element type whether inherits parent element. use cases, may necessary modify extend element tree provide default settings newly defined theme elements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Define and register new theme elements — register_theme_elements","text":"","code":"register_theme_elements(..., element_tree = NULL, complete = TRUE) reset_theme_settings(reset_current = TRUE) get_element_tree() el_def(class = NULL, inherit = NULL, description = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Define and register new theme elements — register_theme_elements","text":"... Element specifications element_tree Addition modification element tree, specifies inheritance relationship theme elements. element tree must provided list named element definitions created el_def(). complete TRUE (default), elements set inherit blank elements. reset_current TRUE (default), currently active theme reset default theme. class name element class. Examples \"element_line\" \"element_text\" \"unit\", one two reserved keywords \"character\" \"margin\". reserved keyword \"character\" implies character numeric vector, class called \"character\". keyword \"margin\" implies unit vector length 4, created margin(). inherit vector strings, naming elements element inherits . description optional character vector providing description element.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Define and register new theme elements — register_theme_elements","text":"function register_theme_elements() provides option globally register new theme elements ggplot2. general, new theme element element definition corresponding entry element tree provided. See examples details. function meant primarily developers extension packages, strongly urged adhere following best practices: Call register_theme_elements() .onLoad() function package, new theme elements available anybody using functions package, irrespective whether package attached (library() require()) . new elements create, prepend name package, avoid name clashes extension packages. example, working package ggxyz, want provide new element plot panel annotations (demonstrated Examples ), name new element ggxyz.panel.annotation. function reset_theme_settings() restores default element tree, discards new element definitions, (unless turned ) resets currently active theme default. function get_element_tree() returns currently active element tree. function el_def() used define new modified element types element inheritance relationships element tree.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/register_theme_elements.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Define and register new theme elements — register_theme_elements","text":"","code":"# Let's assume a package `ggxyz` wants to provide an easy way to add annotations to # plot panels. To do so, it registers a new theme element `ggxyz.panel.annotation` register_theme_elements( ggxyz.panel.annotation = element_text(color = \"blue\", hjust = 0.95, vjust = 0.05), element_tree = list(ggxyz.panel.annotation = el_def(\"element_text\", \"text\")) ) # Now the package can define a new coord that includes a panel annotation coord_annotate <- function(label = \"panel annotation\") { ggproto(NULL, CoordCartesian, limits = list(x = NULL, y = NULL), expand = TRUE, default = FALSE, clip = \"on\", render_fg = function(panel_params, theme) { element_render(theme, \"ggxyz.panel.annotation\", label = label) } ) } # Example plot with this new coord df <- data.frame(x = 1:3, y = 1:3) ggplot(df, aes(x, y)) + geom_point() + coord_annotate(\"annotation in blue\") # Revert to the original ggplot2 settings reset_theme_settings()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/remove_missing.html","id":null,"dir":"Reference","previous_headings":"","what":"Convenience function to remove missing values from a data.frame — remove_missing","title":"Convenience function to remove missing values from a data.frame — remove_missing","text":"Remove non-complete rows, warning na.rm = FALSE. ggplot somewhat accommodating missing values R generally. stats require complete data, missing values automatically removed warning. na.rm = TRUE supplied statistic, warning suppressed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/remove_missing.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Convenience function to remove missing values from a data.frame — remove_missing","text":"","code":"remove_missing(df, na.rm = FALSE, vars = names(df), name = \"\", finite = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/remove_missing.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Convenience function to remove missing values from a data.frame — remove_missing","text":"df data.frame na.rm true, suppress warning message. vars Character vector variables check missings name Optional function name improve error message. finite TRUE, also remove non-finite values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":null,"dir":"Reference","previous_headings":"","what":"Render panel axes — render_axes","title":"Render panel axes — render_axes","text":"helpers facilitates generating theme compliant axes building plot.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Render panel axes — render_axes","text":"","code":"render_axes(x = NULL, y = NULL, coord, theme, transpose = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Render panel axes — render_axes","text":"x, y list ranges available draw_panel method Facet subclasses. coord Coord object theme theme object transpose output transposed?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_axes.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Render panel axes — render_axes","text":"list element \"x\" \"y\" containing axis specifications ranges passed . axis specification list \"top\" \"bottom\" element x-axes \"left\" \"right\" element y-axis, holding respective axis grobs. Depending content x y grobs might zeroGrobs. transpose=TRUE content x y elements transposed e.g. left-axes collected left element list grobs.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":null,"dir":"Reference","previous_headings":"","what":"Render panel strips — render_strips","title":"Render panel strips — render_strips","text":"positions rendered facet decide use","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Render panel strips — render_strips","text":"","code":"render_strips(x = NULL, y = NULL, labeller = identity, theme)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Render panel strips — render_strips","text":"x, y data.frame column variable row combination draw labeller labeller function theme theme object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/render_strips.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Render panel strips — render_strips","text":"list \"x\" \"y\" element, containing \"top\" \"bottom\" \"left\" \"right\" element respectively. contains list rendered strips gtables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute the ","title":"Compute the ","text":"resolution smallest non-zero distance adjacent values. one unique value, resolution defined one. x integer vector, assumed represent discrete variable, resolution 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute the ","text":"","code":"resolution(x, zero = TRUE, discrete = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute the ","text":"x numeric vector zero zero value automatically included computation resolution discrete vectors mapped discrete scale treated resolution 1?","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/resolution.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute the ","text":"","code":"resolution(1:10) #> [1] 1 resolution((1:10) - 0.5) #> [1] 0.5 resolution((1:10) - 0.5, FALSE) #> [1] 1 # Note the difference between numeric and integer vectors resolution(c(2, 10, 20, 50)) #> [1] 2 resolution(c(2L, 10L, 20L, 50L)) #> [1] 1"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":null,"dir":"Reference","previous_headings":"","what":"Alpha transparency scales — scale_alpha","title":"Alpha transparency scales — scale_alpha","text":"Alpha-transparency scales tremendously useful, can convenient way visually -weight less important observations. scale_alpha() alias scale_alpha_continuous() since common use alpha, saves bit typing.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Alpha transparency scales — scale_alpha","text":"","code":"scale_alpha(name = waiver(), ..., range = c(0.1, 1)) scale_alpha_continuous(name = waiver(), ..., range = c(0.1, 1)) scale_alpha_binned(name = waiver(), ..., range = c(0.1, 1)) scale_alpha_discrete(...) scale_alpha_ordinal(name = waiver(), ..., range = c(0.1, 1))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Alpha transparency scales — scale_alpha","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed continuous_scale(), binned_scale(), discrete_scale() appropriate, control name, limits, breaks, labels forth. range Output range alpha values. Must lie 0 1.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_alpha.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Alpha transparency scales — scale_alpha","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point(aes(alpha = year)) # The default range of 0.1-1.0 leaves all data visible p # Include 0 in the range to make data invisible p + scale_alpha(range = c(0, 1)) # Changing the title p + scale_alpha(\"cylinders\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":null,"dir":"Reference","previous_headings":"","what":"Positional scales for binning continuous data (x & y) — scale_binned","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"scale_x_binned() scale_y_binned() scales discretize continuous position data. can use scales transform continuous inputs using geom requires discrete positions. example using scale_x_binned() geom_bar() create histogram.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"","code":"scale_x_binned( name = waiver(), n.breaks = 10, nice.breaks = TRUE, breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = squish, na.value = NA_real_, right = TRUE, show.limits = FALSE, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"bottom\" ) scale_y_binned( name = waiver(), n.breaks = 10, nice.breaks = TRUE, breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = squish, na.value = NA_real_, right = TRUE, show.limits = FALSE, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"left\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. n.breaks number break points create breaks given directly. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::squish()) squishes bounds values range. scales::censor replacing bounds values NA. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. right intervals closed right (TRUE, default) intervals closed left (FALSE)? 'Closed right' means values break positions part lower bin (open left), whereas part upper bin intervals closed left (open right). show.limits limits scale appear ticks transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_binned.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Positional scales for binning continuous data (x & y) — scale_binned","text":"","code":"# Create a histogram by binning the x-axis ggplot(mtcars) + geom_bar(aes(mpg)) + scale_x_binned()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":null,"dir":"Reference","previous_headings":"","what":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"brewer scales provide sequential, diverging qualitative colour schemes ColorBrewer. particularly well suited display discrete values map. See https://colorbrewer2.org information.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"","code":"scale_colour_brewer( name = waiver(), ..., type = \"seq\", palette = 1, direction = 1, aesthetics = \"colour\" ) scale_fill_brewer( name = waiver(), ..., type = \"seq\", palette = 1, direction = 1, aesthetics = \"fill\" ) scale_colour_distiller( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_distiller( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_fermenter( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_fill_fermenter( name = waiver(), ..., type = \"seq\", palette = 1, direction = -1, na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed discrete_scale(), continuous_scale(), binned_scale(), brewer, distiller, fermenter variants respectively, control name, limits, breaks, labels forth. type One \"seq\" (sequential), \"div\" (diverging) \"qual\" (qualitative) palette string, use named palette. number, index list palettes appropriate type. list available palettes can found Palettes section. direction Sets order colours scale. 1, default, colours output RColorBrewer::brewer.pal(). -1, order colours reversed. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Colour use missing values guide Type legend. Use \"colourbar\" continuous colour bar, \"legend\" discrete colour legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"brewer scales carefully designed tested discrete data. designed extended continuous data, results often look good. mileage may vary.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"distiller scales extend brewer scales smoothly interpolating 7 colours palette continuous scale. distiller scales default direction = -1. reverse, use direction = 1. fermenter scales provide binned versions brewer scales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"palettes","dir":"Reference","previous_headings":"","what":"Palettes","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"following palettes available use scales: Diverging BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral Qualitative Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3 Sequential Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd Modify palette palette argument.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_brewer.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Sequential, diverging and qualitative colour scales from ColorBrewer — scale_colour_brewer","text":"","code":"set.seed(596) dsamp <- diamonds[sample(nrow(diamonds), 1000), ] (d <- ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity))) d + scale_colour_brewer() # Change scale label d + scale_colour_brewer(\"Diamond\\nclarity\") # Select brewer palette to use, see ?scales::pal_brewer for more details d + scale_colour_brewer(palette = \"Greens\") d + scale_colour_brewer(palette = \"Set1\") # \\donttest{ # scale_fill_brewer works just the same as # scale_colour_brewer but for fill colours p <- ggplot(diamonds, aes(x = price, fill = cut)) + geom_histogram(position = \"dodge\", binwidth = 1000) p + scale_fill_brewer() # the order of colour can be reversed p + scale_fill_brewer(direction = -1) # the brewer scales look better on a darker background p + scale_fill_brewer(direction = -1) + theme_dark() # } # Use distiller variant with continuous data v <- ggplot(faithfuld) + geom_tile(aes(waiting, eruptions, fill = density)) v v + scale_fill_distiller() v + scale_fill_distiller(palette = \"Spectral\") # the order of colour can be reversed, but with scale_*_distiller(), # the default direction = -1, so to reverse, use direction = 1. v + scale_fill_distiller(palette = \"Spectral\", direction = 1) # or use blender variants to discretise continuous data v + scale_fill_fermenter()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":null,"dir":"Reference","previous_headings":"","what":"Continuous and binned colour scales — scale_colour_continuous","title":"Continuous and binned colour scales — scale_colour_continuous","text":"scales scale_colour_continuous() scale_fill_continuous() default colour scales ggplot2 uses continuous data values mapped onto colour fill aesthetics, respectively. scales scale_colour_binned() scale_fill_binned() equivalent scale functions assign discrete color bins continuous values instead using continuous color spectrum.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Continuous and binned colour scales — scale_colour_continuous","text":"","code":"scale_colour_continuous(..., type = getOption(\"ggplot2.continuous.colour\")) scale_fill_continuous(..., type = getOption(\"ggplot2.continuous.fill\")) scale_colour_binned(..., type = getOption(\"ggplot2.binned.colour\")) scale_fill_binned(..., type = getOption(\"ggplot2.binned.fill\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Continuous and binned colour scales — scale_colour_continuous","text":"... Additional parameters passed scale type type One following: \"gradient\" (default) \"viridis\" function returns continuous colour scale.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Continuous and binned colour scales — scale_colour_continuous","text":"colour scales use options() mechanism determine default settings. Continuous colour scales default values ggplot2.continuous.colour ggplot2.continuous.fill options, binned colour scales default values ggplot2.binned.colour ggplot2.binned.fill options. option values default \"gradient\", means scale functions actually used scale_colour_gradient()/scale_fill_gradient() continuous scales scale_colour_steps()/scale_fill_steps() binned scales. Alternative option values \"viridis\" different scale function. See description type argument details. Note binned colour scales use settings ggplot2.continuous.colour ggplot2.continuous.fill fallback, respectively, ggplot2.binned.colour ggplot2.binned.fill set. scale functions meant provide simple defaults. want manually set colors scale, consider using scale_colour_gradient() scale_colour_steps().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"color-blindness","dir":"Reference","previous_headings":"","what":"Color Blindness","title":"Continuous and binned colour scales — scale_colour_continuous","text":"Many color palettes derived RGB combinations (like \"rainbow\" color palette) suitable support viewers, especially color vision deficiencies. Using viridis type, perceptually uniform colour black--white display easy option ensure good perceptive properties visualizations. colorspace package offers functionalities generate color palettes good perceptive properties, analyse given color palette, like emulating color blindness, modify given color palette better perceptivity. information color vision deficiencies suitable color choices see paper colorspace package references therein.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_continuous.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Continuous and binned colour scales — scale_colour_continuous","text":"","code":"v <- ggplot(faithfuld, aes(waiting, eruptions, fill = density)) + geom_tile() v v + scale_fill_continuous(type = \"gradient\") v + scale_fill_continuous(type = \"viridis\") # The above are equivalent to v + scale_fill_gradient() v + scale_fill_viridis_c() # To make a binned version of this plot v + scale_fill_binned(type = \"viridis\") # Set a different default scale using the options # mechanism tmp <- getOption(\"ggplot2.continuous.fill\") # store current setting options(ggplot2.continuous.fill = scale_fill_distiller) v options(ggplot2.continuous.fill = tmp) # restore previous setting"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":null,"dir":"Reference","previous_headings":"","what":"Discrete colour scales — scale_colour_discrete","title":"Discrete colour scales — scale_colour_discrete","text":"default discrete colour scale. Defaults scale_fill_hue()/scale_fill_brewer() unless type (defaults ggplot2.discrete.fill/ggplot2.discrete.colour options) specified.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Discrete colour scales — scale_colour_discrete","text":"","code":"scale_colour_discrete(..., type = getOption(\"ggplot2.discrete.colour\")) scale_fill_discrete(..., type = getOption(\"ggplot2.discrete.fill\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Discrete colour scales — scale_colour_discrete","text":"... Additional parameters passed scale type, type One following: character vector color codes. codes used 'manual' color scale long number codes exceeds number data levels (levels codes, scale_colour_hue()/scale_fill_hue() used construct default scale). named vector, color values matched levels based names vectors. Data values match set na.value. list character vectors color codes. minimum length vector exceeds number data levels chosen color scaling. useful want change color palette based number levels. function returns discrete colour/fill scale (e.g., scale_fill_hue(), scale_fill_brewer(), etc).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_colour_discrete.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Discrete colour scales — scale_colour_discrete","text":"","code":"# Template function for creating densities grouped by a variable cty_by_var <- function(var) { ggplot(mpg, aes(cty, colour = factor({{var}}), fill = factor({{var}}))) + geom_density(alpha = 0.2) } # The default, scale_fill_hue(), is not colour-blind safe cty_by_var(class) # (Temporarily) set the default to Okabe-Ito (which is colour-blind safe) okabe <- c(\"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#CC79A7\") withr::with_options( list(ggplot2.discrete.fill = okabe), print(cty_by_var(class)) ) # Define a collection of palettes to alter the default based on number of levels to encode discrete_palettes <- list( c(\"skyblue\", \"orange\"), RColorBrewer::brewer.pal(3, \"Set2\"), RColorBrewer::brewer.pal(6, \"Accent\") ) withr::with_options( list(ggplot2.discrete.fill = discrete_palettes), { # 1st palette is used when there 1-2 levels (e.g., year) print(cty_by_var(year)) # 2nd palette is used when there are 3 levels print(cty_by_var(drv)) # 3rd palette is used when there are 4-6 levels print(cty_by_var(fl)) }) #> Warning: Groups with fewer than two data points have been dropped. #> Warning: no non-missing arguments to max; returning -Inf"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":null,"dir":"Reference","previous_headings":"","what":"Position scales for continuous data (x & y) — scale_continuous","title":"Position scales for continuous data (x & y) — scale_continuous","text":"scale_x_continuous() scale_y_continuous() default scales continuous x y aesthetics. three variants set transform argument commonly used transformations: scale_*_log10(), scale_*_sqrt() scale_*_reverse().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Position scales for continuous data (x & y) — scale_continuous","text":"","code":"scale_x_continuous( name = waiver(), breaks = waiver(), minor_breaks = waiver(), n.breaks = NULL, labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_continuous( name = waiver(), breaks = waiver(), minor_breaks = waiver(), n.breaks = NULL, labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, transform = \"identity\", trans = deprecated(), guide = waiver(), position = \"left\", sec.axis = waiver() ) scale_x_log10(...) scale_y_log10(...) scale_x_reverse(...) scale_y_reverse(...) scale_x_sqrt(...) scale_y_sqrt(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Position scales for continuous data (x & y) — scale_continuous","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. sec.axis sec_axis() used specify secondary axis. ... arguments passed scale_(x|y)_continuous()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Position scales for continuous data (x & y) — scale_continuous","text":"simple manipulation labels limits, may wish use labs() lims() instead.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_continuous.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position scales for continuous data (x & y) — scale_continuous","text":"","code":"p1 <- ggplot(mpg, aes(displ, hwy)) + geom_point() p1 # Manipulating the default position scales lets you: # * change the axis labels p1 + scale_x_continuous(\"Engine displacement (L)\") + scale_y_continuous(\"Highway MPG\") # You can also use the short-cut labs(). # Use NULL to suppress axis labels p1 + labs(x = NULL, y = NULL) # * modify the axis limits p1 + scale_x_continuous(limits = c(2, 6)) #> Warning: Removed 27 rows containing missing values or values outside the scale #> range (`geom_point()`). p1 + scale_x_continuous(limits = c(0, 10)) # you can also use the short hand functions `xlim()` and `ylim()` p1 + xlim(2, 6) #> Warning: Removed 27 rows containing missing values or values outside the scale #> range (`geom_point()`). # * choose where the ticks appear p1 + scale_x_continuous(breaks = c(2, 4, 6)) # * choose your own labels p1 + scale_x_continuous( breaks = c(2, 4, 6), label = c(\"two\", \"four\", \"six\") ) # Typically you'll pass a function to the `labels` argument. # Some common formats are built into the scales package: set.seed(1) df <- data.frame( x = rnorm(10) * 100000, y = seq(0, 1, length.out = 10) ) p2 <- ggplot(df, aes(x, y)) + geom_point() p2 + scale_y_continuous(labels = scales::label_percent()) p2 + scale_y_continuous(labels = scales::label_dollar()) p2 + scale_x_continuous(labels = scales::label_comma()) # You can also override the default linear mapping by using a # transformation. There are three shortcuts: p1 + scale_y_log10() p1 + scale_y_sqrt() p1 + scale_y_reverse() # Or you can supply a transformation in the `trans` argument: p1 + scale_y_continuous(transform = scales::transform_reciprocal()) # You can also create your own. See ?scales::new_transform"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":null,"dir":"Reference","previous_headings":"","what":"Position scales for date/time data — scale_date","title":"Position scales for date/time data — scale_date","text":"default scales three date/time class. usually added automatically. override manually, use scale_*_date dates (class Date), scale_*_datetime datetimes (class POSIXct), scale_*_time times (class hms).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Position scales for date/time data — scale_date","text":"","code":"scale_x_date( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_date( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"left\", sec.axis = waiver() ) scale_x_datetime( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), timezone = NULL, limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_datetime( name = waiver(), breaks = waiver(), date_breaks = waiver(), labels = waiver(), date_labels = waiver(), minor_breaks = waiver(), date_minor_breaks = waiver(), timezone = NULL, limits = NULL, expand = waiver(), oob = censor, guide = waiver(), position = \"left\", sec.axis = waiver() ) scale_x_time( name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_time( name = waiver(), breaks = waiver(), minor_breaks = waiver(), labels = waiver(), limits = NULL, expand = waiver(), oob = censor, na.value = NA_real_, guide = waiver(), position = \"left\", sec.axis = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Position scales for date/time data — scale_date","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() breaks specified date_breaks Date/POSIXct vector giving positions breaks function takes limits input returns breaks output date_breaks string giving distance breaks like \"2 weeks\", \"10 years\". breaks date_breaks specified, date_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. date_labels string giving formatting specification labels. Codes defined strftime(). labels date_labels specified, date_labels wins. minor_breaks One : NULL breaks waiver() breaks specified date_minor_breaks Date/POSIXct vector giving positions minor breaks function takes limits input returns minor breaks output date_minor_breaks string giving distance minor breaks like \"2 weeks\", \"10 years\". minor_breaks date_minor_breaks specified, date_minor_breaks wins. Valid specifications 'sec', 'min', 'hour', 'day', 'week', 'month' 'year', optionally followed 's'. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. sec.axis sec_axis() used specify secondary axis. timezone timezone use display axes. default (NULL) uses timezone encoded data. na.value Missing values replaced value.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_date.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position scales for date/time data — scale_date","text":"","code":"last_month <- Sys.Date() - 0:29 set.seed(1) df <- data.frame( date = last_month, price = runif(30) ) base <- ggplot(df, aes(date, price)) + geom_line() # The date scale will attempt to pick sensible defaults for # major and minor tick marks. Override with date_breaks, date_labels # date_minor_breaks arguments. base + scale_x_date(date_labels = \"%b %d\") base + scale_x_date(date_breaks = \"1 week\", date_labels = \"%W\") base + scale_x_date(date_minor_breaks = \"1 day\") # Set limits base + scale_x_date(limits = c(Sys.Date() - 7, NA)) #> Warning: Removed 22 rows containing missing values or values outside the scale #> range (`geom_line()`)."},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":null,"dir":"Reference","previous_headings":"","what":"Position scales for discrete data — scale_x_discrete","title":"Position scales for discrete data — scale_x_discrete","text":"scale_x_discrete() scale_y_discrete() used set values discrete x y scale aesthetics. simple manipulation scale labels limits, may wish use labs() lims() instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Position scales for discrete data — scale_x_discrete","text":"","code":"scale_x_discrete( name = waiver(), ..., palette = seq_len, expand = waiver(), guide = waiver(), position = \"bottom\", sec.axis = waiver() ) scale_y_discrete( name = waiver(), ..., palette = seq_len, expand = waiver(), guide = waiver(), position = \"left\", sec.axis = waiver() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Position scales for discrete data — scale_x_discrete","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. na.value na.translate = TRUE, aesthetic value missing values displayed ? apply position scales NA always placed far right. aesthetics names aesthetics scale works . minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. call call used construct scale reporting messages. super super class use constructed scale palette palette function called single integer argument (number levels scale) returns numerical values take. expand position scales, vector range expansion constants used add padding around data ensure placed distance away axes. Use convenience function expansion() generate values expand argument. defaults expand scale 5% side continuous variables, 0.6 units side discrete variables. guide function used create guide name. See guides() information. position position scales, position axis. left right y axes, top bottom x axes. sec.axis dup_axis() used specify secondary axis.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Position scales for discrete data — scale_x_discrete","text":"can use continuous positions even discrete position scale - allows (e.g.) place labels bars bar chart. Continuous positions numeric values starting one first level, increasing one level (.e. labels placed integer positions). allows jittering work.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_discrete.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Position scales for discrete data — scale_x_discrete","text":"","code":"ggplot(diamonds, aes(cut)) + geom_bar() # \\donttest{ # The discrete position scale is added automatically whenever you # have a discrete position. (d <- ggplot(subset(diamonds, carat > 1), aes(cut, clarity)) + geom_jitter()) d + scale_x_discrete(\"Cut\") d + scale_x_discrete( \"Cut\", labels = c( \"Fair\" = \"F\", \"Good\" = \"G\", \"Very Good\" = \"VG\", \"Perfect\" = \"P\", \"Ideal\" = \"I\" ) ) # Use limits to adjust the which levels (and in what order) # are displayed d + scale_x_discrete(limits = c(\"Fair\",\"Ideal\")) #> Warning: Removed 11189 rows containing missing values or values outside the scale #> range (`geom_point()`). # you can also use the short hand functions xlim and ylim d + xlim(\"Fair\",\"Ideal\", \"Good\") #> Warning: Removed 9610 rows containing missing values or values outside the scale #> range (`geom_point()`). d + ylim(\"I1\", \"IF\") #> Warning: Removed 16770 rows containing missing values or values outside the scale #> range (`geom_point()`). # See ?reorder to reorder based on the values of another variable ggplot(mpg, aes(manufacturer, cty)) + geom_point() ggplot(mpg, aes(reorder(manufacturer, cty), cty)) + geom_point() ggplot(mpg, aes(reorder(manufacturer, displ), cty)) + geom_point() # Use abbreviate as a formatter to reduce long names ggplot(mpg, aes(reorder(manufacturer, displ), cty)) + geom_point() + scale_x_discrete(labels = abbreviate) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":null,"dir":"Reference","previous_headings":"","what":"Gradient colour scales — scale_colour_gradient","title":"Gradient colour scales — scale_colour_gradient","text":"scale_*_gradient creates two colour gradient (low-high), scale_*_gradient2 creates diverging colour gradient (low-mid-high), scale_*_gradientn creates n-colour gradient. binned variants scales, see color steps scales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Gradient colour scales — scale_colour_gradient","text":"","code":"scale_colour_gradient( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_gradient( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_gradient2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_gradient2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_gradientn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\", colors ) scale_fill_gradientn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\", colors )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Gradient colour scales — scale_colour_gradient","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed continuous_scale scale_name name scale used error messages associated scale. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). rescaler function used scale input values range [0, 1]. always scales::rescale(), except diverging n colour gradients (.e., scale_colour_gradient2(), scale_colour_gradientn()). rescaler ignored position scales, always use scales::rescale(). Also accepts rlang lambda function notation. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. trans Deprecated favour transform. call call used construct scale reporting messages. super super class use constructed scale low, high Colours low high ends gradient. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Colour use missing values guide Type legend. Use \"colourbar\" continuous colour bar, \"legend\" discrete colour legend. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). mid colour mid point midpoint midpoint (data value) diverging scale. Defaults 0. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). colours, colors Vector colours use n-colour gradient. values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Gradient colour scales — scale_colour_gradient","text":"Default colours generated munsell mnsl(c(\"2.5PB 2/4\", \"2.5PB 7/10\")). Generally, continuous colour scales want keep hue constant, vary chroma luminance. munsell package makes easy using Munsell colour system.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_gradient.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Gradient colour scales — scale_colour_gradient","text":"","code":"set.seed(1) df <- data.frame( x = runif(100), y = runif(100), z1 = rnorm(100), z2 = abs(rnorm(100)) ) df_na <- data.frame( value = seq(1, 20), x = runif(20), y = runif(20), z1 = c(rep(NA, 10), rnorm(10)) ) # Default colour scale colours from light blue to dark blue ggplot(df, aes(x, y)) + geom_point(aes(colour = z2)) # For diverging colour scales use gradient2 ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradient2() # Use your own colour scale with gradientn ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradientn(colours = terrain.colors(10)) # The gradientn scale can be centered by using a rescaler ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradientn( colours = c(\"blue\", \"dodgerblue\", \"white\", \"orange\", \"red\"), rescaler = ~ scales::rescale_mid(.x, mid = 0) ) # Equivalent fill scales do the same job for the fill aesthetic ggplot(faithfuld, aes(waiting, eruptions)) + geom_raster(aes(fill = density)) + scale_fill_gradientn(colours = terrain.colors(10)) # Adjust colour choices with low and high ggplot(df, aes(x, y)) + geom_point(aes(colour = z2)) + scale_colour_gradient(low = \"white\", high = \"black\") # Avoid red-green colour contrasts because ~10% of men have difficulty # seeing them # Use `na.value = NA` to hide missing values but keep the original axis range ggplot(df_na, aes(x = value, y)) + geom_bar(aes(fill = z1), stat = \"identity\") + scale_fill_gradient(low = \"yellow\", high = \"red\", na.value = NA) ggplot(df_na, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradient(low = \"yellow\", high = \"red\", na.value = NA) #> Warning: Removed 10 rows containing missing values or values outside the scale #> range (`geom_point()`)."},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":null,"dir":"Reference","previous_headings":"","what":"Sequential grey colour scales — scale_colour_grey","title":"Sequential grey colour scales — scale_colour_grey","text":"Based gray.colors(). black white equivalent scale_colour_gradient().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Sequential grey colour scales — scale_colour_grey","text":"","code":"scale_colour_grey( name = waiver(), ..., start = 0.2, end = 0.8, na.value = \"red\", aesthetics = \"colour\" ) scale_fill_grey( name = waiver(), ..., start = 0.2, end = 0.8, na.value = \"red\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Sequential grey colour scales — scale_colour_grey","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale start grey value low end palette end grey value high end palette na.value Colour use missing values aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_grey.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Sequential grey colour scales — scale_colour_grey","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl))) p + scale_colour_grey() p + scale_colour_grey(end = 0) # You may want to turn off the pale grey background with this scale p + scale_colour_grey() + theme_bw() # Colour of missing values is controlled with na.value: miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) + scale_colour_grey() ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) + scale_colour_grey(na.value = \"green\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":null,"dir":"Reference","previous_headings":"","what":"Evenly spaced colours for discrete data — scale_colour_hue","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"Maps level evenly spaced hue colour wheel. generate colour-blind safe palettes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"","code":"scale_colour_hue( name = waiver(), ..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = \"grey50\", aesthetics = \"colour\" ) scale_fill_hue( name = waiver(), ..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = \"grey50\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale h range hues use, [0, 360] c chroma (intensity colour), maximum value varies depending combination hue luminance. l luminance (lightness), [0, 100] h.start hue start direction direction travel around colour wheel, 1 = clockwise, -1 = counter-clockwise na.value Colour use missing values aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_hue.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Evenly spaced colours for discrete data — scale_colour_hue","text":"","code":"# \\donttest{ set.seed(596) dsamp <- diamonds[sample(nrow(diamonds), 1000), ] (d <- ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity))) # Change scale label d + scale_colour_hue() d + scale_colour_hue(\"clarity\") d + scale_colour_hue(expression(clarity[beta])) # Adjust luminosity and chroma d + scale_colour_hue(l = 40, c = 30) d + scale_colour_hue(l = 70, c = 30) d + scale_colour_hue(l = 70, c = 150) d + scale_colour_hue(l = 80, c = 150) # Change range of hues used d + scale_colour_hue(h = c(0, 90)) d + scale_colour_hue(h = c(90, 180)) d + scale_colour_hue(h = c(180, 270)) d + scale_colour_hue(h = c(270, 360)) # Vary opacity # (only works with pdf, quartz and cairo devices) d <- ggplot(dsamp, aes(carat, price, colour = clarity)) d + geom_point(alpha = 0.9) d + geom_point(alpha = 0.5) d + geom_point(alpha = 0.2) # Colour of missing values is controlled with na.value: miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = miss)) + scale_colour_hue(na.value = \"black\") # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":null,"dir":"Reference","previous_headings":"","what":"Use values without scaling — scale_identity","title":"Use values without scaling — scale_identity","text":"Use set scales data already scaled, .e. already represents aesthetic values ggplot2 can handle directly. scales produce legend unless also supply breaks, labels, type guide want.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Use values without scaling — scale_identity","text":"","code":"scale_colour_identity( name = waiver(), ..., guide = \"none\", aesthetics = \"colour\" ) scale_fill_identity(name = waiver(), ..., guide = \"none\", aesthetics = \"fill\") scale_shape_identity(name = waiver(), ..., guide = \"none\") scale_linetype_identity(name = waiver(), ..., guide = \"none\") scale_linewidth_identity(name = waiver(), ..., guide = \"none\") scale_alpha_identity(name = waiver(), ..., guide = \"none\") scale_size_identity(name = waiver(), ..., guide = \"none\") scale_discrete_identity(aesthetics, name = waiver(), ..., guide = \"none\") scale_continuous_identity(aesthetics, name = waiver(), ..., guide = \"none\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Use values without scaling — scale_identity","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed discrete_scale() continuous_scale() guide Guide use scale. Defaults \"none\". aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Use values without scaling — scale_identity","text":"functions scale_colour_identity(), scale_fill_identity(), scale_size_identity(), etc. work aesthetics specified scale name: colour, fill, size, etc. However, functions scale_colour_identity() scale_fill_identity() also optional aesthetics argument can used define colour fill aesthetic mappings via single function call. functions scale_discrete_identity() scale_continuous_identity() generic scales can work aesthetic set aesthetics provided via aesthetics argument.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_identity.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Use values without scaling — scale_identity","text":"","code":"ggplot(luv_colours, aes(u, v)) + geom_point(aes(colour = col), size = 3) + scale_color_identity() + coord_fixed() df <- data.frame( x = 1:4, y = 1:4, colour = c(\"red\", \"green\", \"blue\", \"yellow\") ) ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) + scale_fill_identity() # To get a legend guide, specify guide = \"legend\" ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) + scale_fill_identity(guide = \"legend\") # But you'll typically also need to supply breaks and labels: ggplot(df, aes(x, y)) + geom_tile(aes(fill = colour)) + scale_fill_identity(\"trt\", labels = letters[1:4], breaks = df$colour, guide = \"legend\") # cyl scaled to appropriate size ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(size = cyl)) # cyl used as point size ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(size = cyl)) + scale_size_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":null,"dir":"Reference","previous_headings":"","what":"Scale for line patterns — scale_linetype","title":"Scale for line patterns — scale_linetype","text":"Default line types based set supplied Richard Pearson, University Manchester. Continuous values can mapped line types unless scale_linetype_binned() used. Still, linetypes inherent order, use advised.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scale for line patterns — scale_linetype","text":"","code":"scale_linetype(name = waiver(), ..., na.value = \"blank\") scale_linetype_binned(name = waiver(), ..., na.value = \"blank\") scale_linetype_continuous(...) scale_linetype_discrete(name = waiver(), ..., na.value = \"blank\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scale for line patterns — scale_linetype","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. aesthetics names aesthetics scale works . minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale na.value linetype use NA values.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linetype.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scale for line patterns — scale_linetype","text":"","code":"base <- ggplot(economics_long, aes(date, value01)) base + geom_line(aes(group = variable)) base + geom_line(aes(linetype = variable)) # See scale_manual for more flexibility # Common line types ---------------------------- df_lines <- data.frame( linetype = factor( 1:4, labels = c(\"solid\", \"longdash\", \"dashed\", \"dotted\") ) ) ggplot(df_lines) + geom_hline(aes(linetype = linetype, yintercept = 0), linewidth = 2) + scale_linetype_identity() + facet_grid(linetype ~ .) + theme_void(20)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":null,"dir":"Reference","previous_headings":"","what":"Scales for line width — scale_linewidth","title":"Scales for line width — scale_linewidth","text":"scale_linewidth scales width lines polygon strokes. Due historical reasons, also possible control size aesthetic, using linewidth encourage clearly differentiate area aesthetics stroke width aesthetics.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scales for line width — scale_linewidth","text":"","code":"scale_linewidth( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = \"identity\", trans = deprecated(), guide = \"legend\" ) scale_linewidth_binned( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), n.breaks = NULL, nice.breaks = TRUE, transform = \"identity\", trans = deprecated(), guide = \"bins\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scales for line width — scale_linewidth","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). range numeric vector length 2 specifies minimum maximum size plotting symbol transformation. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_linewidth.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scales for line width — scale_linewidth","text":"","code":"p <- ggplot(economics, aes(date, unemploy, linewidth = uempmed)) + geom_line(lineend = \"round\") p p + scale_linewidth(\"Duration of\\nunemployment\") p + scale_linewidth(range = c(0, 4)) # Binning can sometimes make it easier to match the scaled data to the legend p + scale_linewidth_binned()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":null,"dir":"Reference","previous_headings":"","what":"Create your own discrete scale — scale_manual","title":"Create your own discrete scale — scale_manual","text":"functions allow specify set mappings levels data aesthetic values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Create your own discrete scale — scale_manual","text":"","code":"scale_colour_manual( ..., values, aesthetics = \"colour\", breaks = waiver(), na.value = \"grey50\" ) scale_fill_manual( ..., values, aesthetics = \"fill\", breaks = waiver(), na.value = \"grey50\" ) scale_size_manual(..., values, breaks = waiver(), na.value = NA) scale_shape_manual(..., values, breaks = waiver(), na.value = NA) scale_linetype_manual(..., values, breaks = waiver(), na.value = \"blank\") scale_linewidth_manual(..., values, breaks = waiver(), na.value = NA) scale_alpha_manual(..., values, breaks = waiver(), na.value = NA) scale_discrete_manual(aesthetics, ..., values, breaks = waiver())"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Create your own discrete scale — scale_manual","text":"... Arguments passed discrete_scale limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale values set aesthetic values map data values . values matched order (usually alphabetical) limits scale, breaks provided. named vector, values matched based names instead. Data values match given na.value. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output na.value aesthetic value use missing (NA) values","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Create your own discrete scale — scale_manual","text":"functions scale_colour_manual(), scale_fill_manual(), scale_size_manual(), etc. work aesthetics specified scale name: colour, fill, size, etc. However, functions scale_colour_manual() scale_fill_manual() also optional aesthetics argument can used define colour fill aesthetic mappings via single function call (see examples). function scale_discrete_manual() generic scale can work aesthetic set aesthetics provided via aesthetics argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"color-blindness","dir":"Reference","previous_headings":"","what":"Color Blindness","title":"Create your own discrete scale — scale_manual","text":"Many color palettes derived RGB combinations (like \"rainbow\" color palette) suitable support viewers, especially color vision deficiencies. Using viridis type, perceptually uniform colour black--white display easy option ensure good perceptive properties visualizations. colorspace package offers functionalities generate color palettes good perceptive properties, analyse given color palette, like emulating color blindness, modify given color palette better perceptivity. information color vision deficiencies suitable color choices see paper colorspace package references therein.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_manual.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Create your own discrete scale — scale_manual","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl))) p + scale_colour_manual(values = c(\"red\", \"blue\", \"green\")) # It's recommended to use a named vector cols <- c(\"8\" = \"red\", \"4\" = \"blue\", \"6\" = \"darkgreen\", \"10\" = \"orange\") p + scale_colour_manual(values = cols) # You can set color and fill aesthetics at the same time ggplot( mtcars, aes(mpg, wt, colour = factor(cyl), fill = factor(cyl)) ) + geom_point(shape = 21, alpha = 0.5, size = 2) + scale_colour_manual( values = cols, aesthetics = c(\"colour\", \"fill\") ) # As with other scales you can use breaks to control the appearance # of the legend. p + scale_colour_manual(values = cols) p + scale_colour_manual( values = cols, breaks = c(\"4\", \"6\", \"8\"), labels = c(\"four\", \"six\", \"eight\") ) # And limits to control the possible values of the scale p + scale_colour_manual(values = cols, limits = c(\"4\", \"8\")) p + scale_colour_manual(values = cols, limits = c(\"4\", \"6\", \"8\", \"10\"))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":null,"dir":"Reference","previous_headings":"","what":"Scales for shapes, aka glyphs — scale_shape","title":"Scales for shapes, aka glyphs — scale_shape","text":"scale_shape() maps discrete variables six easily discernible shapes. six levels, get warning message, seventh subsequent levels appear plot. Use scale_shape_manual() supply values. can map continuous variable shape unless scale_shape_binned() used. Still, shape inherent order, use advised.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scales for shapes, aka glyphs — scale_shape","text":"","code":"scale_shape(name = waiver(), ..., solid = TRUE) scale_shape_binned(name = waiver(), ..., solid = TRUE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scales for shapes, aka glyphs — scale_shape","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed discrete_scale breaks One : NULL breaks waiver() default breaks (scale limits) character vector breaks function takes limits input returns breaks output. Also accepts rlang lambda function notation. limits One : NULL use default scale values character vector defines possible values scale order function accepts existing (automatic) values returns new ones. Also accepts rlang lambda function notation. drop unused factor levels omitted scale? default, TRUE, uses levels appear data; FALSE includes levels factor. Please note display every level legend, layer use show.legend = TRUE. na.translate Unlike continuous scales, discrete scales can easily show missing values, default. want remove missing values discrete scale, specify na.translate = FALSE. na.value na.translate = TRUE, aesthetic value missing values displayed ? apply position scales NA always placed far right. aesthetics names aesthetics scale works . minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. guide function used create guide name. See guides() information. call call used construct scale reporting messages. super super class use constructed scale solid shapes solid, TRUE, hollow, FALSE?","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_shape.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scales for shapes, aka glyphs — scale_shape","text":"","code":"set.seed(596) dsmall <- diamonds[sample(nrow(diamonds), 100), ] (d <- ggplot(dsmall, aes(carat, price)) + geom_point(aes(shape = cut))) #> Warning: Using shapes for an ordinal variable is not advised d + scale_shape(solid = TRUE) # the default d + scale_shape(solid = FALSE) d + scale_shape(name = \"Cut of diamond\") # To change order of levels, change order of # underlying factor levels(dsmall$cut) <- c(\"Fair\", \"Good\", \"Very Good\", \"Premium\", \"Ideal\") # Need to recreate plot to pick up new data ggplot(dsmall, aes(price, carat)) + geom_point(aes(shape = cut)) #> Warning: Using shapes for an ordinal variable is not advised # Show a list of available shapes 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()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":null,"dir":"Reference","previous_headings":"","what":"Scales for area or radius — scale_size","title":"Scales for area or radius — scale_size","text":"scale_size() scales area, scale_radius() scales radius. size aesthetic commonly used points text, humans perceive area points (radius), provides optimal perception. scale_size_area() ensures value 0 mapped size 0. scale_size_binned() binned version scale_size() scales area (ensure 0 equals area zero). binned equivalent scale_size_area() use scale_size_binned_area().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Scales for area or radius — scale_size","text":"","code":"scale_size( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = \"identity\", trans = deprecated(), guide = \"legend\" ) scale_radius( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = \"identity\", trans = deprecated(), guide = \"legend\" ) scale_size_binned( name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), n.breaks = NULL, nice.breaks = TRUE, transform = \"identity\", trans = deprecated(), guide = \"bins\" ) scale_size_area(name = waiver(), ..., max_size = 6) scale_size_binned_area(name = waiver(), ..., max_size = 6)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Scales for area or radius — scale_size","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). range numeric vector length 2 specifies minimum maximum size plotting symbol transformation. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). trans Deprecated favour transform. guide function used create guide name. See guides() information. n.breaks integer guiding number major breaks. algorithm may choose slightly different number ensure nice break labels. effect breaks = waiver(). Use NULL use default number breaks given transformation. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. ... Arguments passed continuous_scale minor_breaks One : NULL minor breaks waiver() default breaks (none discrete, one minor break major break continuous) numeric vector positions function given limits returns vector minor breaks. Also accepts rlang lambda function notation. function two arguments, given limits major break positions. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::censor()) replaces bounds values NA. scales::squish() squishing bounds values range. scales::squish_infinite() squishing infinite values range. na.value Missing values replaced value. call call used construct scale reporting messages. super super class use constructed scale max_size Size largest points.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Scales for area or radius — scale_size","text":"Historically size aesthetic used two different things: Scaling size object (like points glyphs) scaling width lines. ggplot2 3.4.0 latter moved linewidth aesthetic. backwards compatibility using size still possible, highly advised switch new linewidth aesthetic cases.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_size.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Scales for area or radius — scale_size","text":"","code":"p <- ggplot(mpg, aes(displ, hwy, size = hwy)) + geom_point() p p + scale_size(\"Highway mpg\") p + scale_size(range = c(0, 10)) # If you want zero value to have zero size, use scale_size_area: p + scale_size_area() # Binning can sometimes make it easier to match the scaled data to the legend p + scale_size_binned() # This is most useful when size is a count ggplot(mpg, aes(class, cyl)) + geom_count() + scale_size_area() # If you want to map size to radius (usually bad idea), use scale_radius p + scale_radius()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":null,"dir":"Reference","previous_headings":"","what":"Binned gradient colour scales — scale_colour_steps","title":"Binned gradient colour scales — scale_colour_steps","text":"scale_*_steps creates two colour binned gradient (low-high), scale_*_steps2 creates diverging binned colour gradient (low-mid-high), scale_*_stepsn creates n-colour binned gradient. scales binned variants gradient scale family works way.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Binned gradient colour scales — scale_colour_steps","text":"","code":"scale_colour_steps( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_colour_steps2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_colour_stepsn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\", colors ) scale_fill_steps( name = waiver(), ..., low = \"#132B43\", high = \"#56B1F7\", space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\" ) scale_fill_steps2( name = waiver(), ..., low = muted(\"red\"), mid = \"white\", high = muted(\"blue\"), midpoint = 0, space = \"Lab\", na.value = \"grey50\", transform = \"identity\", guide = \"coloursteps\", aesthetics = \"fill\" ) scale_fill_stepsn( name = waiver(), ..., colours, values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\", colors )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Binned gradient colour scales — scale_colour_steps","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... Arguments passed binned_scale n.breaks number break points create breaks given directly. nice.breaks Logical. breaks attempted placed nice values instead exactly evenly spaced limits. TRUE (default) scale ask transformation object create breaks, may result different number breaks requested. Ignored breaks given explicitly. oob One : Function handles limits outside scale limits (bounds). Also accepts rlang lambda function notation. default (scales::squish()) squishes bounds values range. scales::censor replacing bounds values NA. scales::squish_infinite() squishing infinite values range. right intervals closed right (TRUE, default) intervals closed left (FALSE)? 'Closed right' means values break positions part lower bin (open left), whereas part upper bin intervals closed left (open right). show.limits limits scale appear ticks breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output (e.g., function returned scales::extended_breaks()). Note position scales, limits provided scale expansion. Also accepts rlang lambda function notation. labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) expression vector (must length breaks). See ?plotmath details. function takes breaks input returns labels output. Also accepts rlang lambda function notation. limits One : NULL use default scale range numeric vector length two providing limits scale. Use NA refer existing minimum maximum function accepts existing (automatic) limits returns new limits. Also accepts rlang lambda function notation. Note setting limits positional scales remove data outside limits. purpose zoom, use limit argument coordinate system (see coord_cartesian()). trans Deprecated favour transform. call call used construct scale reporting messages. super super class use constructed scale low, high Colours low high ends gradient. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Colour use missing values guide Type legend. Use \"colourbar\" continuous colour bar, \"legend\" discrete colour legend. aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). mid colour mid point midpoint midpoint (data value) diverging scale. Defaults 0. transform continuous scales, name transformation object object . Built-transformations include \"asn\", \"atanh\", \"boxcox\", \"date\", \"exp\", \"hms\", \"identity\", \"log\", \"log10\", \"log1p\", \"log2\", \"logit\", \"modulus\", \"probability\", \"probit\", \"pseudo_log\", \"reciprocal\", \"reverse\", \"sqrt\" \"time\". transformation object bundles together transform, inverse, methods generating breaks labels. Transformation objects defined scales package, called transform_. transformations require arguments, can call scales package, e.g. scales::transform_boxcox(p = 2). can create transformation scales::new_transform(). colours, colors Vector colours use n-colour gradient. values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Binned gradient colour scales — scale_colour_steps","text":"Default colours generated munsell mnsl(c(\"2.5PB 2/4\", \"2.5PB 7/10\")). Generally, continuous colour scales want keep hue constant, vary chroma luminance. munsell package makes easy using Munsell colour system.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_steps.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Binned gradient colour scales — scale_colour_steps","text":"","code":"set.seed(1) df <- data.frame( x = runif(100), y = runif(100), z1 = rnorm(100) ) # Use scale_colour_steps for a standard binned gradient ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_steps() # Get a divergent binned scale with the *2 variant ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_steps2() # Define your own colour ramp to extract binned colours from ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_stepsn(colours = terrain.colors(10))"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":null,"dir":"Reference","previous_headings":"","what":"Determine default scale type — scale_type","title":"Determine default scale type — scale_type","text":"need define method method want extend ggplot2 handle new types data. simply want pass vector additional aesthetic, return \"identity\".","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Determine default scale type — scale_type","text":"","code":"scale_type(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Determine default scale type — scale_type","text":"x vector","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Determine default scale type — scale_type","text":"character vector scale types. tried turn find default scale. example, scale_type() returns c(\"foo\", \"bar\") vector used colour aesthetic, ggplot2 first look scale_colour_foo scale_colour_bar.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_type.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Determine default scale type — scale_type","text":"","code":"scale_type(1:5) #> [1] \"continuous\" scale_type(\"test\") #> [1] \"discrete\" scale_type(Sys.Date()) #> [1] \"date\" \"continuous\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":null,"dir":"Reference","previous_headings":"","what":"Viridis colour scales from viridisLite — scale_colour_viridis_d","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"viridis scales provide colour maps perceptually uniform colour black--white. also designed perceived viewers common forms colour blindness. See also https://bids.github.io/colormap/.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"","code":"scale_colour_viridis_d( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", aesthetics = \"colour\" ) scale_fill_viridis_d( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", aesthetics = \"fill\" ) scale_colour_viridis_c( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"colour\" ) scale_fill_viridis_c( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\" ) scale_colour_viridis_b( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"colour\" ) scale_fill_viridis_b( name = waiver(), ..., alpha = 1, begin = 0, end = 1, direction = 1, option = \"D\", values = NULL, space = \"Lab\", na.value = \"grey50\", guide = \"coloursteps\", aesthetics = \"fill\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"name name scale. Used axis legend title. waiver(), default, name scale taken first mapping used aesthetic. NULL, legend title omitted. ... arguments passed discrete_scale(), continuous_scale(), binned_scale() control name, limits, breaks, labels forth. alpha alpha transparency, number [0,1], see argument alpha hsv. begin, end (corrected) hue [0,1] color map begins ends. direction Sets order colors scale. 1, default, colors ordered darkest lightest. -1, order colors reversed. option character string indicating color map option use. Eight options available: \"magma\" (\"\") \"inferno\" (\"B\") \"plasma\" (\"C\") \"viridis\" (\"D\") \"cividis\" (\"E\") \"rocket\" (\"F\") \"mako\" (\"G\") \"turbo\" (\"H\") aesthetics Character string vector character strings listing name(s) aesthetic(s) scale works . can useful, example, apply colour settings colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\"). values colours evenly positioned along gradient vector gives position (0 1) colour colours vector. See rescale() convenience function map arbitrary range 0 1. space colour space calculate gradient. Must \"Lab\" - values deprecated. na.value Missing values replaced value. guide function used create guide name. See guides() information.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/scale_viridis.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Viridis colour scales from viridisLite — scale_colour_viridis_d","text":"","code":"# viridis is the default colour/fill scale for ordered factors set.seed(596) dsamp <- diamonds[sample(nrow(diamonds), 1000), ] ggplot(dsamp, aes(carat, price)) + geom_point(aes(colour = clarity)) # Use viridis_d with discrete data txsamp <- subset(txhousing, city %in% c(\"Houston\", \"Fort Worth\", \"San Antonio\", \"Dallas\", \"Austin\")) (d <- ggplot(data = txsamp, aes(x = sales, y = median)) + geom_point(aes(colour = city))) d + scale_colour_viridis_d() # Change scale label d + scale_colour_viridis_d(\"City\\nCenter\") # Select palette to use, see ?scales::pal_viridis for more details d + scale_colour_viridis_d(option = \"plasma\") d + scale_colour_viridis_d(option = \"inferno\") # scale_fill_viridis_d works just the same as # scale_colour_viridis_d but for fill colours p <- ggplot(txsamp, aes(x = median, fill = city)) + geom_histogram(position = \"dodge\", binwidth = 15000) p + scale_fill_viridis_d() # the order of colour can be reversed p + scale_fill_viridis_d(direction = -1) # Use viridis_c with continuous data (v <- ggplot(faithfuld) + geom_tile(aes(waiting, eruptions, fill = density))) v + scale_fill_viridis_c() v + scale_fill_viridis_c(option = \"plasma\") # Use viridis_b to bin continuous data before mapping v + scale_fill_viridis_b()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":null,"dir":"Reference","previous_headings":"","what":"Vector field of seal movements — seals","title":"Vector field of seal movements — seals","text":"vector field produced data described Brillinger, D.R., Preisler, H.K., Ager, .. Kie, J.G. \"exploratory data analysis (EDA) paths moving animals\". J. Statistical Planning Inference 122 (2004), 43-63, using methods Brillinger, D.R., \"Learning potential function trajectory\", Signal Processing Letters. December (2007).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Vector field of seal movements — seals","text":"","code":"seals"},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Vector field of seal movements — seals","text":"data frame 1155 rows 4 variables","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/seals.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Vector field of seal movements — seals","text":"https://www.stat.berkeley.edu/~brill/Papers/jspifinal.pdf","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":null,"dir":"Reference","previous_headings":"","what":"Specify a secondary axis — sec_axis","title":"Specify a secondary axis — sec_axis","text":"function used conjunction position scale create secondary axis, positioned opposite primary axis. secondary axes must based one--one transformation primary axes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Specify a secondary axis — sec_axis","text":"","code":"sec_axis( transform = NULL, name = waiver(), breaks = waiver(), labels = waiver(), guide = waiver(), trans = deprecated() ) dup_axis( transform = identity, name = derive(), breaks = derive(), labels = derive(), guide = derive(), trans = deprecated() ) derive()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Specify a secondary axis — sec_axis","text":"transform formula function strictly monotonic transformation name name secondary axis breaks One : NULL breaks waiver() default breaks computed transformation object numeric vector positions function takes limits input returns breaks output labels One : NULL labels waiver() default labels computed transformation object character vector giving labels (must length breaks) function takes breaks input returns labels output guide position guide used render axis plot. Usually guide_axis(). trans","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Specify a secondary axis — sec_axis","text":"sec_axis() used create specifications secondary axis. Except trans argument arguments can set derive() result secondary axis inheriting settings primary axis. dup_axis() provide shorthand creating secondary axis duplication primary axis, effectively mirroring primary axis. v3.1, date datetime scales limited secondary axis capabilities. Unlike continuous scales, secondary axis transformations date datetime scales must respect primary POSIX data structure. means may transformed via addition subtraction, e.g. ~ . + hms::hms(days = 8), ~ . - 8*60*60. Nonlinear transformations return error. produce time-since-event secondary axis context, users may consider adapting secondary axis labels.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sec_axis.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Specify a secondary axis — sec_axis","text":"","code":"p <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() # Create a simple secondary axis p + scale_y_continuous(sec.axis = sec_axis(~ . + 10)) # Inherit the name from the primary axis p + scale_y_continuous(\"Miles/gallon\", sec.axis = sec_axis(~ . + 10, name = derive())) # Duplicate the primary axis p + scale_y_continuous(sec.axis = dup_axis()) # You can pass in a formula as a shorthand p + scale_y_continuous(sec.axis = ~ .^2) # Secondary axes work for date and datetime scales too: df <- data.frame( dx = seq( as.POSIXct(\"2012-02-29 12:00:00\", tz = \"UTC\"), length.out = 10, by = \"4 hour\" ), price = seq(20, 200000, length.out = 10) ) # This may useful for labelling different time scales in the same plot ggplot(df, aes(x = dx, y = price)) + geom_line() + scale_x_datetime( \"Date\", date_labels = \"%b %d\", date_breaks = \"6 hour\", sec.axis = dup_axis( name = \"Time of Day\", labels = scales::label_time(\"%I %p\") ) ) # or to transform axes for different timezones ggplot(df, aes(x = dx, y = price)) + geom_line() + scale_x_datetime(\" GMT\", date_labels = \"%b %d %I %p\", sec.axis = sec_axis( ~ . + 8 * 3600, name = \"GMT+8\", labels = scales::label_time(\"%b %d %I %p\") ) )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/set_last_plot.html","id":null,"dir":"Reference","previous_headings":"","what":"Set the last plot to be fetched by lastplot() — set_last_plot","title":"Set the last plot to be fetched by lastplot() — set_last_plot","text":"Set last plot fetched lastplot()","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/set_last_plot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Set the last plot to be fetched by lastplot() — set_last_plot","text":"","code":"set_last_plot(value)"},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":null,"dir":"Reference","previous_headings":"","what":"Transform spatial position data — sf_transform_xy","title":"Transform spatial position data — sf_transform_xy","text":"Helper function can transform spatial position data (pairs x, y values) among coordinate systems. implemented thin wrapper around sf::sf_project().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Transform spatial position data — sf_transform_xy","text":"","code":"sf_transform_xy(data, target_crs, source_crs, authority_compliant = FALSE)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Transform spatial position data — sf_transform_xy","text":"data Data frame list containing numerical columns x y. target_crs, source_crs Target source coordinate reference systems. NULL NA, data transformed. authority_compliant logical; TRUE means handle axis order authority compliant (e.g. EPSG:4326 implying x = lat, y = lon), FALSE means use visualisation order (.e. always x = lon, y = lat). Default FALSE.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Transform spatial position data — sf_transform_xy","text":"copy input data x y replaced transformed values.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/sf_transform_xy.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Transform spatial position data — sf_transform_xy","text":"","code":"if (requireNamespace(\"sf\", quietly = TRUE)) { # location of cities in NC by long (x) and lat (y) data <- data.frame( city = c(\"Charlotte\", \"Raleigh\", \"Greensboro\"), x = c(-80.843, -78.639, -79.792), y = c(35.227, 35.772, 36.073) ) # transform to projected coordinates data_proj <- sf_transform_xy(data, 3347, 4326) data_proj # transform back sf_transform_xy(data_proj, 4326, 3347) } #> city x y #> 1 Charlotte -80.843 35.227 #> 2 Raleigh -78.639 35.772 #> 3 Greensboro -79.792 36.073"},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":null,"dir":"Reference","previous_headings":"","what":"Used in examples to illustrate when errors should occur. — should_stop","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"Used examples illustrate errors occur.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"","code":"should_stop(expr)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"expr code evaluate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/should_stop.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Used in examples to illustrate when errors should occur. — should_stop","text":"","code":"should_stop(stop(\"Hi!\")) should_stop(should_stop(\"Hi!\")) #> [1] \"Hi!\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":null,"dir":"Reference","previous_headings":"","what":"Standardise aesthetic names — standardise_aes_names","title":"Standardise aesthetic names — standardise_aes_names","text":"function standardises aesthetic names converting color colour (also substrings, e.g. point_color point_colour) translating old style R names ggplot names (eg. pch shape, cex size).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Standardise aesthetic names — standardise_aes_names","text":"","code":"standardise_aes_names(x)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Standardise aesthetic names — standardise_aes_names","text":"x Character vector aesthetics names, c(\"colour\", \"size\", \"shape\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/standardise_aes_names.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Standardise aesthetic names — standardise_aes_names","text":"Character vector standardised names.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute empirical cumulative distribution — stat_ecdf","title":"Compute empirical cumulative distribution — stat_ecdf","text":"empirical cumulative distribution function (ECDF) provides alternative visualisation distribution. Compared visualisations rely density (like geom_histogram()), ECDF require tuning parameters handles continuous categorical variables. downside requires training accurately interpret, underlying visual tasks somewhat challenging.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute empirical cumulative distribution — stat_ecdf","text":"","code":"stat_ecdf( mapping = NULL, data = NULL, geom = \"step\", position = \"identity\", ..., n = NULL, pad = TRUE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute empirical cumulative distribution — stat_ecdf","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. n NULL, interpolate. NULL, number points interpolate . pad TRUE, pad ecdf additional points (-Inf, 0) (Inf, 1) na.rm FALSE (default), removes missing values warning. TRUE silently removes missing values. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Compute empirical cumulative distribution — stat_ecdf","text":"statistic relies aesthetics assignment guess variable use input use output. Either x y must provided one must unused. ECDF calculated given aesthetic output unused one. weight aesthetic provided, weighted ECDF computed. case, ECDF incremented weight / sum(weight) instead 1 / length(x) observation.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Compute empirical cumulative distribution — stat_ecdf","text":"stat_ecdf() understands following aesthetics (required aesthetics bold): x y group weight Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Compute empirical cumulative distribution — stat_ecdf","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(ecdf) Cumulative density corresponding x. after_stat(y) backward compatibility.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Compute empirical cumulative distribution — stat_ecdf","text":"weight calculation, weights individual observations (supplied), longer available.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ecdf.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute empirical cumulative distribution — stat_ecdf","text":"","code":"set.seed(1) df <- data.frame( x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)), g = gl(2, 100) ) ggplot(df, aes(x)) + stat_ecdf(geom = \"step\") # Don't go to positive/negative infinity ggplot(df, aes(x)) + stat_ecdf(geom = \"step\", pad = FALSE) # Multiple ECDFs ggplot(df, aes(x, colour = g)) + stat_ecdf() # Using weighted eCDF weighted <- data.frame(x = 1:10, weights = c(1:5, 5:1)) plain <- data.frame(x = rep(weighted$x, weighted$weights)) ggplot(plain, aes(x)) + stat_ecdf(linewidth = 1) + stat_ecdf( aes(weight = weights), data = weighted, colour = \"green\" )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":null,"dir":"Reference","previous_headings":"","what":"Compute normal data ellipses — stat_ellipse","title":"Compute normal data ellipses — stat_ellipse","text":"method calculating ellipses modified car::dataEllipse (Fox Weisberg 2011, Friendly Monette 2013)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Compute normal data ellipses — stat_ellipse","text":"","code":"stat_ellipse( mapping = NULL, data = NULL, geom = \"path\", position = \"identity\", ..., type = \"t\", level = 0.95, segments = 51, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Compute normal data ellipses — stat_ellipse","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. type type ellipse. default \"t\" assumes multivariate t-distribution, \"norm\" assumes multivariate normal distribution. \"euclid\" draws circle radius equal level, representing euclidean distance center. ellipse probably appear circular unless coord_fixed() applied. level level draw ellipse, , type=\"euclid\", radius circle drawn. segments number segments used drawing ellipse. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"references","dir":"Reference","previous_headings":"","what":"References","title":"Compute normal data ellipses — stat_ellipse","text":"John Fox Sanford Weisberg (2011). R Companion Applied Regression, Second Edition. Thousand Oaks CA: Sage. URL: https://socialsciences.mcmaster.ca/jfox/Books/Companion/ Michael Friendly. Georges Monette. John Fox. \"Elliptical Insights: Understanding Statistical Methods Elliptical Geometry.\" Statist. Sci. 28 (1) 1 - 39, February 2013. URL: https://projecteuclid.org/journals/statistical-science/volume-28/issue-1/Elliptical-Insights-Understanding-Statistical-Methods--Elliptical-Geometry/10.1214/12-STS402.full","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_ellipse.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Compute normal data ellipses — stat_ellipse","text":"","code":"ggplot(faithful, aes(waiting, eruptions)) + geom_point() + stat_ellipse() ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse() ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse(type = \"norm\", linetype = 2) + stat_ellipse(type = \"t\") ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse(type = \"norm\", linetype = 2) + stat_ellipse(type = \"euclid\", level = 3) + coord_fixed() ggplot(faithful, aes(waiting, eruptions, fill = eruptions > 3)) + stat_ellipse(geom = \"polygon\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":null,"dir":"Reference","previous_headings":"","what":"Leave data as is — stat_identity","title":"Leave data as is — stat_identity","text":"identity statistic leaves data unchanged.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Leave data as is — stat_identity","text":"","code":"stat_identity( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Leave data as is — stat_identity","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_identity.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Leave data as is — stat_identity","text":"","code":"p <- ggplot(mtcars, aes(wt, mpg)) p + stat_identity()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":null,"dir":"Reference","previous_headings":"","what":"Extract coordinates from 'sf' objects — stat_sf_coordinates","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"stat_sf_coordinates() extracts coordinates 'sf' objects summarises one pair coordinates (x y) per geometry. convenient draw sf object geoms like text labels (geom_sf_text() geom_sf_label() relies ).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"","code":"stat_sf_coordinates( mapping = aes(), data = NULL, geom = \"point\", position = \"identity\", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, fun.geometry = NULL, ... )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). fun.geometry function takes sfc object returns sfc_POINT length input. NULL, function(x) sf::st_point_on_surface(sf::st_zm(x)) used. Note function may warn incorrectness result data projected, can ignore except really care exact locations. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"coordinates sf object can retrieved sf::st_coordinates(). , simply use sf::st_coordinates() , whereas text labels require exactly one coordinate per geometry, returns multiple ones polygon line. Thus, two steps needed: Choose one point per geometry function like sf::st_centroid() sf::st_point_on_surface(). Retrieve coordinates points sf::st_coordinates(). first step, can use arbitrary function via fun.geometry. default, function(x) sf::st_point_on_surface(sf::st_zm(x)) used; sf::st_point_on_surface() seems appropriate sf::st_centroid() since labels text usually intended put within polygon line. sf::st_zm() needed drop Z M dimension beforehand, otherwise sf::st_point_on_surface() may fail geometries M dimension.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x) X dimension simple feature. after_stat(y) Y dimension simple feature.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_sf_coordinates.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Extract coordinates from 'sf' objects — stat_sf_coordinates","text":"","code":"if (requireNamespace(\"sf\", quietly = TRUE)) { nc <- sf::st_read(system.file(\"shape/nc.shp\", package=\"sf\")) ggplot(nc) + stat_sf_coordinates() ggplot(nc) + geom_errorbarh( aes(geometry = geometry, xmin = after_stat(x) - 0.1, xmax = after_stat(x) + 0.1, y = after_stat(y), height = 0.04), stat = \"sf_coordinates\" ) } #> Reading layer `nc' from data source #> `/home/runner/work/_temp/Library/sf/shape/nc.shp' using driver `ESRI Shapefile' #> Simple feature collection with 100 features and 14 fields #> Geometry type: MULTIPOLYGON #> Dimension: XY #> Bounding box: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965 #> Geodetic CRS: NAD27 #> Warning: st_point_on_surface may not give correct results for longitude/latitude data"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":null,"dir":"Reference","previous_headings":"","what":"Summarise y values at unique/binned x — stat_summary_bin","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"stat_summary() operates unique x y; stat_summary_bin() operates binned x y. flexible versions stat_bin(): instead just counting, can compute aggregate.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"","code":"stat_summary_bin( mapping = NULL, data = NULL, geom = \"pointrange\", position = \"identity\", ..., fun.data = NULL, fun = NULL, fun.max = NULL, fun.min = NULL, fun.args = list(), bins = 30, binwidth = NULL, breaks = NULL, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, fun.y = deprecated(), fun.ymin = deprecated(), fun.ymax = deprecated() ) stat_summary( mapping = NULL, data = NULL, geom = \"pointrange\", position = \"identity\", ..., fun.data = NULL, fun = NULL, fun.max = NULL, fun.min = NULL, fun.args = list(), na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE, fun.y = deprecated(), fun.ymin = deprecated(), fun.ymax = deprecated() )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. fun.data function given complete data return data frame variables ymin, y, ymax. fun.min, fun, fun.max Alternatively, supply three individual functions passed vector values return single number. fun.args Optional additional arguments passed functions. bins Number bins. Overridden binwidth. Defaults 30. binwidth width bins. Can specified numeric value function takes x scale transformation input returns single numeric value. specifying function along grouping structure, function called per group. default use number bins bins, covering range data. always override value, exploring multiple widths find best illustrate stories data. bin width date variable number days time; bin width time variable number seconds. breaks Alternatively, can supply numeric vector giving bin boundaries. Overrides binwidth bins. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. orientation orientation layer. default (NA) automatically determines orientation aesthetic mapping. rare event fails can given explicitly setting orientation either \"x\" \"y\". See Orientation section detail. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders(). fun.ymin, fun.y, fun.ymax Use versions specified instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"orientation","dir":"Reference","previous_headings":"","what":"Orientation","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"geom treats axis differently , thus, can thus two orientations. Often orientation easy deduce combination given mappings types positional scales use. Thus, ggplot2 default try guess orientation layer . rare circumstances, orientation ambiguous guessing may fail. case orientation can specified directly using orientation parameter, can either \"x\" \"y\". value gives axis geom run along, \"x\" default orientation expect geom.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"stat_summary() understands following aesthetics (required aesthetics bold): x y group Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"summary-functions","dir":"Reference","previous_headings":"","what":"Summary functions","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"can either supply summary functions individually (fun, fun.max, fun.min), single function (fun.data): fun.data Complete summary function. take numeric vector input return data frame output fun.min min summary function (take numeric vector return single number) fun main summary function (take numeric vector return single number) fun.max max summary function (take numeric vector return single number) simple vector function easiest work can return single number, somewhat less flexible. summary function computes multiple values (e.g. min max), use fun.data. fun.data receive data oriented along x-axis return data.frame corresponds orientation. layer take care flipping input output oriented along y-axis. aggregation functions supplied, default mean_se().","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Summarise y values at unique/binned x — stat_summary_bin","text":"","code":"d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() d + stat_summary(fun.data = \"mean_cl_boot\", colour = \"red\", linewidth = 2, size = 3) # Orientation follows the discrete axis ggplot(mtcars, aes(mpg, factor(cyl))) + geom_point() + stat_summary(fun.data = \"mean_cl_boot\", colour = \"red\", linewidth = 2, size = 3) # You can supply individual functions to summarise the value at # each x: d + stat_summary(fun = \"median\", colour = \"red\", size = 2, geom = \"point\") d + stat_summary(fun = \"mean\", colour = \"red\", size = 2, geom = \"point\") d + aes(colour = factor(vs)) + stat_summary(fun = mean, geom=\"line\") d + stat_summary(fun = mean, fun.min = min, fun.max = max, colour = \"red\") d <- ggplot(diamonds, aes(cut)) d + geom_bar() d + stat_summary(aes(y = price), fun = \"mean\", geom = \"bar\") # Orientation of stat_summary_bin is ambiguous and must be specified directly ggplot(diamonds, aes(carat, price)) + stat_summary_bin(fun = \"mean\", geom = \"bar\", orientation = 'y') # \\donttest{ # Don't use ylim to zoom into a summary plot - this throws the # data away p <- ggplot(mtcars, aes(cyl, mpg)) + stat_summary(fun = \"mean\", geom = \"point\") p p + ylim(15, 30) #> Warning: Removed 9 rows containing non-finite outside the scale range #> (`stat_summary()`). # Instead use coord_cartesian p + coord_cartesian(ylim = c(15, 30)) # A set of useful summary functions is provided from the Hmisc package: stat_sum_df <- function(fun, geom=\"crossbar\", ...) { stat_summary(fun.data = fun, colour = \"red\", geom = geom, width = 0.2, ...) } d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() # The crossbar geom needs grouping to be specified when used with # a continuous x axis. d + stat_sum_df(\"mean_cl_boot\", mapping = aes(group = cyl)) d + stat_sum_df(\"mean_sdl\", mapping = aes(group = cyl)) d + stat_sum_df(\"mean_sdl\", fun.args = list(mult = 1), mapping = aes(group = cyl)) d + stat_sum_df(\"median_hilow\", mapping = aes(group = cyl)) # An example with highly skewed distributions: if (require(\"ggplot2movies\")) { set.seed(596) mov <- movies[sample(nrow(movies), 1000), ] m2 <- ggplot(mov, aes(x = factor(round(rating)), y = votes)) + geom_point() m2 <- m2 + stat_summary( fun.data = \"mean_cl_boot\", geom = \"crossbar\", colour = \"red\", width = 0.3 ) + xlab(\"rating\") m2 # Notice how the overplotting skews off visual perception of the mean # supplementing the raw data with summary statistics is _very_ important # Next, we'll look at votes on a log scale. # Transforming the scale means the data are transformed # first, after which statistics are computed: m2 + scale_y_log10() # Transforming the coordinate system occurs after the # statistic has been computed. This means we're calculating the summary on the raw data # and stretching the geoms onto the log scale. Compare the widths of the # standard errors. m2 + coord_trans(y=\"log10\") } # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":null,"dir":"Reference","previous_headings":"","what":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"stat_summary_2d() 2d variation stat_summary(). stat_summary_hex() hexagonal variation stat_summary_2d(). data divided bins defined x y, values z cell summarised fun.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"","code":"stat_summary_2d( mapping = NULL, data = NULL, geom = \"tile\", position = \"identity\", ..., bins = 30, binwidth = NULL, drop = TRUE, fun = \"mean\", fun.args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) stat_summary_hex( mapping = NULL, data = NULL, geom = \"hex\", position = \"identity\", ..., bins = 30, binwidth = NULL, drop = TRUE, fun = \"mean\", fun.args = list(), na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. bins numeric vector giving number bins vertical horizontal directions. Set 30 default. binwidth Numeric vector giving bin width vertical horizontal directions. Overrides bins set. drop drop output fun NA. fun function summary. fun.args list extra arguments pass fun na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"x: horizontal position y: vertical position z: value passed summary function","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"computed-variables","dir":"Reference","previous_headings":"","what":"Computed variables","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"calculated 'stat' part layers can accessed delayed evaluation. after_stat(x), after_stat(y) Location. after_stat(value) Value summary statistic.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"dropped-variables","dir":"Reference","previous_headings":"","what":"Dropped variables","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"z binning, z values individual data points longer available.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_summary_2d.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Bin and summarise in 2d (rectangle & hexagons) — stat_summary_2d","text":"","code":"d <- ggplot(diamonds, aes(carat, depth, z = price)) d + stat_summary_2d() # Specifying function d + stat_summary_2d(fun = function(x) sum(x^2)) d + stat_summary_2d(fun = ~ sum(.x^2)) d + stat_summary_2d(fun = var) d + stat_summary_2d(fun = \"quantile\", fun.args = list(probs = 0.1)) if (requireNamespace(\"hexbin\")) { d + stat_summary_hex() d + stat_summary_hex(fun = ~ sum(.x^2)) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":null,"dir":"Reference","previous_headings":"","what":"Remove duplicates — stat_unique","title":"Remove duplicates — stat_unique","text":"Remove duplicates","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Remove duplicates — stat_unique","text":"","code":"stat_unique( mapping = NULL, data = NULL, geom = \"point\", position = \"identity\", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Remove duplicates — stat_unique","text":"mapping Set aesthetic mappings created aes(). specified inherit.aes = TRUE (default), combined default mapping top level plot. must supply mapping plot mapping. data data displayed layer. three options: NULL, default, data inherited plot data specified call ggplot(). data.frame, object, override plot data. objects fortified produce data frame. See fortify() variables created. function called single argument, plot data. return value must data.frame, used layer data. function can created formula (e.g. ~ head(.x, 10)). geom geometric object use display data layer. using stat_*() function construct layer, geom argument can used override default coupling stats geoms. geom argument accepts following: Geom ggproto subclass, example GeomPoint. string naming geom. give geom string, strip function name geom_ prefix. example, use geom_point(), give geom \"point\". information ways specify geom, see layer geom documentation. position position adjustment use data layer. can used various ways, including prevent overplotting improving display. position argument accepts following: result calling position function, position_jitter(). method allows passing extra arguments position. string naming position adjustment. give position string, strip function name position_ prefix. example, use position_jitter(), give position \"jitter\". information ways specify position, see layer position documentation. ... arguments passed layer()'s params argument. arguments broadly fall one 4 categories . Notably, arguments position argument, aesthetics required can passed .... Unknown arguments part 4 categories ignored. Static aesthetics mapped scale, fixed value apply layer whole. example, colour = \"red\" linewidth = 3. geom's documentation Aesthetics section lists available options. 'required' aesthetics passed params. Please note passing unmapped aesthetics vectors technically possible, order required length guaranteed parallel input data. constructing layer using stat_*() function, ... argument can used pass parameters geom part layer. example stat_density(geom = \"area\", outline.type = \"\"). geom's documentation lists parameters can accept. Inversely, constructing layer using geom_*() function, ... argument can used pass parameters stat part layer. example geom_area(stat = \"density\", adjust = 0.5). stat's documentation lists parameters can accept. key_glyph argument layer() may also passed .... can one functions described key glyphs, change display layer legend. na.rm FALSE, default, missing values removed warning. TRUE, missing values silently removed. show.legend logical. layer included legends? NA, default, includes aesthetics mapped. FALSE never includes, TRUE always includes. can also named logical vector finely select aesthetics display. include legend keys levels, even data exists, use TRUE. NA, levels shown legend, unobserved levels omitted. inherit.aes FALSE, overrides default aesthetics, rather combining . useful helper functions define data aesthetics inherit behaviour default plot specification, e.g. borders().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"aesthetics","dir":"Reference","previous_headings":"","what":"Aesthetics","title":"Remove duplicates — stat_unique","text":"stat_unique() understands following aesthetics (required aesthetics bold): group Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/stat_unique.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Remove duplicates — stat_unique","text":"","code":"ggplot(mtcars, aes(vs, am)) + geom_point(alpha = 0.1) ggplot(mtcars, aes(vs, am)) + geom_point(alpha = 0.1, stat = \"unique\")"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":null,"dir":"Reference","previous_headings":"","what":"Summarise built plot objects — summarise_plot","title":"Summarise built plot objects — summarise_plot","text":"functions provide summarised information built ggplot objects.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Summarise built plot objects — summarise_plot","text":"","code":"summarise_layout(p) summarise_coord(p) summarise_layers(p)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Summarise built plot objects — summarise_plot","text":"p ggplot_built object.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"details","dir":"Reference","previous_headings":"","what":"Details","title":"Summarise built plot objects — summarise_plot","text":"three types summary can obtained: summary plot layout, summary plot coord, summary plot layers.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"layout-summary","dir":"Reference","previous_headings":"","what":"Layout summary","title":"Summarise built plot objects — summarise_plot","text":"function summarise_layout() returns table provides information plot panel(s) built plot. table following columns: panel factor indicating individual plot panels. row Row number grid panels. col Column number grid panels. vars list lists. panel, respective list provides variables values specify panel. xmin, xmax minimum maximum values variable mapped x aesthetic, transformed coordinates. ymin, ymax minimum maximum values variable mapped y aesthetic, transformed coordinates. xscale scale object applied x aesthetic. yscale scale object applied y aesthetic. Importantly, values xmin, xmax, ymin, ymax, xscale, yscale determined variables mapped x y aes() call. even coord changes x y shown final plot (case coord_flip() coord_polar()), changes effect results returned summarise_plot().","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"coord-summary","dir":"Reference","previous_headings":"","what":"Coord summary","title":"Summarise built plot objects — summarise_plot","text":"function summarise_coord() returns information log base coordinates log-transformed coord_trans(), also indicates whether coord flipped x y axes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"layer-summary","dir":"Reference","previous_headings":"","what":"Layer summary","title":"Summarise built plot objects — summarise_plot","text":"function summarise_layers() returns table single column, mapping, contains information aesthetic mapping layer.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summarise_plot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Summarise built plot objects — summarise_plot","text":"","code":"p <- ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(~class) b <- ggplot_build(p) summarise_layout(b) #> panel row col vars xmin xmax ymin ymax #> 1 1 1 1 2seater 1.33 7.27 10.4 45.6 #> 2 2 1 2 compact 1.33 7.27 10.4 45.6 #> 3 3 1 3 midsize 1.33 7.27 10.4 45.6 #> 4 4 2 1 minivan 1.33 7.27 10.4 45.6 #> 5 5 2 2 pickup 1.33 7.27 10.4 45.6 #> 6 6 2 3 subcompact 1.33 7.27 10.4 45.6 #> 7 7 3 1 suv 1.33 7.27 10.4 45.6 #> xscale yscale #> 1 #> 2 #> 3 #> 4 #> 5 #> 6 #> 7 summarise_coord(b) #> $xlog #> [1] NA #> #> $ylog #> [1] NA #> #> $flip #> [1] FALSE #> summarise_layers(b) #> mapping #> 1 ~displ, ~hwy"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":null,"dir":"Reference","previous_headings":"","what":"Displays a useful description of a ggplot object — summary.ggplot","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"Displays useful description ggplot object","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"","code":"# S3 method for class 'ggplot' summary(object, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"object ggplot2 object summarise ... arguments ignored (compatibility generic)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/summary.ggplot.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Displays a useful description of a ggplot object — summary.ggplot","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() summary(p) #> data: mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb #> [32x11] #> mapping: x = ~mpg, y = ~wt #> faceting: #> attach_axes: function #> attach_strips: function #> compute_layout: function #> draw_back: function #> draw_front: function #> draw_labels: function #> draw_panels: function #> finish_data: function #> format_strip_labels: function #> init_gtable: function #> init_scales: function #> map_data: function #> params: list #> setup_data: function #> setup_params: function #> shrink: TRUE #> train_scales: function #> vars: function #> super: #> ----------------------------------- #> geom_point: na.rm = FALSE #> stat_identity: na.rm = FALSE #> position_identity #>"},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify components of a theme — theme","title":"Modify components of a theme — theme","text":"Themes powerful way customize non-data components plots: .e. titles, labels, fonts, background, gridlines, legends. Themes can used give plots consistent customized look. Modify single plot's theme using theme(); see theme_update() want modify active theme, affect subsequent plots. Use themes available complete themes like use complete theme theme_bw(), theme_minimal(), . Theme elements documented together according inheritance, read theme inheritance .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify components of a theme — theme","text":"","code":"theme( ..., line, rect, text, title, geom, spacing, margins, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.x.bottom, axis.title.y, axis.title.y.left, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.x.bottom, axis.text.y, axis.text.y.left, axis.text.y.right, axis.text.theta, axis.text.r, axis.ticks, axis.ticks.x, axis.ticks.x.top, axis.ticks.x.bottom, axis.ticks.y, axis.ticks.y.left, axis.ticks.y.right, axis.ticks.theta, axis.ticks.r, axis.minor.ticks.x.top, axis.minor.ticks.x.bottom, axis.minor.ticks.y.left, axis.minor.ticks.y.right, axis.minor.ticks.theta, axis.minor.ticks.r, axis.ticks.length, axis.ticks.length.x, axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, axis.ticks.length.y.left, axis.ticks.length.y.right, axis.ticks.length.theta, axis.ticks.length.r, axis.minor.ticks.length, axis.minor.ticks.length.x, axis.minor.ticks.length.x.top, axis.minor.ticks.length.x.bottom, axis.minor.ticks.length.y, axis.minor.ticks.length.y.left, axis.minor.ticks.length.y.right, axis.minor.ticks.length.theta, axis.minor.ticks.length.r, axis.line, axis.line.x, axis.line.x.top, axis.line.x.bottom, axis.line.y, axis.line.y.left, axis.line.y.right, axis.line.theta, axis.line.r, legend.background, legend.margin, legend.spacing, legend.spacing.x, legend.spacing.y, legend.key, legend.key.size, legend.key.height, legend.key.width, legend.key.spacing, legend.key.spacing.x, legend.key.spacing.y, legend.frame, legend.ticks, legend.ticks.length, legend.axis.line, legend.text, legend.text.position, legend.title, legend.title.position, legend.position, legend.position.inside, legend.direction, legend.byrow, legend.justification, legend.justification.top, legend.justification.bottom, legend.justification.left, legend.justification.right, legend.justification.inside, legend.location, 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.title.position, plot.subtitle, plot.caption, plot.caption.position, plot.tag, plot.tag.position, plot.tag.location, plot.margin, strip.background, strip.background.x, strip.background.y, strip.clip, strip.placement, strip.text, strip.text.x, strip.text.x.bottom, strip.text.x.top, strip.text.y, strip.text.y.left, strip.text.y.right, strip.switch.pad.grid, strip.switch.pad.wrap, complete = FALSE, validate = TRUE )"},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify components of a theme — theme","text":"... additional element specifications part base ggplot2. general, also defined element tree argument. Splicing list also supported. line line elements (element_line()) rect rectangular elements (element_rect()) text text elements (element_text()) title title elements: plot, axes, legends (element_text(); inherits text) geom defaults geoms (element_geom()) spacing spacings (unit()) margins margins (margin()) aspect.ratio aspect ratio panel axis.title, axis.title.x, axis.title.y, axis.title.x.top, axis.title.x.bottom, axis.title.y.left, axis.title.y.right labels axes (element_text()). Specify axes' labels (axis.title), labels plane (using axis.title.x axis.title.y), individually axis (using axis.title.x.bottom, axis.title.x.top, axis.title.y.left, axis.title.y.right). axis.title.*.* inherits axis.title.* inherits axis.title, turn inherits text axis.text, axis.text.x, axis.text.y, axis.text.x.top, axis.text.x.bottom, axis.text.y.left, axis.text.y.right, axis.text.theta, axis.text.r tick labels along axes (element_text()). Specify axis tick labels (axis.text), tick labels plane (using axis.text.x axis.text.y), individually axis (using axis.text.x.bottom, axis.text.x.top, axis.text.y.left, axis.text.y.right). axis.text.*.* inherits axis.text.* inherits axis.text, turn inherits text axis.ticks, axis.ticks.x, axis.ticks.x.top, axis.ticks.x.bottom, axis.ticks.y, axis.ticks.y.left, axis.ticks.y.right, axis.ticks.theta, axis.ticks.r tick marks along axes (element_line()). Specify tick marks (axis.ticks), ticks plane (using axis.ticks.x axis.ticks.y), individually axis (using axis.ticks.x.bottom, axis.ticks.x.top, axis.ticks.y.left, axis.ticks.y.right). axis.ticks.*.* inherits axis.ticks.* inherits axis.ticks, turn inherits line axis.minor.ticks.x.top, axis.minor.ticks.x.bottom, axis.minor.ticks.y.left, axis.minor.ticks.y.right, axis.minor.ticks.theta, axis.minor.ticks.r, minor tick marks along axes (element_line()). axis.minor.ticks.*.* inherit corresponding major ticks axis.ticks.*.*. axis.ticks.length, axis.ticks.length.x, axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, axis.ticks.length.y.left, axis.ticks.length.y.right, axis.ticks.length.theta, axis.ticks.length.r length tick marks (unit). axis.ticks.length inherits spacing. axis.minor.ticks.length, axis.minor.ticks.length.x, axis.minor.ticks.length.x.top, axis.minor.ticks.length.x.bottom, axis.minor.ticks.length.y, axis.minor.ticks.length.y.left, axis.minor.ticks.length.y.right, axis.minor.ticks.length.theta, axis.minor.ticks.length.r length minor tick marks (unit), relative axis.ticks.length provided rel(). axis.line, axis.line.x, axis.line.x.top, axis.line.x.bottom, axis.line.y, axis.line.y.left, axis.line.y.right, axis.line.theta, axis.line.r lines along axes (element_line()). Specify lines along axes (axis.line), lines plane (using axis.line.x axis.line.y), individually axis (using axis.line.x.bottom, axis.line.x.top, axis.line.y.left, axis.line.y.right). axis.line.*.* inherits axis.line.* inherits axis.line, turn inherits line legend.background background legend (element_rect(); inherits rect) legend.margin margin around legend (margin()); inherits margins. legend.spacing, legend.spacing.x, legend.spacing.y spacing legends (unit). legend.spacing.x & legend.spacing.y inherit legend.spacing can specified separately. legend.spacing inherits spacing. legend.key background underneath legend keys (element_rect(); inherits rect) legend.key.size, legend.key.height, legend.key.width size legend keys (unit); key background height & width inherit legend.key.size can specified separately. turn legend.key.size inherits spacing. legend.key.spacing, legend.key.spacing.x, legend.key.spacing.y spacing legend keys given unit. Spacing horizontal (x) vertical (y) direction inherit legend.key.spacing can specified separately. legend.key.spacing inherits spacing. legend.frame frame drawn around bar (element_rect()). legend.ticks tick marks shown along bars axes (element_line()) legend.ticks.length length tick marks legend (unit()); inherits legend.key.size. legend.axis.line lines along axes legends (element_line()) legend.text legend item labels (element_text(); inherits text) legend.text.position placement legend text relative legend keys bars (\"top\", \"right\", \"bottom\" \"left\"). legend text placement might incompatible legend's direction guides. legend.title title legend (element_text(); inherits title) legend.title.position placement legend title relative main legend (\"top\", \"right\", \"bottom\" \"left\"). legend.position default position legends (\"none\", \"left\", \"right\", \"bottom\", \"top\", \"inside\") legend.position.inside numeric vector length two setting placement legends \"inside\" position. legend.direction layout items legends (\"horizontal\" \"vertical\") legend.byrow whether legend-matrix filled columns (FALSE, default) rows (TRUE). legend.justification anchor point positioning legend inside plot (\"center\" two-element numeric vector) justification according plot area positioned outside plot legend.justification.top, legend.justification.bottom, legend.justification.left, legend.justification.right, legend.justification.inside legend.justification specified per legend.position option. legend.location Relative placement legends outside plot string. Can \"panel\" (default) align legends panels \"plot\" align legends plot whole. legend.box arrangement multiple legends (\"horizontal\" \"vertical\") legend.box.just justification legend within overall bounding box, multiple legends (\"top\", \"bottom\", \"left\", \"right\", \"center\" \"centre\") legend.box.margin margins around full legend area, specified using margin(); inherits margins. legend.box.background background legend area (element_rect(); inherits rect) legend.box.spacing spacing plotting area legend box (unit); inherits spacing. panel.background background plotting area, drawn underneath plot (element_rect(); inherits rect) panel.border border around plotting area, drawn top plot covers tick marks grid lines. used fill = NA (element_rect(); inherits rect) panel.spacing, panel.spacing.x, panel.spacing.y spacing facet panels (unit). panel.spacing.x & panel.spacing.y inherit panel.spacing can specified separately. panel.spacing inherits spacing. panel.grid, panel.grid.major, panel.grid.minor, panel.grid.major.x, panel.grid.major.y, panel.grid.minor.x, panel.grid.minor.y grid lines (element_line()). Specify major grid lines, minor grid lines separately (using panel.grid.major panel.grid.minor) individually axis (using panel.grid.major.x, panel.grid.minor.x, panel.grid.major.y, panel.grid.minor.y). Y axis grid lines horizontal x axis grid lines vertical. panel.grid.*.* inherits panel.grid.* inherits panel.grid, turn inherits line panel.ontop option place panel (background, gridlines) data layers (logical). Usually used transparent blank panel.background. plot.background background entire plot (element_rect(); inherits rect) plot.title plot title (text appearance) (element_text(); inherits title) left-aligned default plot.title.position, plot.caption.position Alignment plot title/subtitle caption. setting plot.title.position applies title subtitle. value \"panel\" (default) means titles /caption aligned plot panels. value \"plot\" means titles /caption aligned entire plot (minus space margins plot tag). plot.subtitle plot subtitle (text appearance) (element_text(); inherits title) left-aligned default plot.caption caption plot (text appearance) (element_text(); inherits title) right-aligned default plot.tag upper-left label identify plot (text appearance) (element_text(); inherits title) left-aligned default plot.tag.position position tag string (\"topleft\", \"top\", \"topright\", \"left\", \"right\", \"bottomleft\", \"bottom\", \"bottomright\") coordinate. coordinate, can numeric vector length 2 set x,y-coordinate relative whole plot. coordinate option unavailable plot.tag.location = \"margin\". plot.tag.location placement tag string, one \"panel\", \"plot\" \"margin\". Respectively, place tag inside panel space, anywhere plot whole, margin around panel space. plot.margin margin around entire plot (unit sizes top, right, bottom, left margins); inherits margin. strip.background, strip.background.x, strip.background.y background facet labels (element_rect(); inherits rect). Horizontal facet background (strip.background.x) & vertical facet background (strip.background.y) inherit strip.background can specified separately strip.clip strip background edges strip labels clipped extend strip background? Options \"\" clip, \"\" disable clipping \"inherit\" (default) take clipping setting parent viewport. strip.placement placement strip respect axes, either \"inside\" \"outside\". important axes strips side plot. strip.text, strip.text.x, strip.text.y, strip.text.x.top, strip.text.x.bottom, strip.text.y.left, strip.text.y.right facet labels (element_text(); inherits text). Horizontal facet labels (strip.text.x) & vertical facet labels (strip.text.y) inherit strip.text can specified separately. Facet strips dedicated position-dependent theme elements (strip.text.x.top, strip.text.x.bottom, strip.text.y.left, strip.text.y.right) inherit strip.text.x strip.text.y, respectively. consequence, theme stylings need applied position-dependent elements rather parent elements strip.switch.pad.grid, strip.switch.pad.wrap space strips axes strips switched (unit); inherits spacing. complete set TRUE complete theme, one returned theme_grey(). Complete themes behave differently added ggplot object. Also, setting complete = TRUE elements set inherit blank elements. validate TRUE run validate_element(), FALSE bypass checks.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"theme-inheritance","dir":"Reference","previous_headings":"","what":"Theme inheritance","title":"Modify components of a theme — theme","text":"Theme elements inherit properties theme elements hierarchically. example, axis.title.x.bottom inherits axis.title.x inherits axis.title, turn inherits text. text elements inherit directly indirectly text; lines inherit line, rectangular objects inherit rect. means can modify appearance multiple elements setting single high-level component. Learn setting aesthetics vignette(\"ggplot2-specs\").","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/theme.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify components of a theme — theme","text":"","code":"p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + labs(title = \"Fuel economy declines as weight increases\") p1 # Plot --------------------------------------------------------------------- p1 + theme(plot.title = element_text(size = rel(2))) p1 + theme(plot.background = element_rect(fill = \"green\")) # Panels -------------------------------------------------------------------- p1 + theme(panel.background = element_rect(fill = \"white\", colour = \"grey50\")) p1 + theme(panel.border = element_rect(linetype = \"dashed\")) p1 + theme(panel.grid.major = element_line(colour = \"black\")) p1 + theme( panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank() ) # Put gridlines on top of data p1 + theme( panel.background = element_rect(fill = NA), panel.grid.major = element_line(colour = \"grey50\"), panel.ontop = TRUE ) # Axes ---------------------------------------------------------------------- # Change styles of axes texts and lines p1 + theme(axis.line = element_line(linewidth = 3, colour = \"grey80\")) p1 + theme(axis.text = element_text(colour = \"blue\")) p1 + theme(axis.ticks = element_line(linewidth = 2)) # Change the appearance of the y-axis title p1 + theme(axis.title.y = element_text(size = rel(1.5), angle = 90)) # Make ticks point outwards on y-axis and inwards on x-axis p1 + theme( axis.ticks.length.y = unit(.25, \"cm\"), axis.ticks.length.x = unit(-.25, \"cm\"), axis.text.x = element_text(margin = margin(t = .3, unit = \"cm\")) ) # \\donttest{ # Legend -------------------------------------------------------------------- p2 <- ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(colour = factor(cyl), shape = factor(vs))) + labs( x = \"Weight (1000 lbs)\", y = \"Fuel economy (mpg)\", colour = \"Cylinders\", shape = \"Transmission\" ) p2 # Position p2 + theme(legend.position = \"none\") p2 + theme(legend.justification = \"top\") p2 + theme(legend.position = \"bottom\") # Or place legends inside the plot using relative coordinates between 0 and 1 # legend.justification sets the corner that the position refers to p2 + theme( legend.position = \"inside\", legend.position.inside = c(.95, .95), legend.justification = c(\"right\", \"top\"), legend.box.just = \"right\", legend.margin = margin(6, 6, 6, 6) ) # The legend.box properties work similarly for the space around # all the legends p2 + theme( legend.box.background = element_rect(), legend.box.margin = margin(6, 6, 6, 6) ) # You can also control the display of the keys # and the justification related to the plot area can be set p2 + theme(legend.key = element_rect(fill = \"white\", colour = \"black\")) p2 + theme(legend.text = element_text(size = 8, colour = \"red\")) p2 + theme(legend.title = element_text(face = \"bold\")) # Strips -------------------------------------------------------------------- p3 <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl) p3 p3 + theme(strip.background = element_rect(colour = \"black\", fill = \"white\")) p3 + theme(strip.text.x = element_text(colour = \"white\", face = \"bold\")) # More direct strip.text.x here for top # as in the facet_wrap the default strip.position is \"top\" p3 + theme(strip.text.x.top = element_text(colour = \"white\", face = \"bold\")) p3 + theme(panel.spacing = unit(1, \"lines\")) # }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/tidyeval.html","id":null,"dir":"Reference","previous_headings":"","what":"Tidy eval helpers — tidyeval","title":"Tidy eval helpers — tidyeval","text":"page lists tidy eval tools reexported package rlang. learn using tidy eval scripts packages high level, see dplyr programming vignette ggplot2 packages vignette. Metaprogramming section Advanced R may also useful deeper dive. tidy eval operators {{, !!, !!! syntactic constructs specially interpreted tidy eval functions. mostly need {{, !! !!! advanced operators use simple cases. curly-curly operator {{ allows tunnel data-variables passed function arguments inside tidy eval functions. {{ designed individual arguments. pass multiple arguments contained dots, use ... normal way. enquo() enquos() delay execution one several function arguments. former returns single expression, latter returns list expressions. defused, expressions longer evaluate . must injected back evaluation context !! (single expression) !!! (list expressions). simple case, code equivalent usage {{ ... . Defusing enquo() enquos() needed complex cases, instance need inspect modify expressions way. .data pronoun object represents current slice data. variable name string, use .data pronoun subset variable [[. Another tidy eval operator :=. makes possible use glue curly-curly syntax LHS =. technical reasons, R language support complex expressions left =, use := workaround. Many tidy eval functions like dplyr::mutate() dplyr::summarise() give automatic name unnamed inputs. need create sort automatic names , use as_label(). instance, glue-tunnelling syntax can reproduced manually : Expressions defused enquo() (tunnelled {{) need simple column names, can arbitrarily complex. as_label() handles cases gracefully. code assumes simple column name, use as_name() instead. safer throws error input name expected.","code":"my_function <- function(data, var, ...) { data %>% group_by(...) %>% summarise(mean = mean({{ var }})) } my_function <- function(data, var, ...) { # Defuse var <- enquo(var) dots <- enquos(...) # Inject data %>% group_by(!!!dots) %>% summarise(mean = mean(!!var)) } my_var <- \"disp\" mtcars %>% summarise(mean = mean(.data[[my_var]])) my_function <- function(data, var, suffix = \"foo\") { # Use `{{` to tunnel function arguments and the usual glue # operator `{` to interpolate plain strings. data %>% summarise(\"{{ var }}_mean_{suffix}\" := mean({{ var }})) } my_function <- function(data, var, suffix = \"foo\") { var <- enquo(var) prefix <- as_label(var) data %>% summarise(\"{prefix}_mean_{suffix}\" := mean(!!var)) }"},{"path":"https://ggplot2.tidyverse.org/dev/reference/transform_position.html","id":null,"dir":"Reference","previous_headings":"","what":"Convenience function to transform all position variables. — transform_position","title":"Convenience function to transform all position variables. — transform_position","text":"Convenience function transform position variables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/transform_position.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Convenience function to transform all position variables. — transform_position","text":"","code":"transform_position(df, trans_x = NULL, trans_y = NULL, ...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/transform_position.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Convenience function to transform all position variables. — transform_position","text":"trans_x, trans_y Transformation functions x y aesthetics. (transform x, xmin, xmax, xend etc) ... Additional arguments passed trans_x trans_y.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":null,"dir":"Reference","previous_headings":"","what":"Translating shape strings — translate_shape_string","title":"Translating shape strings — translate_shape_string","text":"translate_shape_string() helper function translating point shapes given character vector integers interpreted grid system.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Translating shape strings — translate_shape_string","text":"","code":"translate_shape_string(shape_string)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Translating shape strings — translate_shape_string","text":"shape_string character vector giving point shapes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Translating shape strings — translate_shape_string","text":"integer vector translated shapes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/translate_shape_string.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Translating shape strings — translate_shape_string","text":"","code":"translate_shape_string(c(\"circle\", \"square\", \"triangle\")) #> [1] 19 15 17 # Strings with 1 or less characters are interpreted as symbols translate_shape_string(c(\"a\", \"b\", \"?\")) #> [1] \"a\" \"b\" \"?\""},{"path":"https://ggplot2.tidyverse.org/dev/reference/txhousing.html","id":null,"dir":"Reference","previous_headings":"","what":"Housing sales in TX — txhousing","title":"Housing sales in TX — txhousing","text":"Information housing market Texas provided TAMU real estate center, https://trerc.tamu.edu/.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/txhousing.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Housing sales in TX — txhousing","text":"","code":"txhousing"},{"path":"https://ggplot2.tidyverse.org/dev/reference/txhousing.html","id":"format","dir":"Reference","previous_headings":"","what":"Format","title":"Housing sales in TX — txhousing","text":"data frame 8602 observations 9 variables: city Name multiple listing service (MLS) area year,month,date Date sales Number sales volume Total value sales median Median sale price listings Total active listings inventory \"Months inventory\": amount time take sell current listings current pace sales.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":null,"dir":"Reference","previous_headings":"","what":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"Functions update reset default aesthetics geoms stats.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"","code":"update_geom_defaults(geom, new) update_stat_defaults(stat, new) reset_geom_defaults() reset_stat_defaults()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"new One following: named list aesthetics serve new defaults. NULL reset defaults. stat, geom Name geom/stat modify (like \"point\" \"bin\"), Geom/Stat object (like GeomPoint StatBin).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"note","dir":"Reference","previous_headings":"","what":"Note","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"Please note geom defaults can set en masse via theme(geom) argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_defaults.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Modify geom/stat aesthetic defaults for future plots — update_geom_defaults","text":"","code":"# updating a geom's default aesthetic settings # example: change geom_point()'s default color GeomPoint$default_aes #> Aesthetic mapping: #> * `shape` -> `from_theme(pointshape)` #> * `colour` -> `from_theme(ink)` #> * `size` -> `from_theme(pointsize)` #> * `fill` -> NA #> * `alpha` -> NA #> * `stroke` -> `from_theme(borderwidth)` update_geom_defaults(\"point\", aes(color = \"red\")) GeomPoint$default_aes #> Aesthetic mapping: #> * `shape` -> `from_theme(pointshape)` #> * `colour` -> \"red\" #> * `size` -> `from_theme(pointsize)` #> * `fill` -> NA #> * `alpha` -> NA #> * `stroke` -> `from_theme(borderwidth)` ggplot(mtcars, aes(mpg, wt)) + geom_point() # reset single default update_geom_defaults(\"point\", NULL) # reset all defaults reset_geom_defaults() # updating a stat's default aesthetic settings # example: change stat_bin()'s default y-axis to the density scale StatBin$default_aes #> Aesthetic mapping: #> * `x` -> `after_stat(count)` #> * `y` -> `after_stat(count)` #> * `weight` -> 1 update_stat_defaults(\"bin\", aes(y = after_stat(density))) StatBin$default_aes #> Aesthetic mapping: #> * `x` -> `after_stat(count)` #> * `y` -> `after_stat(density)` #> * `weight` -> 1 ggplot(data.frame(x = rnorm(1e3)), aes(x)) + geom_histogram() + geom_function(fun = dnorm, color = \"red\") #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. # reset single default update_stat_defaults(\"bin\", NULL) # reset all defaults reset_stat_defaults()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":null,"dir":"Reference","previous_headings":"","what":"Update axis/legend labels — update_labels","title":"Update axis/legend labels — update_labels","text":"Update axis/legend labels","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Update axis/legend labels — update_labels","text":"","code":"update_labels(p, labels)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Update axis/legend labels — update_labels","text":"p plot modify labels named list new labels","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/update_labels.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Update axis/legend labels — update_labels","text":"","code":"p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() update_labels(p, list(x = \"New x\")) update_labels(p, list(x = expression(x / y ^ 2))) update_labels(p, list(x = \"New x\", y = \"New Y\")) update_labels(p, list(colour = \"Fail silently\")) #> Warning: Ignoring unknown labels: #> • `colour = \"Fail silently\"`"},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":null,"dir":"Reference","previous_headings":"","what":"Quote faceting variables — vars","title":"Quote faceting variables — vars","text":"Just like aes(), vars() quoting function takes inputs evaluated context dataset. inputs can : variable names complex expressions cases, results (vectors variable represents results expressions) used form faceting groups.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Quote faceting variables — vars","text":"","code":"vars(...)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Quote faceting variables — vars","text":"... Variables expressions automatically quoted. evaluated context data form faceting groups. Can named (names passed labeller).","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/reference/vars.html","id":"ref-examples","dir":"Reference","previous_headings":"","what":"Examples","title":"Quote faceting variables — vars","text":"","code":"p <- ggplot(mtcars, aes(wt, disp)) + geom_point() p + facet_wrap(vars(vs, am)) # vars() makes it easy to pass variables from wrapper functions: wrap_by <- function(...) { facet_wrap(vars(...), labeller = label_both) } p + wrap_by(vs) p + wrap_by(vs, am) # You can also supply expressions to vars(). In this case it's often a # good idea to supply a name as well: p + wrap_by(drat = cut_number(drat, 3)) # Let's create another function for cutting and wrapping a # variable. This time it will take a named argument instead of dots, # so we'll have to use the \"enquote and unquote\" pattern: wrap_cut <- function(var, n = 3) { # Let's enquote the named argument `var` to make it auto-quoting: var <- enquo(var) # `as_label()` will create a nice default name: nm <- as_label(var) # Now let's unquote everything at the right place. Note that we also # unquote `n` just in case the data frame has a column named # `n`. The latter would have precedence over our local variable # because the data is always masking the environment. wrap_by(!!nm := cut_number(!!var, !!n)) } # Thanks to tidy eval idioms we now have another useful wrapper: p + wrap_cut(drat)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/waiver.html","id":null,"dir":"Reference","previous_headings":"","what":"A waiver object. — waiver","title":"A waiver object. — waiver","text":"waiver \"flag\" object, similar NULL, indicates calling function just use default value. used certain functions distinguish displaying nothing (NULL) displaying default value calculated elsewhere (waiver())","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/waiver.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"A waiver object. — waiver","text":"","code":"waiver()"},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":null,"dir":"Reference","previous_headings":"","what":"Arrange 1d structure into a grid — wrap_dims","title":"Arrange 1d structure into a grid — wrap_dims","text":"Arrange 1d structure grid","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"Arrange 1d structure into a grid — wrap_dims","text":"","code":"wrap_dims(n, nrow = NULL, ncol = NULL)"},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":"arguments","dir":"Reference","previous_headings":"","what":"Arguments","title":"Arrange 1d structure into a grid — wrap_dims","text":"n length structure nrow, ncol desired dimensions grid","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/wrap_dims.html","id":"value","dir":"Reference","previous_headings":"","what":"Value","title":"Arrange 1d structure into a grid — wrap_dims","text":"grid dimension vector nrow ncol","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/zeroGrob.html","id":null,"dir":"Reference","previous_headings":"","what":"The zero grob draws nothing and has zero size. — zeroGrob","title":"The zero grob draws nothing and has zero size. — zeroGrob","text":"zero grob draws nothing zero size.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/reference/zeroGrob.html","id":"ref-usage","dir":"Reference","previous_headings":"","what":"Usage","title":"The zero grob draws nothing and has zero size. — zeroGrob","text":"","code":"zeroGrob()"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-development-version","dir":"Changelog","previous_headings":"","what":"ggplot2 (development version)","title":"ggplot2 (development version)","text":"coord_*(expand) can now take logical vector control expansion side panel (top, right, bottom, left) (@teunbrand, #6020) (Breaking) defaults geoms can set one theme. (@teunbrand based pioneering work @dpseidel, #2239) new theme(geom) argument used track defaults. element_geom() function can used populate argument. from_theme() function allows access theme default fields inside aes() function. Passing empty unmapped aesthetics layers raises warning instead throwing error (@teunbrand, #6009). Moved {mgcv} Imports Suggests (@teunbrand, #5986) New reset_geom_defaults() reset_stat_defaults() restore geom stat default aesthetics (@teunbrand, #5975). facet_wrap() can space = \"free_x\" 1-row layouts space = \"free_y\" 1-column layouts (@teunbrand) Secondary axes respect n.breaks setting continuous scales (@teunbrand, #4483). Layers can names (@teunbrand, #4066). (internal) improvements pal_qualitative() (@teunbrand, #5013) coord_radial(clip = \"\") clips panel area graphics device supports clipping paths (@teunbrand, #5952). (internal) Panel clipping responsibility moved Facet class Coord class new Coord$draw_panel() method. theme(strip.clip) now defaults \"\" independent Coord clipping (@teunbrand, 5952). (internal) rearranged code Facet$draw_paensl() method (@teunbrand). Axis labels now justified across facet panels (@teunbrand, #5820) Fixed bug stat_function() x-axis title now produced automatically data added. (@phispu, #5647). geom_sf now accepts shape names (@sierrajohnson, #5808) Added gg class labs() (@phispu, #5553). Missing values discrete palettes longer translated (@teunbrand, #5929). Fixed bug facet_grid(margins = TRUE) using expresssions (@teunbrand, #1864). geom_step() now supports orientation argument (@teunbrand, #5936). position_dodge() position_jitterdodge() now reverse argument (@teunbrand, #3610) coord_radial(r.axis.inside) can now take numeric value control placement internally placed radius axes (@teunbrand, #5805). (internal) default labels derived ggplot_build() rather ggplot_add.Layer() (@teunbrand, #5894) attempt made use variable’s label attribute default label (@teunbrand, #4631) Themes gain additional header_family argument easily set font headers titles (#5886). plot.subtitle, plot.caption plot.tag theme elements now inherit root text element instead title element (#5886). ggplot2 longer imports {glue} (@teunbrand, #5986). geom_rect() can now derive required corners positions x/width y/height parameterisation (@teunbrand, #5861). position scales now use definition x y aesthetics. lets uncommon aesthetics like xintercept expand scales usual. (#3342, #4966, @teunbrand) Bare numeric values provided Date Datetime scales get inversely transformed (cast Date/POSIXct) warning (@teunbrand). stat_bin() now accepts functions argument breaks (@aijordan, #4561) (internal) plot’s layout now coord parameter used prevent setting identical panel parameters (#5427) (internal) rearranged code Facet$draw_panels() method (@teunbrand). geom_rug() prints warning na.rm = FALSE, per documentation (@pn317, #5905) position_dodge(preserve = \"single\") now handles multi-row geoms better, geom_violin() (@teunbrand based @clauswilke’s work, #2801). position_jitterdodge() now dodges group (@teunbrand, #3656) arrow.fill parameter now applied line-based functions: geom_path(), geom_line(), geom_step() geom_function(), line geometries geom_sf() element_line(). Fixed bug binned guides keep --bounds breaks (@teunbrand, #5870). size draw_key_polygon() glyph now reflects linewidth aesthetic (#4852). New function complete_theme() replicate themes handled plot building (#5801). Special getter setter functions renamed consistency, allowing better tab-completion get_*- set_*-prefixes. old names remain available backward compatibility (@teunbrand, #5568). Discrete scales now support minor_breaks. may make sense discrete position scales, affects placement minor ticks minor gridlines (#5434). Discrete position scales now expose palette argument, can used customise spacings levels (@teunbrand, #5770). default se parameter layers geom = \"smooth\" TRUE data ymin ymax parameters FALSE absent. Note affect default geom_smooth() stat_smooth() (@teunbrand, #5572). bounded density option stat_density() uses wider range prevent discontinuities (#5641). geom_raster() now falls back rendering geom_rect() coordinates Cartesian (#5503). stat_ecdf() now optional weight aesthetic (@teunbrand, #5058). Position scales combined coord_sf() can now use functions breaks argument. addition, n.breaks works intended breaks = NULL removes grid lines axes (@teunbrand, #4622). (Internal) Applying defaults geom_sf() moved internal sf_grob() GeomSf$use_defaults() (@teunbrand). facet_wrap() new options dir argument precisely control panel directions. Internally dir = \"h\" dir = \"v\" deprecated (@teunbrand, #5212). Prevented facet_wrap(..., drop = FALSE) throwing spurious errors character facetting variable contained NAs (@teunbrand, #5485). facets coerce faceting variables factors, ‘ordered’ class dropped (@teunbrand, #5666). geom_curve() now appropriately removes missing data instead throwing errors (@teunbrand, #5831). update_geom_defaults() update_stat_defaults() reset mechanism using new = NULL invisible return previous defaults (#4993). Fixed regression axes breaks = NULL caused axes disappear instead just rendering axis line (@teunbrand, #5816). geom_point() can dodged vertically using position_dodge(..., orientation = \"y\") (@teunbrand, #5809). Fixed bug na.value incorrectly mapped non-NA values (@teunbrand, #5756). Fixed bug guide_custom() throw error theme_void() (@teunbrand, #5856). New helper function gg_par() translate ggplot2’s interpretation graphical parameters {grid}’s interpretation (@teunbrand, #5866). scale_{x/y}_discrete() can now accept sec.axis. recommended use dup_axis() set custom breaks labels, discrete variables transformed (@teunbrand, #3171). stat_density() new computed variable: wdensity, calculated density times sum weights (@teunbrand, #4176). theme() gets new spacing margins arguments spacings (non-text) margins inherit (@teunbrand, #5622). geom_ribbon() can varying fill alpha linear coordinate systems (@teunbrand, #4690). geom_tile() computes default widths heights per panel instead per layer (@teunbrand, #5740). fill panel.border theme setting ignored forced transparent (#5782). stat_align() skips computation 1 group therefore alignment necessary (#5788). position_stack() skips computation x values unique therefore stacking necessary (#5788). new ggplot_build() S3 method classes added, returns input unaltered (@teunbrand, #5800). width implemented aesthetic instead parameter geom_col() geom_bar() (#3142). Fix bug position_jitterdodge() different jitters applied different position aesthetics axis (@teunbrand, #5818). stat_bin(), default boundary now chosen better adhere nbin argument (@teunbrand, #5882, #5036) after_stat() after_scale() throw warnings computed aesthetics correct length (#5901). guide_colourbar() now correctly hands position available_aes parameters downstream (@teunbrand, #5930) geom_hline() geom_vline() now position argument (@yutannihilation, #4285). New function get_strip_labels() retrieve facet labels (@teunbrand, #4979) Fixed bug position_dodge2()’s identification range overlaps (@teunbrand, #5938, #4327). Fixed bug empty discrete scales weren’t recognised (@teunbrand, #5945). (internal) summary function stat_summary() stat_summary_bin() setup total instead per group (@teunbrand, #5971) facet_grid(space = \"free\") can now combined coord_fixed() (@teunbrand, #4584). theme_classic() now black ticks text instead dark gray. addition, theme_classic()’s axis line end \"square\" (@teunbrand, #5978). {tibble} now suggested instead imported (@teunbrand, #5986) ellipsis argument now checked fortify(), get_alt_text(), labs() several guides (@teunbrand, #3196).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-351","dir":"Changelog","previous_headings":"","what":"ggplot2 3.5.1","title":"ggplot2 3.5.1","text":"CRAN release: 2024-04-23 small release focusing fixing regressions 3.5.0 documentation updates.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-5-1","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.5.1","text":"Fixed bug discrete scales map aesthetics consisting NAs (#5623) Fixed spurious warnings sec_axis() breaks = NULL (#5713). Patterns gradients now also enabled geom_sf() (@teunbrand, #5716). default behaviour resolution() reverted pre-3.5.0 behaviour. Whether mapped discrete vectors treated resolution 1 controlled new discrete argument. Fixed bug guide_bins() guide_coloursteps() discrete breaks, levels produced cut(), ordered incorrectly (@teunbrand, #5757).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"improvements-3-5-1","dir":"Changelog","previous_headings":"","what":"Improvements","title":"ggplot2 3.5.1","text":"facets coerce faceting variables factors, ‘ordered’ class dropped (@teunbrand, #5666). coord_map() coord_polar() throw informative warnings used guide system (#5707). passing function stat_contour(breaks), function used calculate breaks even bins binwidth missing (@teunbrand, #5686). geom_step() now supports lineend, linejoin linemitre parameters (@teunbrand, #5705). Fixed performance loss .data pronoun used aes() (#5730). Facet evaluation better dealing inherited errors (@teunbrand, #5670). stat_bin() deals non-finite breaks better (@teunbrand, #5665). axes coord_radial() don’t neatly fit top/right/bottom/left organisation, specifying position = \"top\" position = \"right\" scale flip placement radial axis (#5735) Theme elements exist now throw warnings instead errors (#5719). Fixed bug coord_radial() full circles treated (@teunbrand, #5750). legends detect presence values layer, NA now detected data contains values outside given breaks (@teunbrand, #5749). annotate() now warns stat position arguments (@teunbrand, #5151) guide_coloursteps(even.steps = FALSE) now works discrete data formatted cut() (@teunbrand, #3877).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-350","dir":"Changelog","previous_headings":"","what":"ggplot2 3.5.0","title":"ggplot2 3.5.0","text":"CRAN release: 2024-02-23 minor release turned quite beefy. focused overhauling guide system: system responsible displaying information scales guise axes legends. part overhaul, new guides implemented existing guides refined. look feel guides mostly preserved, internals styling options changed drastically. Briefly summarising highlights, also welcome coord_radial() successor coord_polar(). Initial support newer graphical features, pattern fills added. API changed ()/ vectors interact scale system, namely: .","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-5-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.5.0","text":"guide system. whole. See ‘new features’ information. S3 guide generics still place, S3 methods guide_train(), guide_merge(), guide_geom(), guide_transform(), guide_gengrob() superseded respective ggproto methods. practice, mean NextMethod() sub-classing ggplot2’s guides S3 system longer work. default, guide_legend() now draws key glyph layer value layer’s data. revert old behaviour, can still set show.legend = c({aesthetic} = TRUE) (@teunbrand, #3648). scale_{colour/fill}_gradient2() scale_{colour/fill}_steps2() functions, midpoint argument transformed scale transformation (#3198). legend.key theme element set inherit panel.background theme element. default themes longer set legend.key element. causes visual change default theme_gray() (#5549). scale_name argument continuous_scale(), discrete_scale() binned_scale() soft-deprecated. implemented custom scales, advised double-check unnamed arguments ends (@teunbrand, #1312). legend.text.align legend.title.align arguments theme() deprecated. hjust setting legend.text legend.title elements continues fulfill role text alignment (@teunbrand, #5347). ‘lines’ units geom_label(), often used label.padding argument, now relative text size. causes visual change, fixes misalignment issue textbox text (@teunbrand, #4753) coord_flip() marked superseded. recommended alternative swap x y aesthetic /using orientation argument layer (@teunbrand, #5130). trans argument scales secondary axes renamed transform. trans argument deprecated. access transformation scale, new get_transformation() method added Scale-classes (#5558). Providing numeric vector theme(legend.position) deprecated. set default legend position inside plot use theme(legend.position = \"inside\", legend.position.inside = c(...)) instead.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-5-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.5.0","text":"Plot scales now ignore AsIs objects constructed (x), instead invoking identity scale. allows columns co-exist layers need non-identity scale aesthetic. Also, makes easy specify relative positions (@teunbrand, #5142). fill aesthetic many geoms now accepts grid’s patterns gradients. developers layer extensions, feature can enabled switching fill = alpha(fill, alpha) fill = fill_alpha(fill, alpha) providing fills grid::gpar() (@teunbrand, #3997). New function check_device() testing availability advanced graphics features introduced R 4.1.0 onward (@teunbrand, #5332). coord_radial() successor coord_polar() customisation options. coord_radial() can: integrate new guide system via dedicated guide_axis_theta() display angle coordinate. addition drawing full circles, also draw circle sectors using end argument. avoid data vanishing center plot setting donut argument. adjust angle aesthetic layers, geom_text(), align coordinate system using rotate_angle argument.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"the-guide-system-3-5-0","dir":"Changelog","previous_headings":"New features","what":"The guide system","title":"ggplot2 3.5.0","text":"guide system encompassing axes legends, last remaining chunk ggplot2, rewritten use system instead S3 system. change necessary step officially break open guide system extension package developers. axes legends now inherit class, makes extensible manner geoms, stats, facets coords (#3329, @teunbrand) user-facing change styling guides rewired theme system. Guides now theme argument can style individual guides, theme() gained additional arguments style guides. Theme elements declared guide override theme elements set plot. new theme elements guides : legend.key.spacing{.x/.y}, legend.frame, legend.axis.line, legend.ticks, legend.ticks.length, legend.text.position legend.title.position. Previous style options arguments guide_*() functions soft-deprecated. Unfortunately, fully preserve function pre-existing guide extensions written S3 system. fallback old guides encapsulated class, calls old S3 generics. S3 methods removed part cleaning , old guides still work S3 methods reimplemented, encourage switch new system (#2728). order argument guides now strictly needs length-1 integer (#4958).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"axes-3-5-0","dir":"Changelog","previous_headings":"New features > The guide system","what":"Axes","title":"ggplot2 3.5.0","text":"New guide_axis_stack() combine axis guides top one another. New guide_axis_theta() draw axis circular arc coord_radial(). guide can controlled adding guides(theta = guide_axis_theta(...)) plot. New guide_axis_logticks() can used draw logarithmic tick marks axis. supersedes annotation_logticks() function (@teunbrand, #5325). guide_axis() gains minor.ticks argument draw minor ticks (#4387). guide_axis() gains cap argument can used trim axis line extreme breaks (#4907). Primary axis titles now placed primary guide, guides(x = guide_axis(position = \"top\")) display title top default (#4650). default vjust axis.title.y.right element now 1 instead Unknown secondary axis guide positions now inferred opposite primary axis guide latter known position (#4650).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"legends-3-5-0","dir":"Changelog","previous_headings":"New features > The guide system","what":"Legends","title":"ggplot2 3.5.0","text":"New guide_custom() function drawing custom graphical objects (grobs) unrelated scales legend positions (#5416). legends acquired position argument, allows individual guides deviate legend.position set theme() function. means legends can now placed multiple sides plot (#5488). spacing legend keys labels, addition legends titles, now controlled text’s margin setting. specifying margins automatically add appropriate text margins. control spacing within legend keys, new legend.key.spacing.{x/y} argument can used theme(). leaves legend.spacing theme setting dedicated solely controlling spacing different guides (#5455). guide_colourbar() guide_coloursteps() gain alpha argument set transparency bar (#5085). New display argument guide_colourbar() supplants raster argument. R 4.1.0 , display = \"gradient\" draw gradient. Legend keys can draw arrows size adjusted arrows. legend titles larger legend, title justification extends placement keys labels (#1903). Glyph drawing functions draw_key_*() family can now set \"width\" \"height\" attributes (centimetres) produced keys control displayed size legend. coord_sf() now uses customisable guides provided scales guides() function (@teunbrand).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"improvements-3-5-0","dir":"Changelog","previous_headings":"","what":"Improvements","title":"ggplot2 3.5.0","text":"guide_coloursteps(even.steps = FALSE) now draws one rectangle per interval instead many small ones (#5481). draw_key_label() now better reflects appearance labels (#5561). position_stack() longer silently removes missing data, now handled geom instead position (#3532). minor_breaks function argument scales can now also take function two arguments: scale’s limits scale’s major breaks (#3583). Failing fit predict stat_smooth() now gives warning omits failed group, instead throwing error (@teunbrand, #5352). labeller() now handles unspecified entries lookup tables (@92amartins, #4599). fortify.default() now accepts data-frame-like object granted object exhibits healthy dim(), colnames(), .data.frame() behaviours (@hpages, #5390). geom_violin() gains bounds argument analogous geom_density()s (@eliocamp, #5493). apply dodging consistently violin plots, stat_ydensity() now drop argument keep discard groups 1 observation. geom_boxplot() gains new argument, staplewidth can draw staples ends whiskers (@teunbrand, #5126) geom_boxplot() gains outliers argument switch outliers , manner affects scale range. hiding outliers affect scale range, can continue use outlier.shape = NA (@teunbrand, #4892). Nicer error messages xlim/ylim arguments coord-* functions (@92amartins, #4601, #5297). can now omit either xend yend geom_segment() one now required. one missing, filled x y aesthetics respectively. makes drawing horizontal vertical segments little bit convenient (@teunbrand, #5140). geom_path() aesthetics varying within groups, arrow() applied groups instead individual segments (@teunbrand, #4935). geom_text() geom_label() gained size.unit parameter set text size millimetres, points, centimetres, inches picas (@teunbrand, #3799). geom_label() now uses angle aesthetic (@teunbrand, #2785) label.padding argument geom_label() now supports inputs created margin() function (#5030). ScaleContinuous$get_breaks() now calls scales::zero_range() limits transformed space, rather data space (#5304). Scales throw informative messages (@teunbrand, #4185, #4258) scale_*_manual() named values argument now emits warning none names match values found data (@teunbrand, #5298). name argument scales now explicitly first argument (#5535) translate_shape_string() internal function now exported use extensions point layers (@teunbrand, #5191). improve width calculation bar plots empty factor levels, resolution() considers mapped_discrete values resolution 1 (@teunbrand, #5211) theme(), elements can specified rel() inherit unit-class objects relative fashion (@teunbrand, #3951). theme() now supports splicing list arguments (#5542). theme element hierarchy, parent elements strict subclass child elements now confer subclass upon children (#5457). New plot.tag.location theme() can control placement plot tag \"margin\", \"plot\" new \"panel\" option (#4297). coord_munch() can now close polygon shapes (@teunbrand, #3271) Aesthetics listed geom_*() stat_*() layers now point relevant documentation (@teunbrand, #5123). new argument axes facet_grid() facet_wrap() controls display axes interior panel positions. Additionally, axis.labels argument can used draw tick marks fully labelled axes (@teunbrand, #4064). coord_polar() can free scales facets (@teunbrand, #2815). get_guide_data() function can used extract position label information plot (#5004). Improve performance layers without positional scales (@zeehio, #4990) informative error mismatched direction/theme(legend.direction = ...) arguments (#4364, #4930).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-5-0","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.5.0","text":"Fixed regression guide_legend() linewidth key size wasn’t adapted width lines (#5160). guide_bins(), title longer arbitrarily becomes offset guide long labels. guide_colourbar() guide_coloursteps() merge properly one aesthetics dropped (#5324). using geom_dotplot(binaxis = \"x\") discrete y-variable, dots now stacked y-position rather 0 (@teunbrand, #5462) stat_count() treats x unique manner unique() (#4609). plot’s title, subtitle caption now obey horizontal text margins (#5533). Contour functions fail options(\"OutDec\") . (@eliocamp, #5555). Lines linewidth = NA now dropped geom_sf() (#5204). ggsave() longer sometimes creates new directories, now controlled new create.dir argument (#5489). Legend titles longer take space ’ve removed setting legend.title = element_blank() (@teunbrand, #3587). resolution() small tolerance, preventing spuriously small resolutions due rounding errors (@teunbrand, #2516). stage() now works correctly, even aesthetics scales (#5408) stat_ydensity() incomplete groups calculates default width parameter stably (@teunbrand, #5396) size argument annotation_logticks() deprecated favour linewidth argument (#5292). Binned scales now treat NAs limits way continuous scales (#5355). Binned scales work better trans = \"reverse\" (#5355). Integers valid input theme arguments expect numeric input (@teunbrand, #5369) Legends scale_*_manual() can show NA values values named vector (@teunbrand, #5214, #5286). Fixed bug coord_sf() graticule lines didn’t obey panel.grid.major’s linewidth setting (@teunbrand, #5179) Fixed bug annotation_logticks() suitable tick positions found (@teunbrand, #5248). default width geom_bar() now based panel-wise resolution data, rather global resolution (@teunbrand, #4336). stat_align() now applied per panel instead globally, preventing issues facets different ranges (@teunbrand, #5227). stacking bug stat_align() fixed (@teunbrand, #5176). stat_contour() stat_contour_filled() now warn remove duplicated coordinates (@teunbrand, #5215). guide_coloursteps() guide_bins() sort breaks (#5152).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"internal-changes-3-5-0","dir":"Changelog","previous_headings":"","what":"Internal changes","title":"ggplot2 3.5.0","text":"ScaleContinuous$get_breaks() method longer censors computed breaks. ggplot object now contains $layout points Layout ggproto object used ggplot_build.ggplot method. exposed package developers may extend behaviour Layout ggproto object without needing develop entirely new ggplot_build method (@jtlandis, #5077). Guide building now part ggplot_build() instead ggplot_gtable() allow guides observe unmapped data (#5483). titleGrob() function refactored faster less complicated. scales_*() functions related managing class implemented methods class, rather stray functions (#1310).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-344","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.4","title":"ggplot2 3.4.4","text":"CRAN release: 2023-10-12 hotfix release adapts change r-devel’s base::.atomic() upcoming retirement maptools. fortify() sp objects (e.g., SpatialPolygonsDataFrame) now deprecated removed soon support upcoming retirement rgdal, rgeos, maptools. advance whole removal, fortify(, region = ...) longer works version (@yutannihilation, #5244).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-343","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.3","title":"ggplot2 3.4.3","text":"CRAN release: 2023-08-14 hotfix release addresses version comparison change r-devel. user-facing breaking changes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-342","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.2","title":"ggplot2 3.4.2","text":"CRAN release: 2023-04-03 hotfix release anticipating changes r-devel, folds upkeep changes bug fixes well.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-3-4-2","dir":"Changelog","previous_headings":"","what":"Minor improvements","title":"ggplot2 3.4.2","text":"Various type checks messages standardised (@teunbrand, #4834). ggplot2 now uses scales::DiscreteRange scales::ContinuousRange, available write scale extensions scratch (@teunbrand, #2710). layer_data(), layer_scales() layer_grob() now default plot = last_plot() (@teunbrand, #5166). datetime_scale() scale constructor now exported use extension packages (@teunbrand, #4701).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-4-2","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.4.2","text":"update_geom_defaults() update_stat_defaults() now return properly classed objects updated docs (@dkahle, #5146). purposes checking required non-missing aesthetics, character vectors longer considered non-finite (@teunbrand, @4284). annotation_logticks() skips drawing ticks scale range non-finite instead throwing error (@teunbrand, #5229). Fixed spurious warnings weight used stat_bin_2d(), stat_boxplot(), stat_contour(), stat_bin_hex() stat_quantile() (@teunbrand, #5216). prevent changing plotting order, stat_sf() now computed per panel instead per group (@teunbrand, #4340). Fixed bug coord_sf() graticule lines didn’t obey panel.grid.major’s linewidth setting (@teunbrand, #5179). geom_text() drops observations angle = NA instead throwing error (@teunbrand, #2757).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-341","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.1","title":"ggplot2 3.4.1","text":"CRAN release: 2023-02-10 small release focusing fixing regressions 3.4.0 release minor polishes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-4-1","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.4.1","text":"computed variable y stat_ecdf() superseded ecdf prevent incorrect scale transformations (@teunbrand, #5113 #5112).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-4-1","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.4.1","text":"Added scale_linewidth_manual() scale_linewidth_identity() support linewidth aesthetic (@teunbrand, #5050). ggsave() warns multiple filenames given, writes first file (@teunbrand, #5114).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-3-4-1","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 3.4.1","text":"Fixed regression geom_hex() aesthetics replicated across bins (@thomasp85, #5037 #5044). Using two ordered factors facetting variables facet_grid(..., .table = FALSE) now throws warning instead error (@teunbrand, #5109). Fixed misbehaviour draw_key_boxplot() draw_key_crossbar() skewed key aspect ratio (@teunbrand, #5082). Fixed spurious warning weight aesthetic used stat_smooth() (@teunbrand based @clauswilke’s suggestion, #5053). lwd alias now correctly replaced linewidth instead size (@teunbrand based @clauswilke’s suggestion #5051). Fixed regression Coord$train_panel_guides() names guides dropped (@maxsutton, #5063). binned scales: Automatic breaks longer --bounds, automatic limits adjusted include breaks (@teunbrand, #5082). Zero-range limits longer throw error treated akin continuous scales zero-range limits (@teunbrand, #5066). trans = \"date\" trans = \"time\" transformations made compatible (@teunbrand, #4217).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-340","dir":"Changelog","previous_headings":"","what":"ggplot2 3.4.0","title":"ggplot2 3.4.0","text":"CRAN release: 2022-11-04 minor release focusing tightening internals ironing inconsistencies API. biggest change addition linewidth aesthetic takes sizing width line size. change, attempting non-breaking possible, potential change look plots. notable changes complete redo error warning messaging ggplot2 using cli package. Messaging now better contextualised easier identify layer error coming . Last, now made switch using vctrs package internally means support vctrs classes variables improve, along small gains rendering speed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-4-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.4.0","text":"linewidth aesthetic introduced supersedes size aesthetic scaling width lines line based geoms. size remain functioning deprecated geoms recommended update code reflect new aesthetic. geoms point sizing linewidth sizing (geom_pointrange() geom_sf) size now refers sizing points can leads visual change old code (@thomasp85, #3672) default line width polygons geom_sf() decreased 0.2 reflect usually used demarking borders thinner line better suited. change made since already induced visual change geom_sf() introduction linewidth aesthetic. dot-dot notation (..var..) stat(), superseded after_stat(), now formally deprecated (@yutannihilation, #3693). qplot() now formally deprecated (@yutannihilation, #3956). stage() now properly refers values without scale transformations stage after_stat. code requires scaled version values reason, apply transformation , e.g. sqrt() scale_{x,y}_sqrt() (@yutannihilation @teunbrand, #4155). Use rlang::hash() instead digest::digest(). update may lead changes automatic sorting legends. order enforce specific legend order use order argument guide. (@thomasp85, #4458) referring x backquoted expressions label_bquote() longer possible. ticks.linewidth frame.linewidth parameters guide_colourbar() now multiplied .pt like elsewhere ggplot2. can cause visual changes arguments defaults changes can restored previous behaviour adding / .pt (@teunbrand #4314). scale_*_viridis_b() now uses full range viridis scales (@gregleleu, #4737)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-4-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.4.0","text":"geom_col() geom_bar() gain new just argument. set 0.5 default; use just = 0/just = 1 place columns left/right axis breaks. (@wurli, #4899) geom_density() stat_density() now support bounds argument estimate density boundary correction (@echasnovski, #4013). ggplot now checks statistical transformations whether data columns dropped warns . stats intend drop data columns can declare new field dropped_aes. (@clauswilke, #3250) ... supports rlang::list2 dynamic dots public functions. (@mone27, #4764) theme() now strip.clip argument, can set \"\" prevent clipping strip text background borders (@teunbrand, #4118) geom_contour() now accepts function breaks argument (@eliocamp, #4652).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-bug-fixes-3-4-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and bug fixes","title":"ggplot2 3.4.0","text":"Fix bug position_jitter() infinity values dropped (@javlon, #4790). geom_linerange() now respects na.rm argument (#4927, @thomasp85) Improve support guide_axis() coord_trans() (@yutannihilation, #3959) Added stat_align() align data without common x-coordinates prior stacking. now default stat geom_area() (@thomasp85, #4850) Fix bug stat_contour_filled() break value differences certain number digits cause computations fail (@thomasp85, #4874) Secondary axis ticks now positioned precisely, removing small visual artefacts alignment grid ticks (@thomasp85, #3576) Improve stat_function documentation regarding xlim argument. (@92amartins, #4474) Fix various issues labels, breaks, limits, show.limits interact different binning guides (@thomasp85, #4831) Automatic break calculation now squishes scale limits domain transformation. allows scale_{x/y}_sqrt() find breaks 0 appropriate (@teunbrand, #980). Using multiple modified aesthetics correctly longer trigger warnings. used incorrectly, warning now report duplicated aesthetic instead NA (@teunbrand, #4707). aes() now supports !!! operator first two arguments (#2675). Thanks @yutannihilation @teunbrand draft implementations. Require rlang >= 1.0.0 (@billybarc, #4797) geom_violin() longer issues “collapsing unique ‘x’ values” warning (@bersbersbers, #4455) annotate() now documents unsupported geoms (geom_abline(), geom_hline() geom_vline()), warns requested (@mikmart, #4719) presidential dataset now includes Trump’s presidency (@bkmgit, #4703). position_stack() now works fully geom_text() (@thomasp85, #4367) geom_tile() now correctly recognises missing data xmin, xmax, ymin, ymax (@thomasp85 @sigmapi, #4495) geom_hex() now use binwidth stat_bin_hex() present, instead deriving (@thomasp85, #4580) geom_hex() now works non-linear coordinate systems (@thomasp85) Fixed bug throwing errors trying render empty plot secondary axes (@thomasp85, #4509) Axes now added correctly facet_wrap() .table = FALSE (@thomasp85, #4553) Better compatibility custom device functions ggsave() (@thomasp85, #4539) Binning scales now resilient calculated limits ends NaN transformations (@thomasp85, #4510) Strip padding facet_grid() now effect strip.placement = \"outside\" axis present strip panel (@thomasp85, #4610) Aesthetics length 1 now recycled 0 length data 0 (@thomasp85, #4588) Setting size = NA longer cause guide_legend() error (@thomasp85, #4559) Setting stroke NA geom_point() longer impair sizing points (@thomasp85, #4624) stat_bin_2d() now correctly recognises weight aesthetic (@thomasp85, #4646) geoms now consistent exposure linejoin lineend parameters, guide keys now respect settings (@thomasp85, #4653) geom_sf() now respects arrow parameter lines (@jakeruss, #4659) Updated documentation print.ggplot reflect returns original plot, result ggplot_build(). (@r2evans, #4390) scale_*_manual() longer displays extra legend keys, changes order, named values argument items data. display values legend instead, use scale_*_manual(values = vals, limits = names(vals)). (@teunbrand, @banfai, #4511, #4534) Updated documentation geom_contour() correctly reflect argument precedence bins binwidth. (@eliocamp, #4651) Dots geom_dotplot() now correctly aligned baseline stackratio != 1 stackdir != \"\" (@mjskay, #4614) Key glyphs geom_boxplot(), geom_crossbar(), geom_pointrange(), geom_linerange() now orientation-aware (@mjskay, #4732) Updated documentation geom_smooth() clearly describe effects fullrange parameter (@thoolihan, #4399).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-336","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.6","title":"ggplot2 3.3.6","text":"CRAN release: 2022-05-03 small release applying internal change comply R 4.2 deprecation default.stringsAsFactors(). user facing changes breaking changes.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-335","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.5","title":"ggplot2 3.3.5","text":"CRAN release: 2021-06-25 small release focusing fixing couple untenable issues surfaced 3.3.4 release Revert changes made #4434 (apply transform intercept geom_abline()) introduced undesirable issues far worse bug fixed (@thomasp85, #4514) Fixes issue ggsave() producing emf/wmf files (@yutannihilation, #4521) Warn grDevices specific arguments passed ragg devices (@thomasp85, #4524) Fix issue coord_sf() reporting non-linear even data provided projected coordinates (@clauswilke, #4527)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-334","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.4","title":"ggplot2 3.3.4","text":"CRAN release: 2021-06-16 larger patch release fixing huge number bugs introduces small selection feature refinements.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"features-3-3-4","dir":"Changelog","previous_headings":"","what":"Features","title":"ggplot2 3.3.4","text":"Alt-text can now added plot using alt label, .e + labs(alt = ...). Currently alt text automatically propagated, plan integrate Shiny, RMarkdown, tools future. (@thomasp85, #4477) Add support BrailleR package creating descriptions plot rendered (@thomasp85, #4459) coord_sf() now argument default_crs specifies coordinate reference system (CRS) non-sf layers scale/coord limits. argument defaults NULL, means non-sf layers assumed projected coordinates, prior ggplot2 versions. Setting default_crs = sf::st_crs(4326) provides simple way interpret x y positions longitude latitude, regardless CRS used coord_sf(). Authors extension packages implementing stat_sf()-like functionality encouraged look source code stat_sf()’s compute_group() function see provide scale-limit hints coord_sf() (@clauswilke, #3659). ggsave() now uses ragg render raster output ragg available. also handles custom devices sets default unit (e.g. ragg::agg_png) correctly (@thomasp85, #4388) ggsave() now returns saved file location invisibly (#3379, @eliocamp). Note , side effect, unofficial hack + ggsave() longer works (#4513). scale arguments limits, breaks, minor_breaks, labels, rescaler oob now accept purrr style lambda notation (@teunbrand, #4427). true as_labeller() (therefore also labeller()) (@netique, #4188). Manual scales now allow named vectors passed values contain fewer elements existing data. Elements present values set NA (@thomasp85, #3451) Date datetime position scales support --bounds (oob) arguments control limits affect data outside limits (@teunbrand, #4199).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"fixes-3-3-4","dir":"Changelog","previous_headings":"","what":"Fixes","title":"ggplot2 3.3.4","text":"Fix bug after_stat() after_scale() refer aesthetics ’s specified plot-global mapping (@yutannihilation, #4260). Fix bug annotate_logticks() cause error used together coord_flip() (@thomasp85, #3954) Fix bug geom_abline() resulted intercept subjected transformation y scale (@thomasp85, #3741) Extent range line created geom_abline() line ending visible large linewidths (@thomasp85, #4024) Fix bug geom_dotplot() dots positioned wrong stackgroups = TRUE (@thomasp85, #1745) Fix calculation confidence interval locfit smoothing geom_smooth() (@topepo, #3806) Fix bug geom_text() \"outward\" \"inward\" justification angle values reversed (@aphalo, #4169, #4447) ggsave() now sets default background match fill value plot.background theme element (@karawoo, #4057) now deprecated specify guides( = FALSE) scale_*(guide = FALSE) remove guide. Please use guides( = \"none\") scale_*(guide = \"none\") instead (@yutannihilation, #4097) Fix bug guide_bins() keys disappear guide reversed (@thomasp85, #4210) Fix bug guide_coloursteps() repeat terminal bins breaks coincided limits scale (@thomasp85, #4019) Make sure default labels default mappings doesn’t overwrite default labels explicit mappings (@thomasp85, #2406) Fix bug labeller() parsing turned .multiline = FALSE (@thomasp85, #4084) Make sure label_bquote() access calling environment evaluating labels (@thomasp85, #4141) Fix bug layer implementation introduced new state first render lead different look rendered second time (@thomasp85, #4204) Fix bug legend justification justification lost legend dimensions exceeded available size (@thomasp85, #3635) Fix bug position_dodge2() NA values thee data cause error (@thomasp85, #2905) Make sure position_jitter() creates jittering independent whether called name constructor (@thomasp85, #2507) Fix bug position_jitter() different jitters applied different position aesthetics axis (@thomasp85, #2941) Fix bug qplot() supplying c(NA, NA) axis limits (@thomasp85, #4027) Remove cross-inheritance default discrete colour/fill scales check type aesthetic function output type function (@thomasp85, #4149) Fix bug scale_[x|y]_date() custom breaks functions resulted fractional dates get misaligned (@thomasp85, #3965) Fix bug scale_[x|y]_datetime() specified timezone ignored scale (@thomasp85, #4007) Fix issue sec_axis() throw warnings absence secondary breaks (@thomasp85, #4368) stat_bin()’s computed variable width now documented (#3522). stat_count() now computes width based full dataset instead per group (@thomasp85, #2047) Extended stat_ecdf() calculate cdf either x y instead y (@jgjl, #4005) Fix bug stat_summary_bin() one requested number bins created (@thomasp85, #3824) drop groups stat_ydensity() fewer two data points throw warning (@andrewwbutler, #4111). Fixed bug strip assembly theme strip.text = element_blank() plots faceted multi-layered strips (@teunbrand, #4384). Using theme(aspect.ratio = ...) together free space facet_grid() now correctly throws error (@thomasp85, #3834) Fixed bug labeller() .default passed as_labeller() labellers specified naming faceting variables. (@waltersom, #4031) Updated style example code (@rjake, #4092) ggplot2 now requires R >= 3.3 (#4247). ggplot2 now uses rlang::check_installed() check suggested package installed, offer install package continuing (#4375, Improved error hint piping ggplot object facet function (#4379, @mitchelloharawild).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-333","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.3","title":"ggplot2 3.3.3","text":"CRAN release: 2020-12-30 small patch release mainly intended address changes R CRAN. changes licensing model ggplot2 MIT license. Update ggplot2 licence MIT license (#4231, #4232, #4233, #4281) Use vdiffr conditionally ggplot2 can tested systems without vdiffr Update tests work new .equal() defaults R >4.0.3 Fixed bug guide_bins() mistakenly ignore override.aes argument (@yutannihilation, #4085).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-332","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.2","title":"ggplot2 3.3.2","text":"CRAN release: 2020-06-19 small release focusing fixing regressions introduced 3.3.1. Added outside option annotation_logticks() places tick marks outside plot bounds. (#3783, @kbodwin) annotation_raster() adds support native rasters. large rasters, native rasters render significantly faster arrays (@kent37, #3388) Facet strips now dedicated position-dependent theme elements (strip.text.x.top, strip.text.x.bottom, strip.text.y.left, strip.text.y.right) inherit strip.text.x strip.text.y, respectively. consequence, theme stylings now need applied position-dependent elements rather parent elements. change already introduced ggplot2 3.3.0 listed changelog. (@thomasp85, #3683) Facets now handle layers containing data (@yutannihilation, #3853). newly added geom geom_density_2d_filled() associated stat stat_density_2d_filled() can draw filled density contours (@clauswilke, #3846). newly added geom_function() now recommended use conjunction /instead stat_function(). addition, stat_function() now works transformed y axes, e.g. scale_y_log10(), plots containing data layers (@clauswilke, #3611, #3905, #3983). Fixed bug geom_sf() caused problems legend-type autodetection (@clauswilke, #3963). Support graphics devices use file argument instead fileneame ggsave() (@bwiernik, #3810) Default discrete color scales now configurable options() ggplot2.discrete.colour ggplot2.discrete.fill. set character vector colour codes (list character vectors) sufficient length, colours used default scale. See help(scale_colour_discrete) details examples (@cpsievert, #3833). Default continuous colour scales (.e., options() ggplot2.continuous.colour ggplot2.continuous.fill, inform type argument scale_fill_continuous() scale_colour_continuous()) now accept function, allows control default continuous_scale()s (@cpsievert, #3827). bug fixed stat_contour() calculating breaks based bins argument (@clauswilke, #3879, #4004). Data columns can now contain Vector S4 objects, widely used Bioconductor project. (@teunbrand, #3837)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-331","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.1","title":"ggplot2 3.3.1","text":"CRAN release: 2020-05-28 small release code change. removes malicious links site got hijacked readme pkgdown site.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-330","dir":"Changelog","previous_headings":"","what":"ggplot2 3.3.0","title":"ggplot2 3.3.0","text":"CRAN release: 2020-03-05 minor release contain range substantial new features, along standard bug fixes. release contains visual breaking changes, along breaking changes extension developers due shift internal representation position scales axes. user breaking changes included. release also adds Dewey Dunnington (@paleolimbot) core team.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-3-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.3.0","text":"user-facing breaking changes, change internal representations extension developers may relied , along breaking visual changes may cause visual tests downstream packages fail. panel_params field Layout now contains list list ViewScale objects, describing trained coordinate system scales, instead list object used . extensions use field likely break, unit tests checks aspects . element_text() now issues warning vectorized arguments provided, colour = c(\"red\", \"green\", \"blue\"). use discouraged officially supported (@clauswilke, #3492). Changed theme_grey() setting legend key creates border (NA) rather drawing white one. (@annennenne, #3180) geom_ribbon() now draws separate lines upper lower intervals colour mapped. Similarly, geom_area() geom_density() now draw upper lines case default. want old-style full stroking, use outline.type = \"full\" (@yutannihilation, #3503 / @thomasp85, #3708).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-3-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.3.0","text":"evaluation time aesthetics can now controlled finer degree. after_stat() supersedes use stat() ..var..-notation, joined after_scale() allow mapping scaled aesthetic values. Remapping aesthetic now supported stage(), can map data variable stat aesthetic, remap aesthetic something else statistical transformation (@thomasp85, #3534) coord_*() functions xlim ylim arguments now accept vectors NA placeholder minimum maximum value (e.g., ylim = c(0, NA) zoom y-axis 0 maximum value observed data). mimics behaviour limits argument continuous scale functions (@paleolimbot, #2907). Allowed reversing discrete scales re-writing get_limits() (@AnneLyng, #3115) geoms stats direction (.e. x y axes different interpretation), can now freely choose direction, instead relying coord_flip(). direction deduced aesthetic mapping, can also specified directly new orientation argument (@thomasp85, #3506). Position guides can now customized using new guide_axis(), can passed position scale_*() functions via guides(). new axis guide (guide_axis()) comes arguments check.overlap (automatic removal overlapping labels), angle (easy rotation axis labels), n.dodge (dodge labels multiple rows/columns) (@paleolimbot, #3322). new scale type added, allows binning aesthetics scale level. versions position non-position aesthetics comes two new guides (guide_bins guide_coloursteps) (@thomasp85, #3096) scale_x_continuous() scale_y_continuous() gains n.breaks argument guiding number automatic generated breaks (@thomasp85, #3102) Added stat_contour_filled() geom_contour_filled(), compute draw filled contours gridded data (@paleolimbot, #3044). geom_contour() stat_contour() now use isoband package compute contour lines. complete parameter (undocumented unused least four years) removed (@paleolimbot, #3044). Themes gained two new parameters, plot.title.position plot.caption.position, can used customize plot title/subtitle plot caption positioned relative overall plot (@clauswilke, #3252).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensions-3-3-0","dir":"Changelog","previous_headings":"","what":"Extensions","title":"ggplot2 3.3.0","text":"Geom now gains setup_params() method line ggproto classes (@thomasp85, #3509) newly added function register_theme_elements() now allows developers extension packages define new theme elements place ggplot2 element tree (@clauswilke, #2540).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-bug-fixes-3-3-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and bug fixes","title":"ggplot2 3.3.0","text":"coord_trans() now draws second axes accepts xlim, ylim, expand arguments bring feature parity coord_cartesian(). xtrans ytrans arguments deprecated version 1.0.1 favour x y removed (@paleolimbot, #2990). coord_trans() now calculates breaks using expanded range (previously calculated using unexpanded range, resulted differences plots made coord_trans() made coord_cartesian()). expansion discrete axes coord_trans() also updated behaves identically coord_cartesian() (@paleolimbot, #3338). expand_scale() deprecated favour expansion() setting expand argument x y scales (@paleolimbot). geom_abline(), geom_hline(), geom_vline() now issue informative warnings supplied set aesthetics (.e., slope, intercept, yintercept, /xintercept) mapped aesthetics (.e., data /mapping). Fix bug geom_raster() squeezed image went outside scale limits (#3539, @thomasp85) geom_sf() now determines legend type automatically (@microly, #3646). geom_sf() now removes rows can’t plotted due NA aesthetics (#3546, @thomasp85) geom_sf() now applies alpha linestring geometries (#3589, @yutannihilation). gg_dep() deprecated (@perezp44, #3382). Added function ggplot_add.() lists created (), allowing lists added ggplot objects (#2734, @Maschette) ggplot2 longer depends reshape2, means longer (recursively) needs plyr, stringr, stringi packages. Increase default nbin guide_colourbar() place ticks precisely (#3508, @yutannihilation). manual_scale() now matches values order breaks whenever values unnamed vector. Previously, unnamed values match limits scale ignore order breaks provided. Note may change appearance plots previously relied unordered behaviour (#2429, @idno0001). scale_manual_*(limits = ...) now actually limits scale (#3262, @yutannihilation). Fix bug show.legend named logical vector (#3461, @yutannihilation). Added weight aesthetic option stat_density() made scaling weights default (@annennenne, #2902) stat_density2d() can now take adjust parameter scale default bandwidth. (#2860, @haleyjeppson) stat_smooth() uses REML default, method = \"gam\" gam’s method specified (@ikosmidis, #2630). stacking text calculating labels y axis stat_summary() now works (@ikosmidis, #2709) stat_summary() related functions now support rlang-style lambda functions (#3568, @dkahle). data mask pronoun, .data, now stripped default labels. Addition partial themes plots made predictable; stepwise addition individual partial themes now equivalent addition multple theme elements (@clauswilke, #3039). Facets now don’t fail even variable spec available layers (@yutannihilation, #2963).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-321","dir":"Changelog","previous_headings":"","what":"ggplot2 3.2.1","title":"ggplot2 3.2.1","text":"CRAN release: 2019-08-10 patch release fixing regressions introduced 3.2.0 well fixing unit tests broke due upstream changes. position_stack() longer changes order input data. Changes internal behaviour geom_ribbon() made reordering problematic ribbons spanned y = 0 (#3471) Using qplot() single positional aesthetic longer title non-specified scale \"NULL\" (#3473) Fixes unit tests sf graticule labels caused changes sf","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-320","dir":"Changelog","previous_headings":"","what":"ggplot2 3.2.0","title":"ggplot2 3.2.0","text":"CRAN release: 2019-06-16 minor release emphasis internal changes make ggplot2 faster consistent. interface changes affect aesthetics plot minor ways, potentially break code extension developers relied internals changed. release also sees addition Hiroaki Yutani (@yutannihilation) core developer team. release R 3.6, ggplot2 now requires R version least 3.2, tidyverse committed support 5 major versions R.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-2-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.2.0","text":"Two patches (#2996 #3050) fixed minor rendering problems. cases, visual changes subtle difficult see naked eye. However, changes detected vdiffr package, therefore package developers use vdiffr test visual correctness ggplot2 plots regenerate reference images. cases, ggplot2 now produces warning error code previously produced plot output. cases, previous plot output accidental, plotting code uses ggplot2 API way lead undefined behavior. Examples include missing group aesthetic geom_boxplot() (#3316), annotations across multiple facets (#3305), using aesthetic mappings drawing ribbons geom_ribbon() (#3318).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-2-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.2.0","text":"release includes range internal changes speeds plot generation. None changes user facing break code, general ggplot2 feel much faster. changes includes, limited : Caching ascent descent dimensions text avoid recalculating every title. Using faster data.frame constructor well faster indexing data.frames Removing plyr dependency, replacing plyr functions faster equivalents. geom_polygon() can now draw polygons holes using new subgroup aesthetic. functionality requires R 3.6.0 (@thomasp85, #3128) Aesthetic mappings now accept functions return NULL (@yutannihilation, #2997). stat_function() now accepts rlang/purrr style anonymous functions fun parameter (@dkahle, #3159). geom_rug() gains “outside” option allow moving rug tassels outside plot area (@njtierney, #3085) length option allow changing length rug lines (@daniel-wells, #3109). geoms now take key_glyph paramter allows users customize legend keys drawn (@clauswilke, #3145). addition, new key glyph timeseries provided draw nice legends time series (@mitchelloharawild, #3145).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensions-3-2-0","dir":"Changelog","previous_headings":"","what":"Extensions","title":"ggplot2 3.2.0","text":"Layers now new member function setup_layer() called beginning plot building process access original input data plot object built. function allows creation custom layers autogenerate aesthetic mappings based input data filter input data form. time , feature exported, enabled development new layer type, layer_sf() (see next item). special-purpose layer types may added future (@clauswilke, #2872). new layer type layer_sf() can auto-detect auto-map sf geometry columns data. used extension developers writing new sf-based geoms stats (@clauswilke, #3232). x0 y0 now recognized positional aesthetics get scaled used extension geoms stats (@thomasp85, #3168) Continuous scale limits now accept functions accept default limits return adjusted limits. makes possible write function e.g. ensures limits always multiple 100, regardless data (@econandrew, #2307).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-bug-fixes-3-2-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and bug fixes","title":"ggplot2 3.2.0","text":"cut_width() now accepts ... pass arguments base::cut.default() like cut_number() cut_interval() already (@cderv, #3055) coord_map() now can axes top right (@karawoo, #3042). coord_polar() now correctly rescales secondary axis (@linzi-sg, #3278) coord_sf(), coord_map(), coord_polar() now squash -Inf Inf min max plot (@yutannihilation, #2972). coord_sf() graticule lines now drawn thickness panel grid lines coord_cartesian(), seting panel grid lines element_blank() now also works coord_sf() (@clauswilke, #2991, #2525). economics data regenerated. leads changes values columns (especially psavert), importantly, strips grouping attributes economics_long. element_line() now fills closed arrows (@yutannihilation, #2924). Facet strips left side plots now clipping turned , preventing text running strip borders looking thicker strips (@karawoo, #2772 #3061). ggplot2 now works Turkish locale (@yutannihilation, #3011). Clearer error messages inappropriate aesthetics (@clairemcwhite, #3060). ggplot2 longer attaches external packages using functions depend packages suggested imported ggplot2. affected functions include geom_hex(), stat_binhex(), stat_summary_hex(), geom_quantile(), stat_quantile(), map_data() (@clauswilke, #3126). geom_area() geom_ribbon() now sort data along x-axis setup_data() method rather part draw_group() (@thomasp85, #3023) geom_hline(), geom_vline(), geom_abline() now throw warning user supplies xintercept, yintercept, slope value mapping (@RichardJActon, #2950). geom_rug() now works coord_flip() (@has2k1, #2987). geom_violin() longer throws error quantile lines fall outside violin polygon (@thomasp85, #3254). guide_legend() guide_colorbar() now use appropriate spacing legend key glyphs legend text even legend title missing (@clauswilke, #2943). Default labels now generated consistently; e.g., symbols longer get backticks, long expressions abbreviated ... (@yutannihilation, #2981). -Inf layers now ignored picking scale (@yutannihilation, #3184). Diverging Brewer colour palette now use correct mid-point colour (@dariyasydykova, #3072). scale_color_continuous() now points scale_colour_continuous() handle type = \"viridis\" documentation states (@hlendway, #3079). scale_shape_identity() now works correctly guide = \"legend\" (1, #3029) scale_continuous now draw axis line even length breaks 0 (@thomasp85, #3257) stat_bin() now error number bins exceeds 1e6 avoid accidentally freezing user session (@thomasp85). sec_axis() now places ticks accurately using nonlinear transformations (@dpseidel, #2978). facet_wrap() facet_grid() now automatically remove NULL facet specs, accept empty specs (@yutannihilation, #3070, #2986). stat_bin() now handles data one unique value (@yutannihilation #3047). sec_axis() now accepts functions well formulas (@yutannihilation, #3031). New theme elements allowing different ticks lengths axis. instance, can used inwards ticks x-axis (axis.ticks.length.x) outwards ticks y-axis (axis.ticks.length.y) (@pank, #2935). arguments Stat*$compute_layer() Position*$compute_layer() now renamed always match ones Stat$compute_layer() Position$compute_layer() (@yutannihilation, #3202). geom_*() stat_*() now accepts purrr-style lambda notation (@yutannihilation, #3138). geom_tile() geom_rect() now draw rectangles without notches corners. style corner can controlled linejoin parameters (@yutannihilation, #3050).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-310","dir":"Changelog","previous_headings":"","what":"ggplot2 3.1.0","title":"ggplot2 3.1.0","text":"CRAN release: 2018-10-25","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-1-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.1.0","text":"minor release breaking changes kept minimum. End users ggplot2 unlikely encounter issues. However, items developers ggplot2 extensions aware . additional details, see also discussion accompanying issue #2890. non-user-facing internal code (specifically aes() function aesthetics argument scale functions), ggplot2 now always uses British spelling aesthetics containing word “colour”. users specify “color” aesthetic automatically renamed “colour”. renaming also applied non-standard aesthetics contain word “color”. example, “point_color” renamed “point_colour”. convention makes easier support British American spelling novel, non-standard aesthetics, may require adjustment packages previously introduced non-standard color aesthetics using American spelling. new function standardise_aes_names() provided case extension writers need perform renaming code (@clauswilke, #2649). Functions generate functions (closures) now force arguments used generated functions, avoid hard--catch errors. may affect users manual scales (scale_colour_manual(), scale_fill_manual(), etc.) depend incorrect behavior (@krlmlr, #2807). Coord objects now function backtransform_range() returns panel range data coordinates. change may affect developers custom coords, now implement function. may also affect developers custom geoms use range() function. applications, backtransform_range() may appropriate (@clauswilke, #2821).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-1-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.1.0","text":"coord_sf() much improved customization axis tick labels. Labels can now set manually, two new parameters, label_graticule label_axes, can used specify graticules label side plot (@clauswilke, #2846, #2857, #2881). Two new geoms geom_sf_label() geom_sf_text() can draw labels text sf objects. hood, new stat_sf_coordinates() calculates x y coordinates coordinates sf geometries. can customize calculation method via fun.geometry argument (@yutannihilation, #2761).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"minor-improvements-and-fixes-3-1-0","dir":"Changelog","previous_headings":"","what":"Minor improvements and fixes","title":"ggplot2 3.1.0","text":"benchplot() now uses tidy evaluation (@dpseidel, #2699). error message compute_aesthetics() now provides names aesthetics mismatched lengths, rather aesthetics (@karawoo, #2853). faceted plots, data longer internally reordered. makes safer feed data columns aes() parameters geoms stats. However, remains discouraged (@clauswilke, #2694). coord_sf() now also understands clip argument, just like coords (@clauswilke, #2938). fortify() now displays informative error message grouped_df() objects dplyr installed (@jimhester, #2822). geom_*() now display informative error message required aesthetics missing (@dpseidel, #2637 #2706). geom_boxplot() now understands width parameter even used non-standard stat, stat_identity() (@clauswilke, #2893). geom_hex() now understands size linetype aesthetics (@mikmart, #2488). geom_hline(), geom_vline(), geom_abline() now work properly coord_trans() (@clauswilke, #2149, #2812). geom_text(..., parse = TRUE) now correctly renders expected number items instead silently dropping items empty expressions, e.g. empty string ““. expression spans multiple lines, take just first line drop rest. issue also fixed geom_label() axis labels geom_sf() (@slowkow, #2867). geom_sf() now respects lineend, linejoin, linemitre parameters lines polygons (@alistaire47, #2826). ggsave() now exits without creating new graphics device previously none open (@clauswilke, #2363). labs() now named arguments title, subtitle, caption, tag. Also, labs() now accepts tidyeval (@yutannihilation, #2669). position_nudge() now robust nudges direction requested. enables, example, horizontal nudging boxplots (@clauswilke, #2733). sec_axis() dup_axis() now return appropriate breaks secondary axis applied log transformed scales (@dpseidel, #2729). sec_axis() now works expected used combination tidy eval (@dpseidel, #2788). scale_*_date(), scale_*_time() scale_*_datetime() can now display secondary axis one--one transformation primary axis, implemented using sec.axis argument scale constructor (@dpseidel, #2244). stat_contour(), stat_density2d(), stat_bin2d(), stat_binhex() now calculate normalized statistics including nlevel, ndensity, ncount. Also, stat_density() now includes calculated statistic nlevel, alias scaled, better match syntax stat_bin() (@bjreisman, #2679).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-300","dir":"Changelog","previous_headings":"","what":"ggplot2 3.0.0","title":"ggplot2 3.0.0","text":"CRAN release: 2018-07-03","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"breaking-changes-3-0-0","dir":"Changelog","previous_headings":"","what":"Breaking changes","title":"ggplot2 3.0.0","text":"ggplot2 now supports/uses tidy evaluation (described ). major change breaks number packages; made breaking change important make ggplot2 programmable, consistent rest tidyverse. best general (detailed) introduction tidy evaluation can found meta programming chapters Advanced R. primary developer facing change aes() now contains quosures (expression + environment pairs) rather symbols, ’ll need take different approach extracting information need. common symptom change errors “undefined columns selected” “invalid ‘type’ (list) argument” (#2610). previous version, constants (like aes(x = 1) aes(colour = \"smoothed\")) stored . version ggplot2, need describe mapping string, use quo_name() (generate single-line strings; longer expressions may abbreviated) quo_text() (generate non-abbreviated strings may span multiple lines). need extract value variable instead use rlang::eval_tidy(). may want condition (packageVersion(\"ggplot2\") <= \"2.2.1\") code can work released development versions ggplot2. recognise big change ’re already familiar rlang, ’s lot learn. stuck, need help, please reach https://forum.posit.co/. Error: Column y must 1d atomic vector list Internally, ggplot2 now uses .data.frame(tibble::as_tibble(x)) convert list data frame. improves ggplot2’s support list-columns (needed sf support), small cost: can longer use matrix-columns. Note unlike tibble still allow column vectors returned base::scale() widespread use. Error: one expression parsed Previously aes_string(x = c(\"\", \"b\", \"c\")) silently returned aes(x = ). Now clear error. Error: data must uniquely named duplicate columns layer data contains columns identical names error thrown. earlier versions first occurring column chosen silently, potentially masking wrong data chosen. Error: Aesthetics must either length 1 data Layers stricter columns combine single data frame. aesthetic now must either length data frame single value. makes silent recycling errors much less likely. Error: coord_* doesn’t support free scales Free scales work selected coordinate systems; previously ’d get incorrect plot. Error f(…) : unused argument (range = c(0, 1)) oob argument scale set function takes single argument; needs take two arguments (x, range). Error: unused argument (output) function guide_train() now optional parameter aesthetic allows override aesthetic setting scale. make code work released development versions ggplot2 appropriate, add aesthetic = NULL guide_train() method signature. , inside function, replace scale$aesthetics[1], aesthetic %||% scale$aesthetics[1]. (%||% operator defined rlang package). long-deprecated subset argument layer() removed.","code":"# old guide_train.legend <- function(guide, scale) {...} # new guide_train.legend <- function(guide, scale, aesthetic = NULL) {...} # old setNames(list(scale$map(breaks)), scale$aesthetics[1]) # new setNames(list(scale$map(breaks)), aesthetic %||% scale$aesthetics[1])"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"tidy-evaluation-3-0-0","dir":"Changelog","previous_headings":"","what":"Tidy evaluation","title":"ggplot2 3.0.0","text":"aes() now supports quasiquotation can use !!, !!!, :=. replaces aes_() aes_string() now soft-deprecated (remain around long time). facet_wrap() facet_grid() now support vars() inputs. Like dplyr::vars(), helper quotes inputs supports quasiquotation. instance, can now supply faceting variables like : facet_wrap(vars(, cyl)) instead facet_wrap(~+ cyl). Note formula interface going away deprecated. vars() simply meant make easier create functions around facet_wrap() facet_grid(). first two arguments facet_grid() become rows cols now support vars() inputs. Note however took special care ensure complete backward compatibility. change facet_grid(vars(cyl), vars(, vs)) equivalent facet_grid(cyl ~ + vs), facet_grid(cols = vars(, vs)) equivalent facet_grid(. ~ + vs). One nice aspect new interface can now easily supply names: facet_grid(vars(Cylinder = cyl), labeller = label_both) give nice label titles facets. course, names can unquoted usual tidy eval syntax.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"sf-3-0-0","dir":"Changelog","previous_headings":"Tidy evaluation","what":"sf","title":"ggplot2 3.0.0","text":"ggplot2 now full support sf geom_sf() coord_sf(): supports simple features, automatically aligns CRS across layers, sets correct aspect ratio, draws graticule.","code":"nc <- sf::st_read(system.file(\"shape/nc.shp\", package = \"sf\"), quiet = TRUE) ggplot(nc) + geom_sf(aes(fill = AREA))"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-3-0-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 3.0.0","text":"ggplot2 now works R 3.1 onwards, uses vdiffr package visual testing. cases, accidentally using %>% instead + generate informative error (#2400). New syntax calculated aesthetics. Instead using aes(y = ..count..) can (!) use aes(y = stat(count)). stat() real function documentation hopefully make part ggplot2 less confusing (#2059). stat() particularly nice complex calculations need specify : aes(y = stat(count / max(count))), rather aes(y = ..count.. / max(..count..)) New tag label adding identification tags plots, typically used labelling subplot letter. Add tag labs(tag = \"\"), style plot.tag theme element, control position plot.tag.position theme setting (@thomasp85).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"layers-geoms-stats-and-position-adjustments-3-0-0","dir":"Changelog","previous_headings":"New features","what":"Layers: geoms, stats, and position adjustments","title":"ggplot2 3.0.0","text":"geom_segment() geom_curve() new arrow.fill parameter allows specify separate fill colour closed arrowheads (@hrbrmstr @clauswilke, #2375). geom_point() friends can now take shapes strings instead integers, e.g. geom_point(shape = \"diamond\") (@daniel-barnett, #2075). position_dodge() gains preserve argument allows control whether total width x value preserved (current default), ensure width single element preserved (many people want) (#1935). New position_dodge2() provides enhanced dodging boxplots. Compared position_dodge(), position_dodge2() compares xmin xmax values determine elements overlap, spreads overlapping elements evenly within region overlap. position_dodge2() now default position adjustment geom_boxplot(), handles varwidth = TRUE, considered geoms future. padding parameter adds small amount padding elements (@karawoo, #2143) reverse parameter allows reverse order placement (@karawoo, #2171). New stat_qq_line() makes easy add simple line Q-Q plot, makes easier judge fit theoretical distribution (@nicksolomon).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"scales-and-guides-3-0-0","dir":"Changelog","previous_headings":"New features","what":"Scales and guides","title":"ggplot2 3.0.0","text":"Improved support mapping date/time variables alpha, size, colour, fill aesthetics, including date_breaks date_labels arguments (@karawoo, #1526), new scale_alpha() variants (@karawoo, #1526). Improved support ordered factors. Ordered factors throw warning mapped shape (unordered factors ), throw warnings mapped size alpha (unordered factors ). Viridis used default colour fill scale ordered factors (@karawoo, #1526). expand argument scale_*_continuous() scale_*_discrete() now accepts separate expansion values lower upper range limits. expansion limits can specified using convenience function expand_scale(). Separate expansion limits may useful bar charts, e.g. one wants bottom bars flush x axis still leave (automatically calculated amount ) space : can also useful line charts, e.g. counts time, one wants ’hard’ lower limit y = 0 leave upper limit unspecified (perhaps differing panels), extra space highest point line (symmetrical limits, extra space highest point cases cause lower limit negative). old syntax expand argument , course, continue work (@huftis, #1669). scale_colour_continuous() scale_colour_gradient() now controlled global options ggplot2.continuous.colour ggplot2.continuous.fill. can set \"gradient\" (default) \"viridis\" (@karawoo). New scale_colour_viridis_c()/scale_fill_viridis_c() (continuous) scale_colour_viridis_d()/scale_fill_viridis_d() (discrete) make easy use Viridis colour scales (@karawoo, #1526). Guides geom_text() now accept custom labels guide_legend(override.aes = list(label = \"foo\")) (@brianwdavis, #2458).","code":"ggplot(mtcars) + geom_bar(aes(x = factor(cyl))) + scale_y_continuous(expand = expand_scale(mult = c(0, .1)))"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"margins-3-0-0","dir":"Changelog","previous_headings":"New features","what":"Margins","title":"ggplot2 3.0.0","text":"Strips gain margins sides default. means fully justify text edge strip, need also set margins 0 (@karawoo). Rotated strip labels now correctly understand hjust vjust parameters angles (@karawoo). Strip labels now understand justification relative direction text, meaning y facets, strip text can placed either end strip using hjust (@karawoo). Legend titles labels get little extra space around , prevents legend titles overlapping legend large font sizes (@karawoo, #1881).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extension-points-3-0-0","dir":"Changelog","previous_headings":"","what":"Extension points","title":"ggplot2 3.0.0","text":"New autolayer() S3 generic (@mitchelloharawild, #1974). similar autoplot() produces layers rather complete plots. Custom objects can now added using + ggplot_add method defined class object (@thomasp85). Theme elements can now subclassed. Add merge_element method control properties inherited parent element. Add element_grob method define elements rendered grobs (@thomasp85, #1981). Coords gained new extension mechanisms. existing coord extension, need revise specification train() method. now called setup_panel_params() (better reflecting actually ) now arguments scale_x, scale_y (x y scales respectively) param, list plot specific parameters generated setup_params(). formerly called scale_details (coords), panel_ranges (layout) panel_scales (geoms) now consistently called panel_params (#1311). parameters coord vary panel panel. ggplot_build() ggplot_gtable() now generics, ggplot-subclasses can define additional behavior build stage. guide_train(), guide_merge(), guide_geom(), guide_gengrob() now exported needed want design guide. currently documented; use risk (#2528). scale_type() generic now exported documented. Use want extend ggplot2 work new type vector.","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"faceting-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Faceting","title":"ggplot2 3.0.0","text":"facet_grid() gives informative error message try use variable rows cols (#1928). facet_grid() facet_wrap() give better error messages attempt use unsupported coord free scales (#2049). label_parsed() works (#2279). can now style background horizontal vertical strips independently strip.background.x strip.background.y theme settings (#2249).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"scales-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Scales","title":"ggplot2 3.0.0","text":"discrete_scale() documentation now inherits shared definitions continuous_scale() (@alistaire47, #2052). guide_colorbar() shows colours scale (@has2k1, #2343). scale_identity() produces legends default (#2112). Tick marks secondary axes strong transformations accurately placed (@thomasp85, #1992). Missing line types now reliably generate missing lines (standard warning) (#2206). Legends now ignore set aesthetics length one (#1932). colour fill scales now aesthetics argument can used set aesthetic(s) scale works . makes possible apply colour scale colour fill aesthetics time, via aesthetics = c(\"colour\", \"fill\") (@clauswilke). Three new generic scales work aesthetic set aesthetics: scale_continuous_identity(), scale_discrete_identity(), scale_discrete_manual() (@clauswilke). scale_*_gradient2() now consistently omits points outside limits rescaling limits enforced (@foo-bar-baz-qux, #2230).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"layers-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Layers","title":"ggplot2 3.0.0","text":"geom_label() now correctly produces unbordered labels label.size 0, even saving PDF (@bfgray3, #2407). layer() gives considerably better error messages incorrectly specified geom, stat, position (#2401). layers use , linemitre now defaults 10 (instead 1) better match base R. geom_boxplot() now supplies default value x aesthetic present (@foo-bar-baz-qux, #2110). geom_density() drops groups fewer two data points throws warning. groups two data points, density values now calculated stats::density (@karawoo, #2127). geom_segment() now also takes linejoin parameter. allows control appearance segments, especially useful plotting thick arrows (@Ax3man, #774). geom_smooth() now reports formula used method = \"auto\" (@davharris #1951). geom_smooth() now orders x aesthetic, making easier pass pre-computed values without manual ordering (@izahn, #2028). also now knows ymin ymax aesthetics (#1939). legend correctly reflects status se argument used stats default (@clauswilke, #1546). geom_tile() now interprets width height correctly (1, #2510). position_jitter() position_jitterdodge() gain seed argument allows specification random seed reproducible jittering (@krlmlr, #1996 @slowkow, #2445). stat_density() better behaviour groups dropped small (#2282). stat_summary_bin() now understands breaks parameter (@karawoo, #2214). stat_bin() now accepts functions binwidth. allows better binning faceting along variables different ranges (@botanize). stat_bin() geom_histogram() now sum correctly using weight aesthetic (@jiho, #1921). stat_bin() uses correct scaling computed variable ndensity (@timgoodman, #2324). stat_bin() stat_bin_2d() now properly handle breaks parameter scales transformed (@has2k1, #2366). update_geom_defaults() update_stat_defaults() allow American spelling aesthetic parameters (@foo-bar-baz-qux, #2299). show.legend parameter now accepts named logical vector hide/show aesthetics legend (@tutuchan, #1798). Layers now silently ignore unknown aesthetics value NULL (#1909).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"coords-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Coords","title":"ggplot2 3.0.0","text":"Clipping plot panel now configurable, clip argument coordinate systems, e.g. coord_cartesian(clip = \"\") (@clauswilke, #2536). Like scales, coordinate systems now give message ’re replacing existing coordinate system (#2264). coord_polar() now draws secondary axis ticks labels (@dylan-stark, #2072), can draw radius axis right (@thomasp85, #2005). coord_trans() now generates warning transformation generates non-finite values (@foo-bar-baz-qux, #2147).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"themes-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Themes","title":"ggplot2 3.0.0","text":"Complete themes now always override elements default theme (@has2k1, #2058, #2079). Themes now set default grid colour panel.grid rather individually panel.grid.major panel.grid.minor individually. makes slightly easier customise theme (#2352). Fixed bug setting strips element_blank() (@thomasp85). Axes positioned top right can now customize ticks lines separately (@thomasp85, #1899). Built-themes gain parameters base_line_size base_rect_size control default sizes line rectangle elements (@karawoo, #2176). Default themes use rel() set line widths (@baptiste). Themes tweaked visual consistency graceful behavior changing base font size. absolute heights widths replaced heights widths proportional base font size. One relative font size eliminated (@clauswilke). height descenders now calculated solely font metrics doesn’t change specific letters string. fixes minor alignment issues plot titles, subtitles, legend titles (#2288, @clauswilke).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"guides-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Guides","title":"ggplot2 3.0.0","text":"guide_colorbar() configurable: tick marks color bar frame can now styled arguments ticks.colour, ticks.linewidth, frame.colour, frame.linewidth, frame.linetype (@clauswilke). guide_colorbar() now uses legend.spacing.x legend.spacing.y correctly, can handle multi-line titles. Minor tweaks made guide_legend() make sure two legend functions behave similarly possible (@clauswilke, #2397 #2398). theme elements legend.title legend.text now respect settings margin, hjust, vjust (@clauswilke, #2465, #1502). Non-angle parameters label.theme title.theme can now set guide_legend() guide_colorbar() (@clauswilke, #2544).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"other-3-0-0","dir":"Changelog","previous_headings":"Minor bug fixes and improvements","what":"Other","title":"ggplot2 3.0.0","text":"fortify() gains method tbls (@karawoo, #2218). ggplot gains method grouped_dfs adds .group variable, computes unique value group. Use aes(group = .group) (#2351). ggproto() produces objects class c(\"ggproto\", \"gg\"), allowing informative error message adding layers, scales, ggproto objects (@jrnold, #2056). ggsave()’s DPI argument now supports 3 string options: “retina” (320 DPI), “print” (300 DPI), “screen” (72 DPI) (@foo-bar-baz-qux, #2156). ggsave() now uses full argument names avoid partial match warnings (#2355), correctly restores previous graphics device several graphics devices open (#2363). print.ggplot() now returns original ggplot object, instead output ggplot_build(). Also, object returned ggplot_build() now class \"ggplot_built\" (#2034). map_data() now works even purrr loaded (tidyverse#66). New functions summarise_layout(), summarise_coord(), summarise_layers() summarise layout, coordinate systems, layers built ggplot object (#2034, @wch). provides tested API (e.g.) shiny can depend . Updated startup messages reflect new resources (#2410, @mine-cetinkaya-rundel).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-221","dir":"Changelog","previous_headings":"","what":"ggplot2 2.2.1","title":"ggplot2 2.2.1","text":"CRAN release: 2016-12-30 Fix usage structure(NULL) R-devel compatibility (#1968).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-220","dir":"Changelog","previous_headings":"","what":"ggplot2 2.2.0","title":"ggplot2 2.2.0","text":"CRAN release: 2016-11-11","code":""},{"path":[]},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"subtitle-and-caption-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Subtitle and caption","title":"ggplot2 2.2.0","text":"Thanks @hrbrmstr plots now subtitles captions, can set subtitle caption arguments ggtitle() labs(). can control appearance theme settings plot.caption plot.subtitle. main plot title now left-aligned better work better subtitle. caption right-aligned (@hrbrmstr).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"stacking-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Stacking","title":"ggplot2 2.2.0","text":"position_stack() position_fill() now sort stacking order match grouping order. allows control order grouping, ensures default legend matches plot (#1552, #1593). want opposite order (useful horizontal bars horizontal legend), can request reverse stacking using position = position_stack(reverse = TRUE) (#1837). position_stack() position_fill() now accepts negative values create stacks extending x-axis (#1691). position_stack() position_fill() gain vjust argument makes easy (e.g.) display labels middle stacked bars (#1821).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"layers-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Layers","title":"ggplot2 2.2.0","text":"geom_col() added complement geom_bar() (@hrbrmstr). uses stat=\"identity\" default, making y aesthetic mandatory. support stat_() provide fallback support binwidth parameter. Examples references functions updated demonstrate geom_col() usage. creating layer, ggplot2 warn use unknown aesthetic unknown parameter. Compared previous version, stricter aesthetics (previously message), less strict parameters (previously threw error) (#1585).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"facetting-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Facetting","title":"ggplot2 2.2.0","text":"facet system, well internal panel class, rewritten ggproto. Facets now extendable manner geoms stats, described vignette(\"extending-ggplot2\"). also added following new features. facet_grid() facet_wrap() now allow expressions faceting formulas (@DanRuderman, #1596). facet_wrap() results uneven number panels, axes now drawn underneath hanging panels (fixes #1607) Strips can now freely positioned facet_wrap() using strip.position argument (deprecates switch). relative order panel, strip, axis can now controlled theme setting strip.placement takes either inside (strip panel axis) outside (strip axis). theme option panel.margin deprecated favour panel.spacing clearly communicate intent.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensions-2-2-0","dir":"Changelog","previous_headings":"Major new features","what":"Extensions","title":"ggplot2 2.2.0","text":"Unfortunately major oversight construction ggproto lead extensions capturing super object package build time, instead package run time (#1826). problem fixed, requires re-installation extension packages.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"scales-2-2-0","dir":"Changelog","previous_headings":"","what":"Scales","title":"ggplot2 2.2.0","text":"position x y axes can now changed using position argument scale_x_*scale_y_* can take top bottom, left right respectively. themes top right axes can modified using .top .right modifiers axis.text.* axis.title.*.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"continuous-scales-2-2-0","dir":"Changelog","previous_headings":"Scales","what":"Continuous scales","title":"ggplot2 2.2.0","text":"scale_x_continuous() scale_y_continuous() can now display secondary axis one--one transformation primary axis (e.g. degrees Celcius degrees Fahrenheit). secondary axis positioned opposite primary axis can controlled sec.axis argument scale constructor. Scales worry less breaks. breaks can computed, plot work instead throwing uninformative error (#791). particularly helpful facets free scales, panels contain data. Scales now warn transformation introduces infinite values (#1696).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"date-time-2-2-0","dir":"Changelog","previous_headings":"Scales","what":"Date time","title":"ggplot2 2.2.0","text":"scale_*_datetime() now supports time zones. use timezone attached variable default, can overridden timezone argument. New scale_x_time() scale_y_time() generate reasonable default breaks labels hms vectors (#1752).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"discrete-scales-2-2-0","dir":"Changelog","previous_headings":"Scales","what":"Discrete scales","title":"ggplot2 2.2.0","text":"treatment missing values discrete scales thoroughly overhauled (#1584). underlying principle can naturally represent missing values discrete variables (treating just like another level), default . principle applies : character vectors factors implicit NA factors explicit NA scales (position non-position.) Compared previous version ggplot2, three main changes: scale_x_discrete() scale_y_discrete() always show discrete NA, regardless source present, NAs shown discrete legends. discrete scales gain na.translate argument allows control whether NAs translated something can visualised, left missing. Note don’t translate (.e.  na.translate = FALSE) missing values passed layer, warning ’s dropping missing values. suppress warnings, ’ll also need add na.rm = TRUE layer call. also number smaller changes Correctly use scale expansion factors. Don’t preserve space dropped levels (#1638). issue one warning asking many levels (#1674). Unicode labels work better Windows (#1827). Warn used continuous data (#1589)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"themes-2-2-0","dir":"Changelog","previous_headings":"","what":"Themes","title":"ggplot2 2.2.0","text":"theme() constructor now named arguments rather ellipses. make autocomplete substantially useful. documentation (including examples) considerably improved. Built-themes visually homogeneous, match theme_grey better. (@jiho, #1679) computing height titles, ggplot2 now includes height descenders (.e. bits g y hang beneath baseline). improves margins around titles, particularly y axis label (#1712). also slightly increased inner margins axis titles, removed outer margins. Theme element inheritance now easier work modification now overrides default element_blank elements (#1555, #1557, #1565, #1567) Horizontal legends (.e. legends top bottom) horizontally aligned default (#1842). Use legend.box = \"vertical\" switch back previous behaviour. element_line() now takes arrow argument specify arrows end lines (#1740) number tweaks theme elements control legends: legend.justification now controls appearance plotting legend outside plot area. example, can use theme(legend.justification = \"top\") make legend align top plot. panel.margin legend.margin renamed panel.spacing legend.spacing respectively, better communicate intent (affect spacing legends panels, margins around ) legend.margin now controls margin around individual legends. New legend.box.background, legend.box.spacing, legend.box.margin control background, spacing, margin legend box (region contains legends).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-and-minor-improvements-2-2-0","dir":"Changelog","previous_headings":"","what":"Bug fixes and minor improvements","title":"ggplot2 2.2.0","text":"ggplot2 now imports tibble. ensures built-datasets print compactly even haven’t explicitly loaded tibble dplyr (#1677). Class aesthetic mapping preserved adding aes() objects (#1624). +.gg now works lists include data frames. annotation_x() now works absense global data (#1655) geom_*(show.legend = FALSE) now works guide_colorbar. geom_boxplot() gains new outlier.alpha (@jonathan-g) outlier.fill (@schloerke, #1787) parameters control alpha/fill outlier points independently alpha boxes. position_jitter() (hence geom_jitter()) now correctly computes jitter width/jitter supplied user (#1775, @has2k1). geom_contour() clearly describes inputs needs (#1577). geom_curve() respects lineend parameter (#1852). geom_histogram() stat_bin() understand breaks parameter . (#1665). floating point adjustment histogram bins now actually used - previously inadvertently ignored (#1651). geom_violin() longer transforms quantile lines alpha aesthetic (@mnbram, #1714). longer errors quantiles requested data zero range (#1687). trim = FALSE nice range allows density reach zero (extending range 3 bandwidths either side data) (#1700). geom_dotplot() works better faceting binning y-axis. (#1618, @has2k1). geom_hexbin() supports ..density.. (@mikebirdgeneau, #1688). geom_step() gives useful warning one data point layer (#1645). layer() gains new check.aes check.param arguments. allow geom/stat authors optional suppress checks known aesthetics/parameters. Currently used geom_blank() powers expand_limits() (#1795). stat_*() display better error message required aesthetics missing. stat_bin() stat_summary_hex() now accept length 1 binwidth (#1610) stat_density() gains new argument n, passed underlying function stats::density (“number equally spaced points density estimated”). (@hbuschme) stat_binhex() now returns count rather value (#1747) stat_ecdf() respects pad argument (#1646). stat_smooth() informs method chosen. also correctly calculates size largest group within facets. x y scales now symmetric regarding list aesthetics accept: xmin_final, xmax_final, xlower, xmiddle xupper now valid x aesthetics. Scale extensions can now override make_title make_sec_title methods let scale modify axis/legend titles. random stream now reset calling .onAttach() (#2409).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-210","dir":"Changelog","previous_headings":"","what":"ggplot2 2.1.0","title":"ggplot2 2.1.0","text":"CRAN release: 2016-03-01","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-features-2-1-0","dir":"Changelog","previous_headings":"","what":"New features","title":"ggplot2 2.1.0","text":"mapping aesthetic constant (e.g.  geom_smooth(aes(colour = \"loess\")))), default guide title name aesthetic (.e. “colour”), value (.e. “loess”) (#1431). layer() now accepts function data argument. function applied data passed ggplot() function must return data.frame (#1527, @thomasp85). general version deprecated subset argument. theme_update() now uses + operator instead %+replace%, unspecified values longer NULLed . theme_replace() preserves old behaviour desired (@oneillkza, #1519). stat_bin() overhauled use algorithm ggvis, considerably improved thanks advice Randy Prium (@rpruim). includes: Better arguments better algorithm determining origin. can now specify either boundary center bin. origin deprecated favour arguments. drop deprecated favour pad, adds extra 0-count bins either end (needed frequency polygons). geom_histogram() defaults pad = FALSE considerably improves default limits histogram, especially bins big (#1477). default algorithm (somewhat) better job picking nice widths origins across wider range input data. bins = n now gives histogram n bins, n + 1 (#1487).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-2-1-0","dir":"Changelog","previous_headings":"","what":"Bug fixes","title":"ggplot2 2.1.0","text":"\\donttest{} examples run. geom_() stat_() functions now consistent argument order: data + mapping, geom/stat/position, ..., specific arguments, arguments common layers (#1305). may break code previously relying partial name matching, long-term make ggplot2 easier use. particular, can now set n parameter geom_density2d() without partially matching na.rm (#1485). geoms colour fill, alpha affects fill (Reverts #1371, #1523). causing problems people. facet_wrap()/facet_grid() works multiple empty panels data (#1445). facet_wrap() correctly swaps nrow ncol faceting vertically (#1417). ggsave(\"x.svg\") now uses svglite produce svg (#1432). geom_boxplot() now understands outlier.color (#1455). geom_path() knows “solid” (just 1) represents solid line (#1534). geom_ribbon() preserves missing values correctly generate gap ribbon (#1549). geom_tile() accepts width height parameters (#1513). uses draw_key_polygon() better legend, including coloured outline (#1484). layer() now automatically adds na.rm parameter none explicitly supplied. position_jitterdodge() now works possible dodge aesthetics, e.g. color, linetype etc. instead based fill (@bleutner) position = \"nudge\" now works (although doesn’t anything useful) (#1428). default scale columns class “AsIs” now “identity” (#1518). scale_*_discrete() better defaults used purely continuous data (#1542). scale_size() warns used categorical data. scale_size(), scale_colour(), scale_fill() gain date date-time variants (#1526). stat_bin_hex() stat_bin_summary() now use underlying algorithm results consistent (#1383). stat_bin_hex() now accepts weight aesthetic. consistent related stats, output variable stat_bin_hex() now value instead count. stat_density() gains bw parameter makes easy get consistent smoothing facets (@jiho) stat-density-2d() longer ignores h parameter, now accepts bins binwidth parameters control number contours (#1448, @has2k1). stat_ecdf() better job adding padding -Inf/Inf, gains argument pad suppress padding needed (#1467). stat_function() gains xlim parameter (#1528). works discrete x values (#1509). stat_summary() preserves sorted x order avoids artefacts display results geom_smooth() (#1520). elements now inherit correctly themes except theme_void(). (@Katiedaisey, #1555) theme_void() completely void text facets legends still need labels. now visible (@jiho). can set legend key height width unit arithmetic objects (like 2 * unit(1, \"cm\")) (#1437). Eliminate spurious warning layer data aesthetics (#1451). Removed superfluous comma theme-defaults.r code (@jschoeley) Fixed compatibility issue ggproto R versions prior 3.1.2. (#1444) Fixed issue coord_map() fails given explicit parameters argument (@tdmcarthur, #1729) Fixed issue geom_errorbarh() required x aesthetic (#1933)","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"ggplot2-200","dir":"Changelog","previous_headings":"","what":"ggplot2 2.0.0","title":"ggplot2 2.0.0","text":"CRAN release: 2015-12-18","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"major-changes-2-0-0","dir":"Changelog","previous_headings":"","what":"Major changes","title":"ggplot2 2.0.0","text":"ggplot longer throws error plot layers. Instead automatically adds geom_blank() (#1246). New cut_width() convenient replacement verbose plyr::round_any(), additional benefit offering finer control. New geom_count() convenient alias stat_sum(). Use overlapping points scatterplot. stat_sum() now defaults using counts instead proportions. New geom_curve() adds curved lines, similar specification geom_segment() (@veraanadi, #1088). Date datetime scales now date_breaks, date_minor_breaks date_labels arguments never need use long scales::date_breaks() scales::date_format(). geom_bar() now ’s stat, distinct stat_bin() also used geom_histogram(). geom_bar() now uses stat_count() counts values distinct value x (.e. bin data first). can useful want show exactly values used continuous variable. geom_point() gains stroke aesthetic controls border width shapes 21-25 (#1133, @SeySayux). size stroke additive point size = 5 stroke = 5 diameter 10mm. (#1142) New position_nudge() allows slightly offset labels (geoms) corresponding points (#1109). scale_size() now maps values area, radius. Use scale_radius() want old behaviour (recommended, except perhaps lines). New stat_summary_bin() works like stat_summary() binned data. ’s generalisation stat_bin() can compute aggregate, just counts (#1274). default mean_se() aggregation functions supplied (#1386). Layers now much stricter arguments - get error ’ve supplied argument isn’t aesthetic parameter. likely cause short-term pain long-term make much easier spot spelling mistakes errors (#1293). change break handful geoms/stats used ... pass additional arguments underlying computation. Now geom_smooth()/stat_smooth() geom_quantile()/stat_quantile() use method.args instead (#1245, #1289); stat_summary() (#1242), stat_summary_hex(), stat_summary2d() use fun.args.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"extensibility-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Extensibility","title":"ggplot2 2.0.0","text":"now official mechanism defining Stats, Geoms, Positions packages. See vignette(\"extending-ggplot2\") details. Geoms, Stats Positions now exported, can inherit making objects (#989). ggplot2 longer uses proto reference classes. Instead, now use ggproto, new OO system designed specifically ggplot2. Unlike proto RC, ggproto supports clean cross-package inheritance. Creating new OO system isn’t usually right way solve problem, ’m pretty sure necessary . Read vignette. aes_() replaces aes_q(). also supports formulas, concise SE version aes(carat, price) now aes_(~carat, ~price). may want use form packages, avoid spurious R CMD check warnings undefined global variables.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"text-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Text","title":"ggplot2 2.0.0","text":"geom_text() overhauled make labelling data little easier. : nudge_x nudge_y arguments let offset labels corresponding points (#1120). check_overlap = TRUE provides simple way avoid overplotting labels: labels otherwise overlap omitted (#1039). hjust vjust can now character vectors: “left”, “center”, “right”, “bottom”, “middle”, “top”. New options include “inward” “outward” align text towards away center plot respectively. geom_label() works like geom_text() draws rounded rectangle underneath label (#1039). useful want label plots dense data.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"deprecated-features-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Deprecated features","title":"ggplot2 2.0.0","text":"little used aes_auto() deprecated. aes_q() replaced aes_() consistent SE versions NSE functions packages. order aesthetic officially deprecated. never really worked, poorly documented. stat position arguments qplot() deprecated. qplot() designed quick plots - need specify position stat, use ggplot() instead. theme setting axis.ticks.margin deprecated: now use margin property axis.text. stat_abline(), stat_hline() stat_vline() removed: never suitable use geom_abline() etc documented. show_guide renamed show.legend: accurately reflects (controls appearance layer legend), uses convention ggplot2 arguments (.e. . names). (Yes, know ’s inconsistent function names use _, ’s late change now.) number geoms renamed internally consistent: stat_binhex() stat_bin2d() renamed stat_bin_hex() stat_bin_2d() (#1274). stat_summary2d() renamed stat_summary_2d(), geom_density2d()/stat_density2d() renamed geom_density_2d()/stat_density_2d(). stat_spoke() now geom_spoke() since realised ’s reparameterisation geom_segment(). stat_bindot() removed ’s tightly coupled geom_dotplot(). happened use stat_bindot(), just change geom_dotplot() (#1194). defunct functions removed.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"default-appearance-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Default appearance","title":"ggplot2 2.0.0","text":"default theme_grey() background colour changed “grey90” “grey92”: makes background little less visually prominent. Labels titles tweaked readability: Axes labels darker. Legend axis titles given visual treatment. default font size dropped 12 11. might surprised ’ve made default text size smaller already hard many people read. turns bug RStudio (fixed 0.99.724), shrunk text grid based graphics. resolved defaults seemed big eyes. spacing titles borders. Default margins scale theme font size, appearance larger font sizes considerably improved (#1228). alpha now affects fill colour aesthetics (#1371). element_text() gains margins argument allows add additional padding around text elements. help see ’s going use debug = TRUE display text region anchors. default font size geom_text() decreased 5mm (14 pts) 3.8 mm (11 pts) match new default theme sizes. diagonal line longer drawn bar rectangle legends. Instead, border tweaked visible, closely match size line drawn plot. geom_pointrange() geom_linerange() get vertical (horizontal) lines legend (#1389). default line size geom_smooth() increased 0.5 1 make easier see overlaid data. geom_bar() geom_rect() use slightly paler shade grey aren’t visually heavy. geom_boxplot() now colours outliers way boxes. geom_point() now uses shape 19 instead 16. looks much better default Linux graphics device. (’s slightly smaller old point, shouldn’t affect graphics significantly) Sizes ggplot2 measured mm. Previously converted pts (use grid) multiplying 72 / 25.4. However, grid uses printer’s points, Adobe (big pts), sizes now correctly multiplied 72.27 / 25.4. unlikely noticeably affect display, ’s technically correct (https://youtu./hou0lU8WMgo). default legend now allocate multiple rows (vertical) columns (horizontal) order make legend likely fit screen. can override nrow/ncol arguments guide_legend()","code":"p <- ggplot(mpg, aes(displ,hwy, colour = model)) + geom_point() p p + theme(legend.position = \"bottom\") # Previous behaviour p + guides(colour = guide_legend(ncol = 1))"},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"new-and-updated-themes-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"New and updated themes","title":"ggplot2 2.0.0","text":"New theme_void() completely empty. ’s useful plots non- standard coordinates drawings (@jiho, #976). New theme_dark() dark background designed make colours pop (@jiho, #1018) theme_minimal() became slightly minimal removing axis ticks: labels now line directly beneath grid lines (@tomschloss, #1084) New theme setting panel.ontop (logical) make possible place background elements (.e., gridlines) top data. Best used transparent panel.background (@noamross. #551).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"labelling-2-0-0","dir":"Changelog","previous_headings":"Major changes","what":"Labelling","title":"ggplot2 2.0.0","text":"facet labelling system updated many new features flexible interface (@lionel-). now works consistently across grid wrap facets. important user visible changes : facet_wrap() gains labeller option (#25). facet_grid() facet_wrap() gain switch argument display facet titles near axes. switched, labels become axes subtitles. switch can set “x”, “y” “” (latter grids) control margin switched. labellers (label_value() label_both()) also get new features: now offer multi_line argument control whether display composite facets (specified ~var1 + var2) one multiple lines. label_bquote() now refer directly names variables. change, can create math expressions depend one variable. math expression can specified either rows columns can also provide different expressions margin. consequence changes, referring x backquoted expressions deprecated. Similarly label_bquote(), labeller() now take .rows .cols arguments. addition, also takes .default. labeller() useful customise particular variables labelled. three additional arguments specify label variables specifically mentioned, respectively rows, columns . makes especially easy set project-wide labeller dispatcher can reused across plots. See documentation example. new labeller label_context() adapts number factors facetted . single factor, displays values, just . multiple factors composite margin (e.g. ~cyl + ), labels passed label_both(). way variables names displayed values help identifying . programming side, labeller API rewritten order offer control faceting multiple factors (e.g. formulae ~cyl + ). also means written custom labellers, need update version ggplot. Previously, labeller function take variable value arguments return character vector. Now, take data frame character vectors return list. input data frame one column per factor facetted column returned list becomes one line strip label. See documentation details. labels received labeller now contain metadata: margin (“type” attribute) whether come wrap grid facet (“facet” attribute). Note new as_labeller() function operator provides easy way transform existing function labeller function. existing function just needs take return character vector.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"documentation-2-0-0","dir":"Changelog","previous_headings":"","what":"Documentation","title":"ggplot2 2.0.0","text":"Improved documentation aes(), layer() much much . ’ve tried reduce use ... can see documentation one place rather integrate multiple pages. cases involved adding additional arguments geoms make clear can : geom_smooth() gains explicit method, se formula arguments. geom_histogram() gains binwidth, bins, origin right arguments. geom_jitter() gains width height arguments make easier control amount jittering without using lengthy position_jitter() function (#1116) Use qplot() examples minimised (#1123, @hrbrmstr). inline 2nd edition ggplot2 box, minimises use qplot() favour ggplot(). Tightly linked geoms stats (e.g. geom_boxplot() stat_boxplot()) now documented file can see arguments one place. Variations idea (e.g. geom_path(), geom_line(), geom_step()) also documented together. ’s now obvious can set binwidth parameter stat_bin_hex(), stat_summary_hex(), stat_bin_2d(), stat_summary_2d(). internals positions cleaned considerably. ’re unlikely notice external changes, although documentation little less confusing since positions now don’t list parameters never use.","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"data-2-0-0","dir":"Changelog","previous_headings":"","what":"Data","title":"ggplot2 2.0.0","text":"datasets class tbl_df also use dplyr, get better print method. economics brought date 2015-04-01. New economics_long economics data long form. New txhousing dataset containing information Texas housing market. Useful examples need multiple time series, demonstrating model+vis methods. New luv_colours dataset contains locations built-colors() Luv space. movies moved package, ggplot2movies, large terribly useful. ’ve used movies dataset, ’ll now need explicitly load package library(ggplot2movies).","code":""},{"path":"https://ggplot2.tidyverse.org/dev/news/index.html","id":"bug-fixes-and-minor-improvements-2-0-0","dir":"Changelog","previous_headings":"","what":"Bug fixes and minor improvements","title":"ggplot2 2.0.0","text":"partially matched arguments $ replaced full matches (@jimhester, #1134). ggplot2 now exports alpha() scales package (#1107), arrow() unit() grid (#1225). means don’t need attach scales/grid scales::/grid:: commonly used functions. aes_string() now parses character inputs. fixes bugs using numbers non default OutDec settings (#1045). annotation_custom() automatically adds unique id grob name, making easier plot multiple grobs name (e.g. grobs ggplot2 graphics) plot (#1256). borders() now accepts xlim ylim arguments specifying geographical region interest (@markpayneatwork, #1392). coord_cartesian() applies expansion factor limits scales. can suppress expand = FALSE (#1207). coord_trans() now works breaks suppressed (#1422). cut_number() gives error message number requested bins can created two unique values (#1046). Character labels facet_grid() longer (incorrectly) coerced factors. caused problems custom label functions (#1070). facet_wrap() facet_grid() now allow use non-standard variable names surrounding backticks (#1067). facet_wrap() carefully checks nrow ncol arguments ensure ’re specified correctly (@richierocks, #962) facet_wrap() gains dir argument control direction panels wrapped . default “h” horizontal. Use “v” vertical layout (#1260). geom_abline(), geom_hline() geom_vline() rewritten simpler behaviour consistent: stat_abline(), stat_hline() stat_vline() removed: never suitable use geom_abline() etc documented. geom_abline(), geom_vline() geom_hline() bound stat_identity() position_identity() Intercept parameters can longer set function. documented one file, since closely related. geom_bin2d() now let specify one dimension’s breaks exactly, without touching dimension’s default breaks (#1126). geom_crossbar() sets grouping correctly can display multiple crossbars one plot. also makes default fatten argument little bigger make middle line obvious (#1125). geom_histogram() geom_smooth() now inform default values per layer, rather per panel (#1220). geom_pointrange() gains fatten argument can control size point relative size line. geom_segment() annotations transforming scales (@BrianDiggs, #859). geom_smooth() longer chatty. want know default smoothing method , look documentation! (#1247) geom_violin() now ability draw quantile lines (@DanRuderman). ggplot() now captures parent frame use evaluation, rather always defaulting global environment. make ggplot suitable use situations (e.g. knitr) ggsave() simplified little make easier maintain. longer checks ’re printing ggplot2 object (now also works grid grob) (#970), always requires filename. Parameter device now supports character argument specify supported device use (‘pdf’, ‘png’, ‘jpeg’, etc.), correctly inferred file extension (example temporary filename supplied server side shiny apps) (@sebkopf, #939). longer opens graphics device one isn’t already open - annoying ’re running script (#1326). guide_colorbar() creates correct legend one color (@krlmlr, #943). guide_colorbar() longer fails legend empty - previously often masked misspecifications elsewhere plot (#967). New layer_data() function extracts data used plotting given layer. ’s mostly useful testing. User supplied minor_breaks can now supplied scale data, automatically transformed scale (#1385). can now suppress appearance axis/legend title (space allocated ) NULL scale_ function. use default label, use waiver() (#1145). Position adjustments longer warn potentially varying ranges problem rarely occurs practice currently lot false positives since don’t understand exactly FP criteria testing. scale_fill_grey() now uses red missing values. matches scale_colour_grey() makes obvious missing values lie. Override na.value. scale_*_gradient2() defaults using Lab colour space. scale_*_gradientn() now allows colours colors (#1290) scale_y_continuous() now also transforms lower, middle upper aesthetics used geom_boxplot(): affects geom_boxplot(stat = \"identity\") (#1020). Legends longer inherit aesthetics inherit.aes FALSE (#1267). lims() makes easy set limits axis (#1138). labels = NULL now works guide_legend() guide_colorbar(). (#1175, #1183). override.aes now works American aesthetic spelling, e.g. color Scales longer round data points improve performance colour palettes. Instead scales package now uses much faster colour interpolation algorithm (#1022). scale_*_brewer() scale_*_distiller() add new direction argument scales::brewer_pal, making easier change order colours (@jiho, #1139). scale_x_date() now clips dates outside limits way scale_x_continuous() (#1090). stat_bin() gains bins arguments, denotes number bins. Now can set bins=100 instead binwidth=0.5. Note breaks binwidth override (@tmshn, #1158, #102). stat_boxplot() warns continuous variable used x aesthetic without also supplying group aesthetic (#992, @krlmlr). stat_summary_2d() stat_bin_2d() now share exactly code determining breaks bins, binwidth, origin. stat_summary_2d() stat_bin_2d() now output tile/raster compatible form instead rect compatible form. Automatically computed breaks lead error transformations like “probit” inverse can map infinity (#871, @krlmlr) stat_function() now always evaluates function original scale. Previously computed function transformed scales, giving incorrect values (@BrianDiggs, #1011). strip_dots works anonymous functions within calculated aesthetics (e.g. aes(sapply(..density.., function(x) mean(x)))) (#1154, @NikNakk) theme() gains validate = FALSE parameter turn validation, hence store arbitrary additional data themes. (@tdhock, #1121) Improved calculation segments needed draw curve representing line plotted polar coordinates. cases, last segment multi-segment line drawn (@BrianDiggs, #952)","code":""}]