From 0d3757d6ccd994e4cf9ea75c3a48db7fbc1bac8f Mon Sep 17 00:00:00 2001 From: Hiroaki Yutani Date: Fri, 6 Sep 2024 16:43:08 +0900 Subject: [PATCH] Fix the YAML syntax of fig.alt chunk option (#6083) --- README.Rmd | 2 +- vignettes/articles/faq-annotation.Rmd | 24 +++++----- vignettes/articles/faq-axes.Rmd | 64 +++++++++++++------------- vignettes/articles/faq-bars.Rmd | 60 ++++++++++++------------ vignettes/articles/faq-customising.Rmd | 58 +++++++++++------------ vignettes/articles/faq-faceting.Rmd | 37 ++++++++------- vignettes/articles/faq-reordering.Rmd | 31 ++++++------- vignettes/extending-ggplot2.Rmd | 58 +++++++++++------------ vignettes/ggplot2-specs.Rmd | 42 ++++++++--------- vignettes/ggplot2.Rmd | 16 +++---- 10 files changed, 191 insertions(+), 201 deletions(-) diff --git a/README.Rmd b/README.Rmd index 693181ebae..337aa50b45 100644 --- a/README.Rmd +++ b/README.Rmd @@ -47,7 +47,7 @@ pak::pak("tidyverse/ggplot2") It's hard to succinctly describe how ggplot2 works because it embodies a deep philosophy of visualisation. However, in most cases you start with `ggplot()`, supply a dataset and aesthetic mapping (with `aes()`). You then add on layers (like `geom_point()` or `geom_histogram()`), scales (like `scale_colour_brewer()`), faceting specifications (like `facet_wrap()`) and coordinate systems (like `coord_flip()`). ```{r example} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars coloured by 7 'types' of car. The displacement and miles #| per gallon are inversely correlated." library(ggplot2) diff --git a/vignettes/articles/faq-annotation.Rmd b/vignettes/articles/faq-annotation.Rmd index a36ddfb670..b92e93e9e1 100644 --- a/vignettes/articles/faq-annotation.Rmd +++ b/vignettes/articles/faq-annotation.Rmd @@ -39,7 +39,7 @@ You should use `annotate(geom = "text")` instead of `geom_text()` for annotation In the following visualisation we have annotated a histogram with a red line and red text to mark the mean. Note that both the line and the text appears pixellated/fuzzy. ```{r} -#| fig.alt = "Histogram of highway miles per gallon for 234 cars. A red line is +#| fig.alt: "Histogram of highway miles per gallon for 234 cars. A red line is #| placed at the position 23.44 and is adorned with the label 'mean 23.44'. #| Both the line and the text appear pixellated due to overplotting." mean_hwy <- round(mean(mpg$hwy), 2) @@ -62,7 +62,7 @@ This is because `geom_text()` draws the geom once per each row of the data frame ```{r} -#| fig.alt = "Histogram of highway miles per gallon for 234 cars. A red line is +#| fig.alt: "Histogram of highway miles per gallon for 234 cars. A red line is #| placed at the position 23.44 and is adorned with the label 'mean = 23.44'. #| Both the line and the text appear crisp." ggplot(mpg, aes(x = hwy)) + @@ -91,7 +91,7 @@ Set `vjust = "inward"` and `hjust = "inward"` in `geom_text()`. Suppose you have the following data frame and visualization. The labels at the edges of the plot are cut off slightly. ```{r} -#| fig.alt = "A plot showing the words 'two', 'three' and 'four' arranged +#| fig.alt: "A plot showing the words 'two', 'three' and 'four' arranged #| diagonally. The 'two' and 'four' labels have been clipped to the panel's #| edge and are not displayed completely." df <- tibble::tribble( @@ -108,7 +108,7 @@ ggplot(df, aes(x = x, y = y, label = name)) + You could manually extend axis limits to avoid this, but a more straightforward approach is to set `vjust = "inward"` and `hjust = "inward"` in `geom_text()`. ```{r} -#| fig.alt = "A plot showing the words 'two', 'three' and 'four' arranged +#| fig.alt: "A plot showing the words 'two', 'three' and 'four' arranged #| diagonally. The 'two' and 'four' labels are aligned to the top-right and #| bottom-left relative to their anchor points, and are displayed in their #| entirety." @@ -129,7 +129,7 @@ Either calculate the counts ahead of time and place them on bars using `geom_tex Suppose you have the following bar plot and you want to add the number of cars that fall into each `drv` level on their respective bars. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train." ggplot(mpg, aes(x = drv)) + geom_bar() @@ -139,7 +139,7 @@ One option is to calculate the counts with `dplyr::count()` and then pass them t Note that we expanded the y axis limit to get the numbers to fit on the plot. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. The count values are displayed on top of the bars as text." mpg %>% dplyr::count(drv) %>% @@ -152,7 +152,7 @@ mpg %>% Another option is to let `ggplot()` do the counting for you, and access these counts with `after_stat(count)` that is mapped to the labels to be placed on the plot with `stat_count()`. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. The count values are displayed on top of the bars as text." ggplot(mpg, aes(x = drv)) + geom_bar() + @@ -173,7 +173,7 @@ First calculate the counts for each segment (e.g. with `dplyr::count()`) and the Suppose you have the following stacked bar plot. ```{r} -#| fig.alt = "A stacked bar chart showing the number of cars for each of seven +#| fig.alt: "A stacked bar chart showing the number of cars for each of seven #| types of cars. The fill colour of the bars indicate the type of drive #| train." ggplot(mpg, aes(x = class, fill = drv)) + @@ -190,7 +190,7 @@ mpg %>% You can then pass this result directly to `ggplot()`, draw the segments with appropriate heights with `y = n` in the `aes`thetic mapping and `geom_col()` to draw the bars, and finally place the counts on the plot with `geom_text()`. ```{r} -#| fig.alt = "A stacked bar chart showing the number of cars for each of seven +#| fig.alt: "A stacked bar chart showing the number of cars for each of seven #| types of cars. The fill colour of the bars indicate the type of drive #| train. In the middle of each filled part, the count value is displayed as #| text." @@ -214,7 +214,7 @@ Either calculate the proportions ahead of time and place them on bars using `geo Suppose you have the following bar plot but you want to display the proportion of cars that fall into each `drv` level, instead of the count. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train." ggplot(mpg, aes(x = drv)) + geom_bar() @@ -223,7 +223,7 @@ ggplot(mpg, aes(x = drv)) + One option is to calculate the proportions with `dplyr::count()` and then use `geom_col()` to draw the bars ```{r} -#| fig.alt = "A bar chart showing the proportion of cars for each of three types +#| fig.alt: "A bar chart showing the proportion of cars for each of three types #| of drive train." mpg %>% dplyr::count(drv) %>% @@ -236,7 +236,7 @@ Another option is to let `ggplot()` do the calculation of proportions for you, a Note that we also need to the `group = 1` mapping for this option. ```{r} -#| fig.alt = "A bar chart showing the proportion of cars for each of three types +#| fig.alt: "A bar chart showing the proportion of cars for each of three types #| of drive train." ggplot(mpg, aes(x = drv, y = ..prop.., group = 1)) + geom_bar() diff --git a/vignettes/articles/faq-axes.Rmd b/vignettes/articles/faq-axes.Rmd index f9868cdf8e..a6996dbe36 100644 --- a/vignettes/articles/faq-axes.Rmd +++ b/vignettes/articles/faq-axes.Rmd @@ -37,7 +37,7 @@ Set the angle of the text in the `axis.text.x` or `axis.text.y` components of th In the following plot the labels on the x-axis are overlapping. ```{r msleep-order-sleep-total} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. The horizontal labels on the #| x-axis for the orders overlap and are unreadable." ggplot(msleep, aes(x = order, y = sleep_total)) + @@ -47,7 +47,7 @@ ggplot(msleep, aes(x = order, y = sleep_total)) + - Rotate axis labels: We can do this by components of the `theme()`, specifically the `axis.text.x` component. Applying some vertical and horizontal justification to the labels centers them at the axis ticks. The `angle` can be set as desired within the 0 to 360 degree range, here we set it to 90 degrees. ```{r msleep-order-sleep-total-rotate} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. The x-axis labels are oriented #| vertically and are readable." ggplot(msleep, aes(x = order, y = sleep_total)) + @@ -58,7 +58,7 @@ ggplot(msleep, aes(x = order, y = sleep_total)) + - Flip the axes: Use the y-axis for long labels. ```{r msleep-order-sleep-total-flip} -#| fig.alt = "A boxplot showing the total amount of sleep on the x-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the x-axis for 19 #| taxonomical orders of mammals on the y-axis. The y-axis labels are oriented #| horizontally and are readable." ggplot(msleep, aes(y = order, x = sleep_total)) + @@ -68,7 +68,7 @@ ggplot(msleep, aes(y = order, x = sleep_total)) + - Dodge axis labels: Add a `scale_*()` layer, e.g. `scale_x_continuous()`, `scale_y_discrete()`, etc., and customise the `guide` argument with the `guide_axis()` function. In this case we want to customise the x-axis, and the variable on the x-axis is discrete, so we'll use `scale_x_continuous()`. In the `guide` argument we use the `guide_axis()` and specify how many rows to dodge the labels into with `n.dodge`. This is likely a trial-and-error exercise, depending on the lengths of your labels and the width of your plot. In this case we've settled on 3 rows to render the labels. ```{r msleep-order-sleep-total-dodge} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. The horizontal labels on the #| x-axis are dodged to three levels so that they remain readable." ggplot(msleep, aes(x = order, y = sleep_total)) + @@ -79,7 +79,7 @@ ggplot(msleep, aes(x = order, y = sleep_total)) + - Omit overlapping labels: Alternatively, you can set `guide_axis(check.overlap = TRUE)` to omit axis labels that overlap. ggplot2 will prioritize the first, last, and middle labels. Note that this option might be more preferable for axes representing variables that have an inherent ordering that is obvious to the audience of the plot, so that it's trivial to guess what the missing labels are. (This is not the case for the following plot.) ```{r msleep-order-sleep-total-check-overlap} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. Several of the x-axis labels #| have been omitted, but the one that remain are readable and don't overlap." ggplot(msleep, aes(x = order, y = sleep_total)) + @@ -100,7 +100,7 @@ Add a `theme()` layer and set relevant arguments, e.g. `axis.title.x`, `axis.tex Suppose we want to remove the axis labels entirely. ```{r ref.label="msleep-order-sleep-total"} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. The horizontal labels on the #| x-axis for the orders overlap and are unreadable." ``` @@ -108,7 +108,7 @@ Suppose we want to remove the axis labels entirely. - Remove x or y axis labels: If you want to modify just one of the axes, you can do so by modifying the components of the `theme()`, setting the elements you want to remove to `element_blank()`. You would replace `x` with `y` for applying the same update to the y-axis. Note the distinction between `axis.title` and `axis.ticks` -- `axis.title` is the name of the variable and `axis.text` is the text accompanying each of the ticks. ```{r} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. The annotation on the x-axis #| is abent." ggplot(msleep, aes(x = order, y = sleep_total)) + @@ -123,7 +123,7 @@ ggplot(msleep, aes(x = order, y = sleep_total)) + - Remove all axis labels: You can use `theme_void()` to remove all theming elements. Note that this might remove more features than you like. For finer control over the theme, see below. ```{r} -#| fig.alt = "A boxplot showing the total amount of sleep on the y-axis for 19 +#| fig.alt: "A boxplot showing the total amount of sleep on the y-axis for 19 #| taxonomical orders of mammals on the x-axis. The plot has no axes, #| gridlines or background panel." ggplot(msleep, aes(x = order, y = sleep_total)) + @@ -162,7 +162,7 @@ sales <- tribble( You can create a line plot of these data and facet by `year` to group the quarters for each year together. ```{r} -#| fig.alt = "A line plot with two panels showing value on the y-axis and four +#| fig.alt: "A line plot with two panels showing value on the y-axis and four #| quarters on the x-axis. The left panel is labelled '2020' and the right #| panel is labelled '2021'." ggplot(sales, aes(x = quarter, y = value, group = 1)) + @@ -175,7 +175,7 @@ However it might be preferable to plot all points in a single plot and indicate To achieve this, map the `interaction()` of `quarter` and `year` to the `x` aesthetic. ```{r} -#| fig.alt = "A line plot with one panel showing value on the y-axis and eight +#| fig.alt: "A line plot with one panel showing value on the y-axis and eight #| quarters on the x-axis. The years are appended after each quarter label." ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + geom_line() @@ -186,7 +186,7 @@ To clean this up (1) clip the plotting area with `coord_cartesian()`, (2) remove Note that the x-coordinates of the year labels are manually assigned here, but if you had many more years, you might write some logic to calculate their placement. ```{r} -#| fig.alt = "A line plot with one panel showing value on the y-axis and eight +#| fig.alt: "A line plot with one panel showing value on the y-axis and eight #| quarters on the x-axis. The years are shown in the middle of the first four #| and last four quarters. The line touches the panel on the left and right." ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + @@ -205,7 +205,7 @@ This approach works with other geoms as well. For example, you might can create a bar plot representing the same data using the following. ```{r} -#| fig.alt = "A bar chart with one panel showing value on the y-axis and eight +#| fig.alt: "A bar chart with one panel showing value on the y-axis and eight #| quarters on the x-axis. The years are shown in the middle of the first four #| and last four quarters. The outer bars touch the panel on the left and #| right." @@ -225,7 +225,7 @@ If it's undesirable to have the bars flush against the edges of the plot, a simi However note that the space between the bars for 2020 Q4 and 2021 Q1 is greater than the space between the other bars. ```{r} -#| fig.alt = "A bar chart showing value on the y-axis and eight +#| fig.alt: "A bar chart showing value on the y-axis and eight #| quarters on the x-axis. The chart appears as a single panel. The years are #| shown in the middle of the first four and last four quarters. The outer bars #| do not touch the panel on the left and right." @@ -255,7 +255,7 @@ Add a `scale_*()` layer, e.g. `scale_x_continuous()`, `scale_y_discrete()`, etc. Suppose you want to give more informative labels for the type of drive train. ```{r} -#| fig.alt = "A horizontal bar chart showing the number of cars on the x-axis +#| fig.alt: "A horizontal bar chart showing the number of cars on the x-axis #| for each of three types of drive trains on the y-axis. The three drive trains #| are labelled from top-to-bottom as 'r', 'f' and '4'." ggplot(mpg, aes(y = drv)) + @@ -265,7 +265,7 @@ ggplot(mpg, aes(y = drv)) + - Use the `labels` argument in the appropriate `scale_*()` function. You can find a list of these functions [here](https://ggplot2.tidyverse.org/reference/index.html#section-scales). Type of drive train (`drv`) is a discrete variable on the y-axis, so we'll adjust the labels in `scale_y_discrete()`. One option is to list the labels in the same order as the levels. Note that we start from the bottom and go up, just like we would if the variable was numeric/continuous. ```{r} -#| fig.alt = "A horizontal bar chart showing the number of cars on the x-axis +#| fig.alt: "A horizontal bar chart showing the number of cars on the x-axis #| for each of three types of drive trains on the y-axis. The three drive trains #| are labelled from top-to-bottom as 'Rear wheel drive', 'Front wheel drive' #| and 'Four wheel drive'." @@ -279,7 +279,7 @@ ggplot(mpg, aes(y = drv)) + - Another approach is to use a named list. This approach not only makes the relabelling more explicit, but it also means you don't need to worry about the order of the levels. ```{r} -#| fig.alt = "A horizontal bar chart showing the number of cars on the x-axis +#| fig.alt: "A horizontal bar chart showing the number of cars on the x-axis #| for each of three types of drive trains on the y-axis. The three drive trains #| are labelled from top-to-bottom as 'Rear wheel drive', 'Front wheel drive' #| and 'Four wheel drive'." @@ -308,7 +308,7 @@ You will first need to add a `scale_*()` layer (e.g. `scale_x_continuous()`, `sc By default, large numbers on the axis labels in the following plot are shown in scientific notation. ```{r} -#| fig.alt = "A scatter plot showing the median sale price of housing in Texas +#| fig.alt: "A scatter plot showing the median sale price of housing in Texas #| on the x-axis and the total volume of sales on the y-axis. The labels of #| both axes are in scientific notation, for example: '1e+09'." ggplot(txhousing, aes(x = median, y = volume)) + @@ -319,7 +319,7 @@ The [**scales**](https://scales.r-lib.org/) package offers a large number of fun Use `scales::label_number()` to force decimal display of numbers rather than using scientific notation or use `scales::label_comma()` to insert a comma every three digits. ```{r} -#| fig.alt = "A scatter plot showing the median sale price of housing in Texas +#| fig.alt: "A scatter plot showing the median sale price of housing in Texas #| on the x-axis and the total volume of sales on the y-axis. The labels of #| the y-axis are written out in full, with commas marking groups of three #| zeroes. The x-axis labels are written out in full, with spaces marking @@ -345,7 +345,7 @@ You will first need to add a `scale_*()` layer (e.g. `scale_x_continuous()`, `sc Suppose you want to increase/decrease the number of decimal spaces shown in the axis text in the following plot. ```{r} -#| fig.alt = "A scatter plot showing the difference in longitude on the x-axis +#| fig.alt: "A scatter plot showing the difference in longitude on the x-axis #| and difference in latitude on the y-axis for seal movements. The x-axis #| labels have one digit after the decimal place. The y-axis labels have two #| digits after the decimal place." @@ -357,7 +357,7 @@ The [**scales**](https://scales.r-lib.org/) package offers a large number of fun Use `scales::label_number()` where the `accuracy` argument indicates the number to round to, e.g. 0.1 to show 1 decimal place, 0.0001 to show 4 decimal places, etc. ```{r} -#| fig.alt = "A scatter plot showing the difference in longitude on the x-axis +#| fig.alt: "A scatter plot showing the difference in longitude on the x-axis #| and difference in latitude on the y-axis for seal movements. The x-axis #| labels have one digit after the decimal place. The y-axis labels have four #| digits after the decimal place." @@ -383,7 +383,7 @@ You will first need to add a `scale_*()` layer (e.g. `scale_x_continuous()`, `sc The variable on the y-axis of the following line plot (`psavert`) indicates the personal savings rate, which is in percentages. ```{r} -#| fig.alt = "A lineplot showing the personal savings rate over time from 1967 +#| fig.alt: "A lineplot showing the personal savings rate over time from 1967 #| to 2015." ggplot(economics, aes(x = date, y = psavert, group = 1)) + geom_line() @@ -392,7 +392,7 @@ ggplot(economics, aes(x = date, y = psavert, group = 1)) + With `scales::label_percent()` you can add `%`s after the numbers shown on the axis to make the units more clear. ```{r} -#| fig.alt = "A lineplot showing the personal savings rate over time from 1967 +#| fig.alt: "A lineplot showing the personal savings rate over time from 1967 #| to 2015. The y-axis labels are appended by percentage signs." ggplot(economics, aes(x = date, y = psavert, group = 1)) + geom_line() + @@ -414,7 +414,7 @@ You can either use `bquote()` to parse mathematical expressions or use the [**gg In the following plot `cty` is squared and `hwy` is log transformed. ```{r} -#| fig.alt = "A scatter plot showing the squared city miles per gallon on the +#| fig.alt: "A scatter plot showing the squared city miles per gallon on the #| x-axis versus the logarithm of highway miles per gallon on the y-axis for #| 234 cars." ggplot(mpg, aes(x = cty^2, y = log(hwy))) + @@ -424,7 +424,7 @@ ggplot(mpg, aes(x = cty^2, y = log(hwy))) + - Use `bquote()` function to parse mathematical expressions. ```{r} -#| fig.alt = "A scatter plot showing the squared city miles per gallon on the +#| fig.alt: "A scatter plot showing the squared city miles per gallon on the #| x-axis versus the base 10 logarithm of highway miles per gallon on the #| y-axis for 234 cars. In the axis titles, the base 10 is indicated in #| subscript on the y-axis and the power 2 is indicated in superscript on @@ -440,7 +440,7 @@ ggplot(mpg, aes(x = cty^2, y = log(hwy, base = 10))) + - If you're already familiar with Markdown and HTML, you might prefer using the [ggtext](https://wilkelab.org/ggtext/) package instead. In Markdown we can write the axis labels as `cty2` and `log10(hwy)` for x and y axes, respectively. Then, we tell ggplot2 to interpret the axis labels as Markdown and not as plain text by setting `axis.title.x` and `axis.title.y` to `ggtext::element_markdown()`. ```{r} -#| fig.alt = "A scatter plot showing the squared city miles per gallon on the +#| fig.alt: "A scatter plot showing the squared city miles per gallon on the #| x-axis versus the base 10 logarithm of highway miles per gallon on the #| y-axis for 234 cars. In the axis titles, the base 10 is indicated in #| subscript on the y-axis and the power 2 is indicated in superscript on @@ -472,7 +472,7 @@ Customise the `breaks` and `minor_breaks` in `scale_x_continuous()`, `scale_y_co Suppose you want to customise the major and minor grid lines on both the x and the y axes of the following plot. ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis versus +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis versus #| the highway miles per gallon on the y-axis for 234 cars. The distance #| between axis ticks is constant within each axis." ggplot(mpg, aes(x = cty, y = hwy)) + @@ -483,7 +483,7 @@ You can set `breaks` and `minor_breaks` in `scale_x_continuous()` and `scale_y_c For example, on the x-axis we have major and minor grid breaks defined as a sequence and on the y-axis we have explicitly stated where major breaks should appear as a vector (the value stated are randomly selected for illustrative purposes only, they don't follow a best practice) and we have completely turned off minor grid lines by setting `minor_breaks` to `NULL`. ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis versus +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis versus #| the highway miles per gallon on the y-axis for 234 cars. The distance #| between axis ticks varies within the y-axis. There are no minor horizontal #| grid lines, and there are three minor vertical gridlines between major @@ -528,7 +528,7 @@ Remove the padding around the data entirely using by setting `expand = c(0, 0)` - Remove all padding: Suppose you want to remove the padding around the heat map so it's flush against the axes. ```{r} -#| fig.alt = "A heatmap showing a 2D density estimate of the waiting and +#| fig.alt: "A heatmap showing a 2D density estimate of the waiting and #| eruption times of the Old Faithful geyser. The heatmap does not touch the #| panel edges." ggplot(faithfuld, aes(waiting, eruptions)) + @@ -538,7 +538,7 @@ ggplot(faithfuld, aes(waiting, eruptions)) + Since both x and y variables are continuous, we set `expand = c(0, 0)` in both `scale_x_continuous()` and `scale_y_continuous()`. ```{r} -#| fig.alt = "A heatmap showing a 2D density estimate of the waiting and +#| fig.alt: "A heatmap showing a 2D density estimate of the waiting and #| eruption times of the Old Faithful geyser. The heatmap touches the panel #| edges." ggplot(faithfuld, aes(waiting, eruptions)) + @@ -550,7 +550,7 @@ ggplot(faithfuld, aes(waiting, eruptions)) + - Remove some of the padding: Suppose you want to remove the padding below the bars and the x-axis only. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. No parts of the bars touch the panel edges." ggplot(mpg, aes(drv)) + geom_bar() @@ -559,7 +559,7 @@ ggplot(mpg, aes(drv)) + You would make this adjustment on `scale_y_continuous()` since that padding is in the vertical direction. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. All bars touch the bottom of the panel, and the highest bar #| touches the top of the panel." ggplot(mpg, aes(drv)) + @@ -574,7 +574,7 @@ The `mult` argument in `expansion()` takes a multiplicative range expansion fact Given a vector of length 2, the lower limit is expanded by `mult[1]` (in this case 0) and the upper limit is expanded by `mult[2]` (in this case 0.05). ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. All bars touch the bottom of the panel, and no bar touches #| the top of the panel." ggplot(mpg, aes(drv)) + diff --git a/vignettes/articles/faq-bars.Rmd b/vignettes/articles/faq-bars.Rmd index 345ff68c1b..3cbacf4d79 100644 --- a/vignettes/articles/faq-bars.Rmd +++ b/vignettes/articles/faq-bars.Rmd @@ -42,7 +42,7 @@ If assigning color based on another variable, map the variable to the `fill` `ae You can set all bars to be a given color with the `fill` argument of `geom_bar()`. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. All bars are blue." ggplot(mpg, aes(x = drv)) + geom_bar(fill = "blue") @@ -51,7 +51,7 @@ ggplot(mpg, aes(x = drv)) + Alternatively, if the colors should be based on a variable, this should be should happen in the `aes()` mapping. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. From left-to-right, the bars appear red, green and blue." ggplot(mpg, aes(x = drv, fill = drv)) + geom_bar() @@ -61,7 +61,7 @@ And if you want to then customize the colors, one option is `scale_fill_manual() See other `scale_fill_*()` functions for more options for color choices. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. From left-to-right, the bars are purple, orange and dark #| blue." ggplot(mpg, aes(x = drv, fill = drv)) + @@ -85,12 +85,11 @@ By default, the `width` of bars is `0.9` (90% of the resolution of the data). You can set this argument to a lower value to get bars that are narrower with more space between them. ```{r} -#| fig.alt = c( -#| "A bar chart showing the number of cars for each of three types -#| of drive train. The bars are somewhat narrower than the default.", -#| "A bar chart showing the number of cars for each of three types +#| fig.alt: +#| - "A bar chart showing the number of cars for each of three types +#| of drive train. The bars are somewhat narrower than the default." +#| - "A bar chart showing the number of cars for each of three types #| of drive train. The bars are very narrow." -#| ) ggplot(mpg, aes(x = drv)) + geom_bar(width = 0.5) @@ -111,7 +110,7 @@ Adjust the `expand` argument in `scale_y_continuous()`, e.g. add `scale_y_contin By default ggplot2 expands the axes so the geoms aren't flush against the edges of the plot. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. No parts of the bars touch the panel edges." ggplot(mpg, aes(x = drv)) + geom_bar() @@ -120,7 +119,7 @@ ggplot(mpg, aes(x = drv)) + To remove the spacing between the bars and the x-axis, but keep the spacing between the bars and the top of the plot, use the following. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. The bottom of the bars touch the x-axis." ggplot(mpg, aes(x = drv)) + geom_bar() + @@ -131,7 +130,7 @@ To achieve the opposite, switch the values in `mult`. Note that the tallest bar is now flush against top of the plot. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. The top of the highest bar touches the top of the panel." ggplot(mpg, aes(x = drv)) + geom_bar() + @@ -142,7 +141,7 @@ To adjust spacing around the x-axis, adjust the `expand` argument in `scale_x_di Note that this places the bars flush against the left side and leaves some space on the right side. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. The left of the leftmost bar touches the y-axis." ggplot(mpg, aes(x = drv)) + geom_bar() + @@ -152,7 +151,7 @@ ggplot(mpg, aes(x = drv)) + The default look of a bar plot can be achieved with the following. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. No parts of the bars touch the panel edges." ggplot(mpg, aes(x = drv)) + geom_bar() + @@ -173,7 +172,7 @@ Set `position = position_dodge2(preserve = "single")` in `geom_bar()`. In the following plot the bars have differing widths within each level of `drv` as there are differing levels of `class` represented. ```{r} -#| fig.alt = "A grouped bar chart showing car counts dodged and filled by 7 +#| fig.alt: "A grouped bar chart showing car counts dodged and filled by 7 #| types of cars for each of three types of drive train. The left group has #| 5 narrower bars, the middle group has 4 bars and the right group has 3 wider #| bars." @@ -184,7 +183,7 @@ ggplot(mpg, aes(x = drv, fill = class)) + You can use `position_dodge2()` with `preserve = "single"` to address this. ```{r} -#| fig.alt = "A grouped bar chart showing car counts dodged and filled by 7 +#| fig.alt: "A grouped bar chart showing car counts dodged and filled by 7 #| types of cars for each of three types of drive train. From left-to-right, #| each groups has respectively 5, 4 and 3 equally wide bars." ggplot(mpg, aes(x = drv, fill = class)) + @@ -207,7 +206,7 @@ If you also want to show percentages on the axis, use `scales::label_percent()`. The following plot is useful for comparing counts but not as useful for comparing proportions, which is what you need if you want to be able to make statements like "in this sample, it's more likely to have a two-seater car that has rear-wheel drive than an SUV that has rear-wheel drive". ```{r} -#| fig.alt = "A horizontal stacked bar chart showing car counts for 7 types of +#| fig.alt: "A horizontal stacked bar chart showing car counts for 7 types of #| cars, stacked and filled by 3 types of drive train." ggplot(mpg, aes(y = class, fill = drv)) + geom_bar() @@ -216,7 +215,7 @@ ggplot(mpg, aes(y = class, fill = drv)) + `position = "fill"` will generate a bar plot with bars of equal length and the stacks in each bar will show the proportion of `drv` for that particular `class`. ```{r} -#| fig.alt = "A horizontal filled bar chart showing proportions of cars for 7 +#| fig.alt: "A horizontal filled bar chart showing proportions of cars for 7 #| types of cars. The fill colour represents 3 types of drive train. Every #| stacked bar spans the width of the panel." ggplot(mpg, aes(y = class, fill = drv)) + @@ -226,7 +225,7 @@ ggplot(mpg, aes(y = class, fill = drv)) + If you want to show percentages instead of proportions on the x-axis, you can define this in `scale_x_continuous()` with `scales::label_percent()`. ```{r} -#| fig.alt = "A horizontal filled bar chart showing percentages of cars for 7 +#| fig.alt: "A horizontal filled bar chart showing percentages of cars for 7 #| types of cars. The fill colour represents 3 types of drive train. Every #| stacked bar spans the width of the panel." ggplot(mpg, aes(y = class, fill = drv)) + @@ -271,7 +270,7 @@ poll_longer Then, you can pass this result to `ggplot()` and create a bar for each `party` on the `y` (or `x`, if you prefer vertical bars) axis and fill the bars in with number of responses for each `opinion`. ```{r} -#| fig.alt = "A horizontal stacked bar chart showing opinion counts for 3 +#| fig.alt: "A horizontal stacked bar chart showing opinion counts for 3 #| parties, stacked and filled by 3 types of opinions." ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + geom_col() @@ -280,7 +279,7 @@ ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + To plot proportions (relative frequencies) instead of counts, use `position = "fill"` in `geom_col()`. ```{r} -#| fig.alt = "A horizontal filled bar chart showing proportions of opinions for +#| fig.alt: "A horizontal filled bar chart showing proportions of opinions for #| 3 parties. The fill colour represents 3 types of opinion. Every #| stacked bar spans the width of the panel." ggplot(poll_longer, aes(y = party, fill = opinion, x = n)) + @@ -315,7 +314,7 @@ You can do this with `tidyr::pivot_longer()`. Then, pass the resulting longer data frame to `ggplot()` group responses for each question together. ```{r} -#| fig.alt = "A grouped bar chart showing the number of responses to three +#| fig.alt: "A grouped bar chart showing the number of responses to three #| questions. Within each question, two bars denote an 'Agree' or 'Disagree' #| response." survey %>% @@ -342,7 +341,7 @@ One option for calculating group means is using `dplyr::group_by()` followed by Then, you can pass the resulting data frame to `ggplot()` and plot bars using `geom_col()`. ```{r} -#| fig.alt = "A bar chart showing the average highway miles per gallon for +#| fig.alt: "A bar chart showing the average highway miles per gallon for #| three types of drive train." mpg %>% group_by(drv) %>% @@ -354,7 +353,7 @@ mpg %>% Alternatively, you can use `stat_summary()` to let ggplot2 calculate and plot the means. ```{r} -#| fig.alt = "A bar chart showing the average highway miles per gallon for +#| fig.alt: "A bar chart showing the average highway miles per gallon for #| three types of drive train." ggplot(mpg, aes(x = drv, y = hwy)) + stat_summary(fun = "mean", geom = "bar") @@ -379,7 +378,7 @@ Also note that this will result in a deceiving bar plot, which should be avoided In the following plot the y-axis is limited to 20 to 120, and hence the bars are not showing up. ```{r} -#| fig.alt = "A plot with axes and a panel, but no other geometry." +#| fig.alt: "A plot with axes and a panel, but no other geometry." ggplot(mpg, aes(x = drv)) + geom_bar() + ylim(c(20, 120)) @@ -388,7 +387,7 @@ ggplot(mpg, aes(x = drv)) + In order to obtain a bar plot with limited y-axis, you need to instead set the limits in `coord_cartesian()`. ```{r} -#| fig.alt = "A bar chart showing the number of cars for each of three types +#| fig.alt: "A bar chart showing the number of cars for each of three types #| of drive train. The y-axis starts at 20, and all bars touch the x-axis." ggplot(mpg, aes(x = drv)) + geom_bar() + @@ -400,7 +399,7 @@ If you're using a bar plot to display values that could not take the value of 0, For example, if you have the following data and plot. ```{r} -#| fig.alt = "A bar chart showing numbers for 3 arbitrary categories. The +#| fig.alt: "A bar chart showing numbers for 3 arbitrary categories. The #| numbers are far away from the x-axis and visually appear broadly similar #| in height." df <- tibble::tribble( @@ -417,14 +416,13 @@ ggplot(df, aes(x = x, y = y)) + Also suppose that you want to cut off the bars at `y = 1000` since you know that the variable you're plotting cannot take a value less than 1000, you might use `geom_point()` instead. ```{r} -#| fig.alt = c( -#| "A bar chart showing numbers for 3 arbitrary categories. The y-axis starts +#| fig.alt: +#| - "A bar chart showing numbers for 3 arbitrary categories. The y-axis starts #| at 1000 and the bars all look different in height. This is not a recommended -#| way of plotting this data.", -#| "A scatter plot with 3 points showing numbers for 3 arbitrary categories. +#| way of plotting this data." +#| - "A scatter plot with 3 points showing numbers for 3 arbitrary categories. #| The y-axis starts at 1000 and the points have visually different values. #| This is a better way of plotting this data." -#| ) # don't do this ggplot(df, aes(x = x, y = y)) + geom_col() + diff --git a/vignettes/articles/faq-customising.Rmd b/vignettes/articles/faq-customising.Rmd index 5c8ed1b44f..b61df09336 100644 --- a/vignettes/articles/faq-customising.Rmd +++ b/vignettes/articles/faq-customising.Rmd @@ -40,7 +40,7 @@ By default your legend label will be the name of the variable that is mapped to You can change the title of your legend using `labs()`. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by three #| types of drive train, which is displayed in a legend with the title 'Drive #| train'." @@ -52,16 +52,16 @@ ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + If a legend is drawn for multiple aesthetics, you'll want to update the title for all of them. ```{r} -#| fig.alt = c( -#| "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: +#| - "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The point shapes and colours #| indicate three types of drive train. The shapes and colours are displayed in -#| separate legends titled 'drv' and 'Drive train' respectively.", -#| "A scatter plot showing the highway miles per gallon on the x-axis +#| separate legends titled 'drv' and 'Drive train' respectively." +#| - "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The point shapes and colours #| indicate three types of drive train. The shapes and colours are displayed in #| a single legend titled 'Drive train'." -#| ) +#| # not this ggplot(mpg, aes(x = hwy, y = cty, color = drv, shape = drv)) + geom_point() + @@ -89,7 +89,7 @@ You can supply a unit object to this argument, e.g. `unit(1.0, "cm")` for 1 cm s See the documentation for `grid::unit()` for more options for units. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by three #| types of drive train, which is displayed in a legend at the bottom of the #| plot in a horizontal orientation. Legend elements are spaced widely apart." @@ -104,7 +104,7 @@ ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + For vertical legends changing `legend.spacing.y` changes the space between the legend title and the keys, but not between the keys, e.g. see the large space between the legend title and keys. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by three #| types of drive train, which is displayed in a legend at the right of the #| plot. In the legend, there is a large space between the title and keys." @@ -116,7 +116,7 @@ ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + In order to change the space between the legend keys, you can first make the key size bigger with `legend.key.size` and then remove the grey background color with `legend.key`. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by three #| types of drive train, which is displayed in a legend at the right of the #| plot. In the legend, elements are placed widely apart and the title is @@ -133,7 +133,7 @@ Note that the legend title is no longer aligned with the keys with this approach You can also shift it over with the `hjust` setting of `legend.title`. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by three #| types of drive train, which is displayed in a legend at the right of the #| plot. In the legend, elements are placed widely apart and the title is @@ -161,7 +161,7 @@ The `labels` argument of `scale_*` functions takes named vectors, which what we Using named lists allows you to declare explicitly which label is assigned to which level, without having to keep track of level order. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by three #| types of drive train, which is displayed in a legend at the right of the #| plot. The legend items are name '4-wheel drive', 'Front-wheel drive' and @@ -191,7 +191,7 @@ You can use the following for 14 pts text for legend key labels and 10 pts text (Note that this doesn't result in a visually pleasing legend, by default ggplot2 uses a larger font size for the legend title than the legend text.) ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by seven #| types of cars, which is displayed in the legend on the right of the plot. #| The labels in the legend have a larger font size than the title." @@ -206,7 +206,7 @@ ggplot(mpg, aes(x = hwy, y = cty, color = class)) + For further customization of legend text, see the documentation for `element_text()`, e.g. you can change font colors or font face as well. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by seven #| types of cars, which is displayed in the legend on the right of the plot. #| The labels in the legends have a large, red font. The title has a smaller, @@ -235,7 +235,7 @@ You can set the background colour of the plot with `panel.background` in `theme( In the following example the border is made thicker with `linewidth = 3` to ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The panel background of the plot #| is light blue and is outlined in red with a thick stroke." ggplot(mpg, aes(x = hwy, y = cty)) + @@ -246,7 +246,7 @@ ggplot(mpg, aes(x = hwy, y = cty)) + If you want to change the colour of the plotting area but not the panel where the panel, you can so the same thing with `plot.background`. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The plot background is light blue #| and is outlined in red with a thick stroke. The panel background remains #| grey." @@ -259,7 +259,7 @@ Note that ggplot2 has a variety of [complete themes](https://ggplot2.tidyverse.o For example, if you prefer a more minimal look to your plots, without the grey background, you might try `theme_minimal()`. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. There is no visible panel #| background and grid lines are in light grey." ggplot(mpg, aes(x = hwy, y = cty)) + @@ -270,7 +270,7 @@ ggplot(mpg, aes(x = hwy, y = cty)) + And you can continue customization based on one of these themes. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. There is no visible panel #| background and grid lines are in light grey. The plot as a whole is outlined #| by a thick red line." @@ -309,7 +309,7 @@ df <- tibble::tribble( By default, ggplot2 uses grey to represent `NA`s. ```{r} -#| fig.alt = "A stacked bar chart showing two groups on the x-axis and counts +#| fig.alt: "A stacked bar chart showing two groups on the x-axis and counts #| on the y-axis. Within a stacked bar, two different outcomes and 'NA's are #| distinguished by fill colour." ggplot(df, aes(x = group, fill = outcome)) + @@ -319,7 +319,7 @@ ggplot(df, aes(x = group, fill = outcome)) + You can change the color of `NA` with `scale_fill_discrete()` in this case, e.g. make it purple. ```{r} -#| fig.alt = "A stacked bar chart showing two groups on the x-axis and counts +#| fig.alt: "A stacked bar chart showing two groups on the x-axis and counts #| on the y-axis. Within a stacked bar, two different outcomes and 'NA's are #| distinguished by fill colour. The 'NA' fill colour is purple." ggplot(df, aes(x = group, fill = outcome)) + @@ -332,7 +332,7 @@ In the plot below this is shown with `theme_minimal()` to demonstrate how that l Note that while this is possible, setting the colour to transparent as such wouldn't be recommended in this particular case as it gives the appearance of a floating bar. ```{r} -#| fig.alt = "A stacked bar chart showing two groups on the x-axis and counts +#| fig.alt: "A stacked bar chart showing two groups on the x-axis and counts #| on the y-axis. Within a stacked bar, two different outcomes and 'NA's are #| distinguished by fill colour. The 'NA' fill colour is transparent, giving #| the appearance that one of the stacked bars is floating." @@ -359,7 +359,7 @@ You can change it with the `base_size` argument in the theme you're using. See the [complete theme documentation](https://ggplot2.tidyverse.org/reference/ggtheme.html) for more high level options you can set. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The points are coloured by seven #| types of car. All text sizes in the axes and legend are large." ggplot(mpg, aes(x = hwy, y = cty, color = class)) + @@ -389,7 +389,7 @@ Font characteristics of plot titles and subtitles can be controlled with the `pl You can use the following for 20 pts text for the plot title and 15 pts text for the plot subtitle. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The plot has a large title #| displaying 'This is the plot title' and a less large subtitle displaying #| 'And this is the subtitle' at the top of the plot." @@ -408,7 +408,7 @@ ggplot(mpg, aes(x = hwy, y = cty)) + For further customization of plot title and subtitle, see the documentation for `element_text()`, e.g. you can change font colors or font face as well. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The plot has a large red title #| displaying 'This is the plot title' and a less large subtitle in bold and #| italic displaying 'And this is the subtitle' at the top of the plot." @@ -439,7 +439,7 @@ In both cases, set font size in the `size` argument of `element_text()`, e.g. `a Font characteristics of axis labels can be controlled with `axis.title.x` or `axis.title.y` (or `axis.title` if you the same settings for both axes). ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The x-axis title displays #| 'This is HUGE' in a large font size, and the y-axis title displays #| 'This is small' in a smaller font size." @@ -458,7 +458,7 @@ ggplot(mpg, aes(x = hwy, y = cty)) + For further customization of plot title and subtitle, see the documentation for `element_text()`, e.g. you can change font colors or font face as well. ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. The x-axis title displays #| 'This is HUGE' in a large, red font, and the y-axis title displays #| 'This is tiny' in a smaller, bold and italic font." @@ -477,7 +477,7 @@ ggplot(mpg, aes(x = hwy, y = cty)) + You can also change the size of the axis text (e.g. numbers at the axis ticks) using `axis.text` (or `axis.text.x` and `axis.text.y` if you want to set different sizes). ```{r} -#| fig.alt = "A scatter plot showing the highway miles per gallon on the x-axis +#| fig.alt: "A scatter plot showing the highway miles per gallon on the x-axis #| and city miles per gallon on the y-axis. Both the x and the y axis titles #| display 'The axis labels are the same size' in a large font. Both axis #| labels are displayed in a larger, blue font." @@ -518,7 +518,7 @@ Please refer to ["Font size" section of the aesthetic specifications](https://gg Suppose you have the following data frame and visualization. ```{r} -#| fig.alt = "A plot showing text at diagonal positions with the labels 'two', +#| fig.alt: "A plot showing text at diagonal positions with the labels 'two', #| 'three' and 'four'." df <- tibble::tribble( ~x, ~y, ~name, @@ -534,7 +534,7 @@ ggplot(df, aes(x = x, y = y, label = name)) + You can set the size of the text with the following. ```{r} -#| fig.alt = "A plot showing larger text at diagonal positions with the labels +#| fig.alt: "A plot showing larger text at diagonal positions with the labels #| 'two', 'three' and 'four'." ggplot(df, aes(x = x, y = y, label = name)) + geom_text(size = 6) @@ -543,7 +543,7 @@ ggplot(df, aes(x = x, y = y, label = name)) + Or you can map it to the `size` `aes`thetic. In the following size is determined by the `x` value with `scale_size_identity()`. ```{r} -#| fig.alt = "A plot showing text at diagonal positions with the labels 'two', +#| fig.alt: "A plot showing text at diagonal positions with the labels 'two', #| 'three' and 'four' that increase in size from left to right." ggplot(df, aes(x = x, y = y, label = name)) + geom_text(aes(size = x)) + diff --git a/vignettes/articles/faq-faceting.Rmd b/vignettes/articles/faq-faceting.Rmd index 93ec538a9e..bb7112edbb 100644 --- a/vignettes/articles/faq-faceting.Rmd +++ b/vignettes/articles/faq-faceting.Rmd @@ -37,7 +37,7 @@ The simplest answer is that you should use `facet_wrap()` when faceting by a sin `facet_wrap()` is most commonly used to facet by a plot by a single categorical variable. ```{r} -#| fig.alt = "A histogram showing the city miles per gallon distribution for +#| fig.alt: "A histogram showing the city miles per gallon distribution for #| three types of drive train, each in their own panel in a 1-row, 3-column #| layout." ggplot(mpg, aes(x = cty)) + @@ -48,7 +48,7 @@ ggplot(mpg, aes(x = cty)) + And `facet_grid()` is commonly used to facet by a plot by two categorical variables. ```{r} -#| fig.alt = "A histogram showing the city miles per gallon distribution. The +#| fig.alt: "A histogram showing the city miles per gallon distribution. The #| plot has twelve panels in a 4-row, 3-column layout, showing three types of #| drive train in the horizontal direction, and four numbers of cylinders #| in the vertical direction. Several panels have no data." @@ -63,7 +63,7 @@ You can also use `facet_wrap()` with to facet by two categorical variables. This will only create facets for combinations of the levels of variables for which data exists. ```{r} -#| fig.alt = "A histogram showing the city miles per gallon distribution. The +#| fig.alt: "A histogram showing the city miles per gallon distribution. The #| plot has nine panels in a 3-row, 3-column layout, showing all existing #| combinations of three types of drive train, and four numbers of cylinders." ggplot(mpg, aes(x = cty)) + @@ -78,12 +78,11 @@ Similarly, you can also use `facet_grid()` to facet by a single categorical vari In the formula notation, you use a `.` to indicate that no faceting should be done along that axis, i.e. `cyl ~ .` facets across the y-axis (within a column) while `. ~ cyl` facets across the x-axis (within a row). ```{r out.width = "50%"} -#| fig.alt = c( -#| "A histogram showing the city miles per gallon distribution. The plot has -#| four panels in a 4-row, 1-column layout, showing four numbers of cylinders.", -#| "A histogram showing the city miles per gallon distribution. The plot has +#| fig.alt: +#| - "A histogram showing the city miles per gallon distribution. The plot has +#| four panels in a 4-row, 1-column layout, showing four numbers of cylinders." +#| - "A histogram showing the city miles per gallon distribution. The plot has #| four panels in a 1-row, 4-column layout, showing four numbers of cylinders." -#| ) ggplot(mpg, aes(x = cty)) + geom_histogram() + facet_grid(cyl ~ .) @@ -107,7 +106,7 @@ Then, add a `geom_vline()` layer to your plot that uses the summarized data. Suppose you have the following plot, and you want to add a vertical line at the mean value of `hwy` (highway mileage) for each pane. ```{r} -#| fig.alt = "A histogram showing the highway miles per gallon distribution for +#| fig.alt: "A histogram showing the highway miles per gallon distribution for #| three types of drive train, each in their own panel in a 1-row, 3-column #| layout." ggplot(mpg, aes(x = hwy)) + @@ -130,7 +129,7 @@ mpg_summary Then, add a `geom_vline()` layer to your plot that uses the summary data. ```{r} -#| fig.alt = "A histogram showing the highway miles per gallon distribution for +#| fig.alt: "A histogram showing the highway miles per gallon distribution for #| three types of drive train, each in their own panel in a 1-row, 3-column #| layout. Each panel has a vertical black line indicating the mean of the #| distribution." @@ -156,7 +155,7 @@ Suppose you have the following faceted plot. By default, both x and y scales are shared across the facets. ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis and +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis and #| highway miles per gallon on the y-axis. The plot has twelve panels in a #| 4-row, 3-column layout, showing three types of drive train in the #| horizontal direction and four numbers of cylinders in the vertical @@ -170,7 +169,7 @@ ggplot(mpg, aes(x = cty, y = hwy)) + You can control this behaviour with the `scales` argument of faceting functions: varying scales across rows (`"free_x"`), columns (`"free_y"`), or both rows and columns (`"free"`), e.g. ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis and +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis and #| highway miles per gallon on the y-axis. The plot has twelve panels in a #| 4-row, 3-column layout, showing three types of drive train in the #| horizontal direction and four numbers of cylinders in the vertical @@ -185,7 +184,7 @@ ggplot(mpg, aes(x = cty, y = hwy)) + If you also want to make sure that a particular value or range is included in each of the facets, you can set this with `expand_limits()`, e.g. ensure that 10 is included in the x-axis and values between 20 to 25 are included in the y-axis: ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis and +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis and #| highway miles per gallon on the y-axis. The plot has twelve panels in a #| 4-row, 3-column layout, showing three types of drive train in the #| horizontal direction and four numbers of cylinders in the vertical @@ -213,7 +212,7 @@ Set the `strip.text` element in `theme()` to `element_blank()`. Setting `strip.text` to `element_blank()` will remove all facet labels. ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis and +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis and #| highway miles per gallon on the y-axis. The plot has twelve panels in a #| 4-row, 3-column layout. The strips, or panel layout titles and #| their backgrounds, are missing." @@ -226,7 +225,7 @@ ggplot(mpg, aes(x = cty, y = hwy)) + You can also remove the labels across rows only with `strip.x.text` or across columns only with `strip.y.text`. ```{r} -#| fig.alt = "A scatter plot showing city miles per gallon on the x-axis and +#| fig.alt: "A scatter plot showing city miles per gallon on the x-axis and #| highway miles per gallon on the y-axis. The plot has twelve panels in a #| 4-row, 3-column layout. In the vertical direction, the panels indicate four #| numbers of cylinders. The strips of the horizontal direction are missing." @@ -250,7 +249,7 @@ In the data frame below we have 100 observations, 50 of them come from one group These groups have very long names, and so when you facet the ploy by group, the facet labels (strips) get cut off. ```{r} -#| fig.alt = "A histogram with two panels in a 1-row, 2-column layout of random +#| fig.alt: "A histogram with two panels in a 1-row, 2-column layout of random #| data. The first panel has as title 'A long group name for the first group'. #| The second panel has a title 'A muuuuuuuuuuuuuch longer group name for the #| second group'. However, the second title is clipped to the panel width and @@ -269,7 +268,7 @@ ggplot(df, aes(x = x)) + You can control the maximum width of the facet label by setting the `width` in the `label_wrap_gen()` function, which is then passed to the `labeller` argument of your faceting function. ```{r} -#| fig.alt = "A histogram with two panels in a 1-row, 2-column layout of random +#| fig.alt: "A histogram with two panels in a 1-row, 2-column layout of random #| data. The first panel has as title 'A long group name for the first group' #| in two lines of text. The second panel has a title 'A muuuuuuuuuuuuuch #| longer group name for the second group' in three lines of text. The width @@ -305,7 +304,7 @@ df You can plot `price` versus `time` and facet by `country`, but the resulting plot can be a bit difficult to read due to the shared y-axis label. ```{r warning = FALSE} -#| fig.alt = "A timeseries plot showing price over time for two countries, Japan +#| fig.alt: "A timeseries plot showing price over time for two countries, Japan #| and the US, in two panels in a 2-row, 1-column layout. The countries are #| indicated at the top of each panel. The two y-axes have different ranges." ggplot(df, aes(x = year, y = price)) + @@ -317,7 +316,7 @@ ggplot(df, aes(x = year, y = price)) + With the following you can customize the facet labels first with `as_labeller()`, turn off the default y-axis label, and then place the facet labels where the y-axis label goes (`"outside"` and on the `"left"`). ```{r} -#| fig.alt = "A timeseries plot showing price over time for two countries and +#| fig.alt: "A timeseries plot showing price over time for two countries and #| their currencies, the Japanese Yen and the US Dollar, in two panels in a #| 2-row, 1-column layout. The countries and currency units are indicated at #| the left of each panel. The two y-axes have different ranges." diff --git a/vignettes/articles/faq-reordering.Rmd b/vignettes/articles/faq-reordering.Rmd index 39584e225d..d820c7a50e 100644 --- a/vignettes/articles/faq-reordering.Rmd +++ b/vignettes/articles/faq-reordering.Rmd @@ -44,7 +44,7 @@ Classes are ordered alphabetically. You might prefer them to be ordered by the number of cars in each class. ```{r} -#| fig.alt = "A horizontal bar plot showing counts on the x-axis and seven +#| fig.alt: "A horizontal bar plot showing counts on the x-axis and seven #| types of cars on the y-axis. From bottom to top, the car types are in #| alphabetical order." ggplot(mpg, aes(y = class)) + @@ -54,7 +54,7 @@ ggplot(mpg, aes(y = class)) + To do this, you can use `forcats::fct_infreq()`. ```{r} -#| fig.alt = "A horizontal bar plot showing counts on the x-axis and seven +#| fig.alt: "A horizontal bar plot showing counts on the x-axis and seven #| types of cars on the y-axis. From top to bottom, the car types are ordered #| by increasing number of cars." ggplot(mpg, aes(y = forcats::fct_infreq(class))) + @@ -64,7 +64,7 @@ ggplot(mpg, aes(y = forcats::fct_infreq(class))) + If you'd like to plot the highest value first, you can also reverse the order with `forcats::fct_rev()`. You might also want to simplify the axis label. ```{r} -#| fig.alt = "A horizontal bar plot showing counts on the x-axis and seven +#| fig.alt: "A horizontal bar plot showing counts on the x-axis and seven #| types of cars on the y-axis. From top to bottom, the car types are ordered #| in decreasing number of cars." ggplot(mpg, aes(y = forcats::fct_rev(forcats::fct_infreq(class)))) + @@ -86,7 +86,7 @@ The forcats package offers a variety of options for doing this, such as `forcats Suppose you have the following stacked bar plot of `clarity` of `diamonds` by their `cut`. ```{r} -#| fig.alt = "A stacked bar plot showing counts on the y-axis and five cut +#| fig.alt: "A stacked bar plot showing counts on the y-axis and five cut #| qualities of diamonds on the x-axis. Within every stacked bar, the fill #| colour indicates an ordinal clarity of the diamond. The worst clarity has #| the darkest colour and the best quality has the lightest colour. The best @@ -99,7 +99,7 @@ You can reverse the order `clarity` levels are displayed in the bars with `forca This will also change the order they're presented in the legend so the two orders match. ```{r} -#| fig.alt = "A stacked bar plot showing counts on the y-axis and five cut +#| fig.alt: "A stacked bar plot showing counts on the y-axis and five cut #| qualities of diamonds on the x-axis. Within every stacked bar, the fill #| colour indicates an ordinal clarity of the diamond. The worst clarity has #| the lightest colour and the best quality has the darkest colour. The worst @@ -126,7 +126,7 @@ The order of the boxes is determined by the order of the levels of the variable If the faceting variable is character, this order is alphabetical by default. ```{r} -#| fig.alt = "A boxplot showing the highway miles per gallon on the y-axis for +#| fig.alt: "A boxplot showing the highway miles per gallon on the y-axis for #| seven types of car on the x-axis. The car types on the x-axis are in #| alphabetical order." ggplot(mpg, aes(x = class, y = hwy)) + @@ -138,7 +138,7 @@ You can do this in a data transformation step prior to plotting (e.g. with `dply You might then want to customize the x-axis label as well. ```{r} -#| fig.alt = "A boxplot showing the highway miles per gallon on the y-axis for +#| fig.alt: "A boxplot showing the highway miles per gallon on the y-axis for #| seven types of car on the x-axis. The car types on the x-axis sorted from #| left to right by increasing medians." ggplot(mpg, aes(x = forcats::fct_reorder(class, hwy, .fun = median), y = hwy)) + @@ -163,7 +163,7 @@ The order of the panes is determined by the order of the levels of the variable If the faceting variable is character, this order is alphabetical by default. ```{r} -#| fig.alt = "A scatter plot showing the engine displacement on the x-axis and +#| fig.alt: "A scatter plot showing the engine displacement on the x-axis and #| highway miles per gallon on the y-axis of 234 cars. The plot has three #| panels in a 1-row, 3-column layout for three types of drive train. The drive #| trains are ordered alphabetically in the horizontal direction." @@ -177,7 +177,7 @@ You can use `forcats::fct_relevel()` to reorder the levels of `drv`. You can do this in a data transformation step prior to plotting (e.g. with `dplyr::mutate()`) or you can do it directly in the plotting code as shown below. ```{r} -#| fig.alt = "A scatter plot showing the engine displacement on the x-axis and +#| fig.alt: "A scatter plot showing the engine displacement on the x-axis and #| highway miles per gallon on the y-axis of 234 cars. The plot has three #| panels in a 1-row, 3-column layout for three types of drive train. The drive #| trains are in the order 'r', 'f' and '4' from left to right." @@ -215,7 +215,7 @@ Note that the blue circle is partially covered by the yellow triangle since that Similarly the black asterisk appears on top of the red square. ```{r} -#| fig.alt = "A scatter plot showing four points at the same y-positions but at +#| fig.alt: "A scatter plot showing four points at the same y-positions but at #| four x-positions, of which two are very distinct. Every point has a distinct #| shape and colour. A yellow triangle is plotted on top of a blue circle. #| A black asterisk is plotted on top of a red square." @@ -229,7 +229,7 @@ Suppose you arranged your data in ascending order of the x-coordinates and plott Now the blue circle is over the yellow triangle since 0.01 comes after 0 and similarly the red square is over the black asterisk since 1 comes after 0.99. ```{r} -#| fig.alt = "A scatter plot showing four points at the same y-positions but at +#| fig.alt: "A scatter plot showing four points at the same y-positions but at #| four x-positions, of which two are very distinct. Every point has a distinct #| shape and colour. A blue circle is plotted on top of a yellow triangle. A #| red square is plotted on top of a black asterisk." @@ -245,16 +245,15 @@ df_arranged %>% If you wanted to make sure that the observation identified with an asterisk is always plotted on top, regardless of how the data are arranged in the data frame, you can create an additional layer for that observation. ```{r} -#| fig.alt = c( -#| "A scatter plot showing four points at the same y-positions but at four +#| fig.alt: +#| - "A scatter plot showing four points at the same y-positions but at four #| x-positions, of which two are very distinct. Every point has a distinct shape #| and colour. A yellow triangle is plotted on top of a blue circle. A black -#| asterisk is plotted on top of a red square.", -#| "A scatter plot showing four points at the same y-positions but at four +#| asterisk is plotted on top of a red square." +#| - "A scatter plot showing four points at the same y-positions but at four #| x-positions, of which two are very distinct. Every point has a distinct shape #| and colour. A blue circle is plotted on top of a yellow triangle. A black #| asterisk is plotted on top of a red square." -#| ) ggplot(mapping = aes(x = x, y = y, fill = fill, shape = shape)) + geom_point(data = df %>% filter(shape != "asterisk"), size = 8) + diff --git a/vignettes/extending-ggplot2.Rmd b/vignettes/extending-ggplot2.Rmd index 6ee65ae718..adac6896ea 100644 --- a/vignettes/extending-ggplot2.Rmd +++ b/vignettes/extending-ggplot2.Rmd @@ -86,7 +86,7 @@ stat_chull <- function(mapping = NULL, data = NULL, geom = "polygon", Once we have a layer function we can try our new stat: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. The convex hull of all the points is marked by a #| polygon with no fill." ggplot(mpg, aes(displ, hwy)) + @@ -99,7 +99,7 @@ ggplot(mpg, aes(displ, hwy)) + Once we've written this basic object, ggplot2 gives a lot for free. For example, ggplot2 automatically preserves aesthetics that are constant within each group: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. The convex hulls of points, grouped and coloured by #| three types of drive train, are marked by polygons with no fill but the #| outline matches the colours of the points." @@ -111,7 +111,7 @@ ggplot(mpg, aes(displ, hwy, colour = drv)) + We can also override the default geom to display the convex hull in a different way: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. The points that are part of the convex hull of all #| points are marked with a red outline." ggplot(mpg, aes(displ, hwy)) + @@ -124,7 +124,7 @@ ggplot(mpg, aes(displ, hwy)) + A more complex stat will do some computation. Let's implement a simple version of `geom_smooth()` that adds a line of best fit to a plot. We create a `StatLm` that inherits from `Stat` and a layer function, `stat_lm()`: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. A straight line with a negative slope passes through #| the cloud of points." StatLm <- ggproto("StatLm", Stat, @@ -159,7 +159,7 @@ ggplot(mpg, aes(displ, hwy)) + `StatLm` is inflexible because it has no parameters. We might want to allow the user to control the model formula and the number of points used to generate the grid. To do so, we add arguments to the `compute_group()` method and our wrapper function: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. A wobbly line follows the point cloud over the #| horizontal direction. 20 points are placed on top of the line with constant #| horizontal intervals." @@ -224,13 +224,12 @@ Sometimes you have calculations that should be performed once for the complete d To do this we override the `setup_params()` method. It's passed the data and a list of params, and returns an updated list. ```{r} -#| fig.alt = c( -#| "A line plot showing three kernel density estimates of engine displacement, +#| fig.alt: +#| - "A line plot showing three kernel density estimates of engine displacement, #| coloured for three types of drive trains. The lines are a little bit -#| wobbly.", -#| "A line plot showing three kernel density estimates of engine displacement, +#| wobbly." +#| - "A line plot showing three kernel density estimates of engine displacement, #| coloured for three types of drive trains. The lines are fairly smooth." -#| ) StatDensityCommon <- ggproto("StatDensityCommon", Stat, required_aes = "x", @@ -278,7 +277,7 @@ I recommend using `NULL` as a default value. If you pick important parameters au This stat illustrates another important point. If we want to make this stat usable with other geoms, we should return a variable called `density` instead of `y`. Then we can set up the `default_aes` to automatically map `density` to `y`, which allows the user to override it to use with different geoms: ```{r} -#| fig.alt = "A plot showing the engine displacement versus three types of drive +#| fig.alt: "A plot showing the engine displacement versus three types of drive #| trains. Every drive train is represented by a series of densely packed #| points that imitate a horizontal line, and their colour intensity indicates #| the kernel density estimate of the displacement." @@ -299,7 +298,7 @@ ggplot(mpg, aes(displ, drv, colour = after_stat(density))) + However, using this stat with the area geom doesn't work quite right. The areas don't stack on top of each other: ```{r} -#| fig.alt = "An area plot showing the kernel density estimates of +#| fig.alt: "An area plot showing the kernel density estimates of #| engine displacement. Three areas are shown that indicate the estimates for #| three types of drive trains separately. All areas are floored to the x-axis #| and overlap one another." @@ -310,16 +309,15 @@ ggplot(mpg, aes(displ, fill = drv)) + This is because each density is computed independently, and the estimated `x`s don't line up. We can resolve that issue by computing the range of the data once in `setup_params()`. ```{r} -#| fig.alt = c( -#| "A stacked area plot showing kernel density estimates of engine displacement. +#| fig.alt: +#| - "A stacked area plot showing kernel density estimates of engine displacement. #| Three areas are shown that indicate the estimates for three types of drive #| trains separately. The areas are stacked on top of one another and show -#| no overlap.", -#| "A heatmap showing the density of engine displacement for three types of +#| no overlap." +#| - "A heatmap showing the density of engine displacement for three types of #| drive trains. The heatmap has three rows for the drive trains, but are #| continuous in the horizontal direction. The fill intensity of the heatmap #| shows the kernel density estimates." -#| ) StatDensityCommon <- ggproto("StatDensityCommon", Stat, required_aes = "x", default_aes = aes(y = after_stat(density)), @@ -377,7 +375,7 @@ It's harder to create a new geom than a new stat because you also need to know s It's easiest to start with a simple example. The code below is a simplified version of `geom_point()`: ```{r GeomSimplePoint} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. The points are larger than the default." GeomSimplePoint <- ggproto("GeomSimplePoint", Geom, required_aes = c("x", "y"), @@ -441,7 +439,7 @@ Overriding `draw_panel()` is most appropriate if there is one graphic element pe The following code makes a simplified version of `GeomPolygon`: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. The convex hulls of points, grouped by 7 types of #| cars, are displayed as multiple polygons with no fill, but the outer line is #| coloured by the type." @@ -512,7 +510,7 @@ You might want to compare this to the real `GeomPolygon`. You'll see it override Sometimes you just want to make a small modification to an existing geom. In this case, rather than inheriting from `Geom` you can inherit from an existing subclass. For example, we might want to change the defaults for `GeomPolygon` to work better with `StatChull`: ```{r} -#| fig.alt = "Scatterplot of engine displacement versus highway miles per +#| fig.alt: "Scatterplot of engine displacement versus highway miles per #| gallon, for 234 cars. The convex hull of all the points is marked by a #| polygon with no fill." GeomPolygonHollow <- ggproto("GeomPolygonHollow", GeomPolygon, @@ -628,12 +626,11 @@ title | `element_text()` | all text in title elements (plot, axes & lege These set default properties that are inherited by more specific settings. These are most useful for setting an overall "background" colour and overall font settings (e.g. family and size). ```{r axis-line-ex} -#| fig.alt = c( -#| "Scatterplot of three observations arranged diagonally. The axis titles 'x' -#| and 'y' are coloured in black", -#| "Scatterplot of three observations arranged diagonally. The axis titles 'x' +#| fig.alt: +#| - "Scatterplot of three observations arranged diagonally. The axis titles 'x' +#| and 'y' are coloured in black" +#| - "Scatterplot of three observations arranged diagonally. The axis titles 'x' #| and 'y' are coloured in red" -#| ) df <- data.frame(x = 1:3, y = 1:3) base <- ggplot(df, aes(x, y)) + geom_point() + @@ -809,11 +806,10 @@ FacetDuplicate <- ggproto("FacetDuplicate", Facet, Now with everything assembled, lets test it out: ```{r} -#| fig.alt = c( -#| "Scatterplot showing horsepower against miles per gallon for 32 cars.", -#| "Scatterplot with two panels showing horsepower against miles per gallon for +#| fig.alt: +#| - "Scatterplot showing horsepower against miles per gallon for 32 cars." +#| - "Scatterplot with two panels showing horsepower against miles per gallon for #| 32 cars. The left and right panels are identical." -#| ) p <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() p p + facet_duplicate() @@ -1005,7 +1001,7 @@ As is very apparent, the `draw_panel` method can become very unwieldy once it be Enough talk - lets see if our new and powerful faceting extension works: ```{r} -#| fig.alt = "Scatterplot with two panels showing horsepower against miles per +#| fig.alt: "Scatterplot with two panels showing horsepower against miles per #| gallon for 32 cars. Both panels show the same datapoints. The left panel is #| titled 'original' and the right panel is titled 'transformed (sqrt)'. On the #| right panel, the miles per gallon are displayed on a square root @@ -1018,7 +1014,7 @@ ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_trans('sqrt') As the rendering part of a facet class is often the difficult development step, it is possible to piggyback on the existing faceting classes to achieve a range of new facetings. Below we will subclass `facet_wrap()` to make a `facet_bootstrap()` class that splits the input data into a number of panels at random. ```{r} -#| fig.alt = "Scatterplot with three-by-three panels showing the weight versus +#| fig.alt: "Scatterplot with three-by-three panels showing the weight versus #| the price of about 10.000 diamonds in every panel. The panels are titled 1 #| to 9 and show different points, but are visually similar." diff --git a/vignettes/ggplot2-specs.Rmd b/vignettes/ggplot2-specs.Rmd index d66cb5951b..7829f05f6a 100644 --- a/vignettes/ggplot2-specs.Rmd +++ b/vignettes/ggplot2-specs.Rmd @@ -53,7 +53,7 @@ Line types can be specified with: 4 = dotdash, 5 = longdash, 6 = twodash, as shown below: ```{r} - #| fig.alt = "A series of 6 horizontal lines with different line types. + #| fig.alt: "A series of 6 horizontal lines with different line types. #| From top-to-bottom they are titled 'solid', 'dashed', 'dotted', #| 'dotdash', 'longdash', 'twodash'." lty <- c("solid", "dashed", "dotted", "dotdash", "longdash", "twodash") @@ -76,7 +76,7 @@ Line types can be specified with: three off followed by one on and finally three off. ```{r} - #| fig.alt = "A series of 9 horizontal lines with different line types. + #| fig.alt: "A series of 9 horizontal lines with different line types. #| Each line is titled by two hexadecimal digits that determined the #| lengths of dashes and gaps." lty <- c("11", "18", "1f", "81", "88", "8f", "f1", "f8", "ff") @@ -107,16 +107,15 @@ with this mistake. and can be one of "round", "butt" (the default), or "square". ```{r, out.width = "30%", fig.show = "hold"} - #| fig.alt = c( - #| "A plot showing a line with an angle. A thinner red line is placed over - #| a thicker black line. The black line ends where the red line ends.", - #| "A plot showing a line with an angle. A thinner red line is placed over + #| fig.alt: + #| - "A plot showing a line with an angle. A thinner red line is placed over + #| a thicker black line. The black line ends where the red line ends." + #| - "A plot showing a line with an angle. A thinner red line is placed over #| a thicker black line. The black line ends past where the red line ends, - #| and ends in a semicircle.", - #| "A plot showing a line with an angle. A thinner red line is placed over + #| and ends in a semicircle." + #| - "A plot showing a line with an angle. A thinner red line is placed over #| a thicker black line. The black line ends past where the red line ends, #| and ends in a square shape." - #| ) 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 + @@ -136,15 +135,14 @@ with this mistake. "round" (the default), "mitre", or "bevel". ```{r, out.width = "30%", fig.show = "hold"} - #| fig.alt = c( - #| "A plot showing a thin red line on top of a thick black line shaped like - #| the letter 'V'. The corner in the black V-shape is rounded.", - #| "A plot showing a thin red line on top of a thick black line shaped like - #| the letter 'V'. The corner in the black V-shape is sharp.", - #| "A plot showing a thin red line on top of a thick black line shaped like + #| fig.alt: + #| - "A plot showing a thin red line on top of a thick black line shaped like + #| the letter 'V'. The corner in the black V-shape is rounded." + #| - "A plot showing a thin red line on top of a thick black line shaped like + #| the letter 'V'. The corner in the black V-shape is sharp." + #| - "A plot showing a thin red line on top of a thick black line shaped like #| the letter 'V'. A piece of the corner is cut off so that the two #| straight parts are connected by a horizontal part." - #| ) df <- data.frame(x = 1:3, y = c(9, 1, 9)) base <- ggplot(df, aes(x, y)) + ylim(0, 10) base + @@ -175,7 +173,7 @@ Shapes take five types of values: * An __integer__ in $[0, 25]$: ```{r} - #| fig.alt = "A 5-by-5 grid of point symbols annotated by the numbers + #| fig.alt: "A 5-by-5 grid of point symbols annotated by the numbers #| that can be used to represent the symbols. From left to right, the #| first 15 symbols are lines or open shapes, the next 5 symbols are solid #| shapes and the last 5 symbols are filled shaped." @@ -195,7 +193,7 @@ Shapes take five types of values: * The __name__ of the shape: ```{r out.width = "90%", fig.asp = 0.4, fig.width = 8} - #| fig.alt = "An irregular 6-by-7 grid of point symbols annotated by the + #| fig.alt: "An irregular 6-by-7 grid of point symbols annotated by the #| names that can be used to represent the symbols. Broadly, from top to #| bottom, the symbols are circles, squares, diamonds, triangles and #| others. Broadly from left to right, the symbols are solid shapes, @@ -233,7 +231,7 @@ Shapes take five types of values: While `colour` applies to all shapes, `fill` only applies to shapes 21-25, as can be seen above. The size of the filled part is controlled by `size`, the size of the stroke is controlled by `stroke`. Each is measured in mm, and the total size of the point is the sum of the two. Note that the size is constant along the diagonal in the following figure. ```{r} -#| fig.alt = "A plot showing a 4-by-4 grid of red points, the top 12 points with +#| fig.alt: "A plot showing a 4-by-4 grid of red points, the top 12 points with #| black outlines. The size of the points increases horizontally. The stroke of #| the outlines of the points increases vertically. A white diagonal line with #| a negative slope marks that the 'stroke' versus 'size' trade-off has @@ -252,7 +250,7 @@ ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) + There are only three fonts that are guaranteed to work everywhere: "sans" (the default), "serif", or "mono": ```{r} -#| fig.alt = "A plot showing three text labels arranged vertically. The top +#| fig.alt: "A plot showing three text labels arranged vertically. The top #| label is 'sans' and is displayed in a sans-serif font. The middle label is #| 'serif' and is displayed in a serif font. The bottom label is 'mono' and #| is displayed in a monospaced font." @@ -272,7 +270,7 @@ Both approaches have pros and cons, so you will to need to try both of them and ### Font face ```{r} -#| fig.alt = "A plot showing four text labels arranged vertically. The top +#| fig.alt: "A plot showing four text labels arranged vertically. The top #| label is 'bold.italic' and is displayed in bold and italic. The next three #| labels are 'italic', 'bold' and 'plain' and are displayed in their #| respective styles." @@ -294,7 +292,7 @@ Horizontal and vertical justification have the same parameterisation, either a s * left = 0, center = 0.5, right = 1 ```{r} -#| fig.alt = "A 3-by-3 grid of text on top of points, with horizontal text +#| fig.alt: "A 3-by-3 grid of text on top of points, with horizontal text #| justification increasing from 0 to 1 on the x-axis and vertical #| justification increasing from 0 to 1 on the y-axis. The points make it #| easier to see the relative placement of text." diff --git a/vignettes/ggplot2.Rmd b/vignettes/ggplot2.Rmd index f82f092df8..36193b65a4 100644 --- a/vignettes/ggplot2.Rmd +++ b/vignettes/ggplot2.Rmd @@ -23,7 +23,7 @@ This allows you to 'speak' a graph from composable elements, instead of being li More complete information about how to use ggplot2 can be found in the [book](https://ggplot2-book.org/), but here you'll find a brief overview of the plot components and some terse examples to build a plot like this: ```{r cake, echo = FALSE} -#| fig.alt = "Scatterplot of city versus highway miles per gallon, for many cars +#| fig.alt: "Scatterplot of city versus highway miles per gallon, for many cars #| coloured by engine displacement. The plot has six panels in a 2-row, #| 3-column layout, showing the combinations of three types of drive train and #| year of manifacture. Every panel has an individual trendline." @@ -41,7 +41,7 @@ ggplot(mpg, aes(cty, hwy)) + For structure, we go over the 7 composable parts that come together as a set of instructions on how to draw a chart. ```{r overview_graphic, echo=FALSE} -#| fig.alt = "A schematic displaying seven overlaying rhombuses indicating the +#| fig.alt: "A schematic displaying seven overlaying rhombuses indicating the #| different composable parts. From bottom to top, the labels read 'Data', #| 'Mapping', 'Layers', 'Scales', 'Facets', 'Coordinates' and 'Theme'." n <- 7 @@ -108,7 +108,7 @@ Every layer consists of three important parts: A layer can be constructed using the `geom_*()` and `stat_*()` functions. These functions often determine one of the three parts of a layer, while the other two can still be specified. Here is how we can use two layers to display the `cty` and `hwy` columns of the `mpg` dataset as points and stack a trend line on top. ```{r example_layer, fig.show='hold'} -#| fig.alt = "A scatterplot showing city versus highway miles per gallon for +#| fig.alt: "A scatterplot showing city versus highway miles per gallon for #| many cars. The plot has a blue trendline with a positive slope." ggplot(mpg, aes(cty, hwy)) + # to create a scatterplot @@ -125,7 +125,7 @@ Scales are responsible for updating the limits of a plot, setting the breaks, fo To use scales, one can use one of the scale functions that are patterned as `scale_{aesthetic}_{type}()` functions, where `{aesthetic}` is one of the pairings made in the mapping part of a plot. To map the `class` column in the `mpg` dataset to the viridis colour palette, we can write the following: ```{r example_scales} -#| fig.alt = "A scatterplot showing city versus highway miles per gallon for +#| fig.alt: "A scatterplot showing city versus highway miles per gallon for #| many cars. The points are coloured according to seven classes of cars." ggplot(mpg, aes(cty, hwy, colour = class)) + geom_point() + @@ -141,7 +141,7 @@ The facets have their own mapping that can be given as a formula. To plot subsets of the `mpg` dataset based on levels of the `drv` and `year` variables, we can use `facet_grid()` as follows: ```{r example_facets} -#| fig.alt = "Scatterplot of city versus highway miles per gallon, for many cars. +#| fig.alt: "Scatterplot of city versus highway miles per gallon, for many cars. #| The plot has six panels in a 2-row, 3-column layout, showing the #| combinations of three types of drive train and year of manifacture." ggplot(mpg, aes(cty, hwy)) + @@ -157,7 +157,7 @@ While typically Cartesian coordinates are used, the coordinate system powers the We can also use coordinates to display a plot with a fixed aspect ratio so that one unit has the same length in both the x and y directions. The `coord_fixed()` function sets this ratio automatically. ```{r example_coords} -#| fig.alt = "A scatterplot showing city versus highway miles per gallon for +#| fig.alt: "A scatterplot showing city versus highway miles per gallon for #| many cars. The aspect ratio of the plot is such that units on the x-axis #| have the same length as units on the y-axis." ggplot(mpg, aes(cty, hwy)) + @@ -172,7 +172,7 @@ The [theme](https://ggplot2-book.org/themes) system controls almost any visuals To tweak the look of the plot, one can use many of the built-in `theme_*()` functions and/or detail specific aspects with the `theme()` function. The `element_*()` functions control the graphical attributes of theme components. ```{r example_theme} -#| fig.alt = "A scatterplot showing city versus highway miles per gallon for +#| fig.alt: "A scatterplot showing city versus highway miles per gallon for #| many cars. The points are coloured according to seven classes of cars. The #| legend of the colour is displayed on top of the plot. The plot has thick #| axis lines and the bottom axis line is blue." @@ -191,7 +191,7 @@ ggplot(mpg, aes(cty, hwy, colour = class)) + As mentioned at the start, you can layer all of the pieces to build a customized plot of your data, like the one shown at the beginning of this vignette: ```{r outro} -#| fig.alt = "Scatterplot of city versus highway miles per gallon, for many cars +#| fig.alt: "Scatterplot of city versus highway miles per gallon, for many cars #| coloured by engine displacement. The plot has six panels in a 2-row, #| 3-column layout, showing the combinations of three types of drive train and #| year of manifacture. Every panel has an individual trendline."