|
1 | 1 | ---
|
2 | 2 | title: Notes for foundations of ggplot2
|
3 | 3 | author: Eric Scott
|
| 4 | +date: 2024-06-06 |
4 | 5 | format:
|
5 | 6 | html:
|
6 | 7 | toc: true
|
@@ -200,7 +201,7 @@ ggplot(penguins, aes(x = island, y = body_mass_g, color = sex)) +
|
200 | 201 | Here's the original plot, saved as `p`
|
201 | 202 |
|
202 | 203 | ```{r}
|
203 |
| -#| echo: false |
| 204 | +#| echo: true |
204 | 205 | p <-
|
205 | 206 | ggplot(penguins |> drop_na(), aes(x = body_mass_g, y = bill_length_mm, color = species)) +
|
206 | 207 | geom_point() +
|
@@ -287,6 +288,14 @@ ggplot(penguins, aes(x = island, y = body_mass_g)) +
|
287 | 288 | color = "blue", shape = "square")
|
288 | 289 | ```
|
289 | 290 |
|
| 291 | +You can also use `scale_x_log10()` to create breaks for a log scale |
| 292 | + |
| 293 | +```{r} |
| 294 | +#| echo: true |
| 295 | +p + scale_x_continuous(n.breaks = 15) |
| 296 | +p + scale_x_log10(n.breaks = 15) |
| 297 | +``` |
| 298 | + |
290 | 299 |
|
291 | 300 | ## Geoms
|
292 | 301 |
|
@@ -414,3 +423,23 @@ p + coord_cartesian(xlim = c(4000, 5000))
|
414 | 423 |
|
415 | 424 | This has the effect of ***zooming in*** on the x-axis. The lines and points just outside of the limits are cut off and the slopes of the trend lines are unaffected because no data has been removed.
|
416 | 425 |
|
| 426 | +We can use `coord_trans()` to warp the coordinate system to plot things on a log scale, for example. This does something slightly different than `scale_x_log10()`. |
| 427 | + |
| 428 | +```{r} |
| 429 | +df <- tibble(x = 1:100, |
| 430 | + y = x^2) |
| 431 | +p2 <- |
| 432 | + ggplot(df, aes(x = x, y = y)) + |
| 433 | + geom_point() + |
| 434 | + geom_smooth(method = "lm") |
| 435 | +p2 |
| 436 | +``` |
| 437 | + |
| 438 | + |
| 439 | + |
| 440 | +```{r} |
| 441 | +p2 + coord_trans(x = "log10") |
| 442 | +p2 + scale_x_log10() |
| 443 | +``` |
| 444 | + |
| 445 | +You can see that `coord_trans()` *warps* the coordinate space because the regression line, which we specified as being straight with `method = "lm"`, is now curved. But with `scale_x_log10()` the line stays straight—the scale transforms the data *before* `geom_smooth()` calculates its statistics. |
0 commit comments