Skip to content

Instantly share code, notes, and snippets.

@kylebutts
Created October 4, 2024 12:18
Show Gist options
  • Save kylebutts/bcac802aa7f3cdcb0aed344ea5ddf71c to your computer and use it in GitHub Desktop.
Save kylebutts/bcac802aa7f3cdcb0aed344ea5ddf71c to your computer and use it in GitHub Desktop.
Plot multiple columns of a data frame and have a legend
library(ggplot2)
beta <- seq(-0.2, 0.2, by = 0.001)
exp_minus_1 <- exp(beta) - 1
(plot_pct_change_appxoimation <- ggplot() +
  geom_line(
    aes(x = beta, y = beta, color = "approx"),
    linewidth = 2
  ) +
  geom_line(
    aes(x = beta, y = exp_minus_1, color = "exact"),
    linewidth = 2
  ) +
  scale_color_manual(
    values = c("exact" = "#3B3B9A", "approx" = "#FFA500"),
    labels = c(
      "exact" = "exp(beta) - 1",
      "approx" = "beta"
    )
  ) +
  labs(
    x = "beta",
    y = "% Change in $Y$",
    color = NULL
  ) +
  kfbmisc::theme_kyle(base_size = 18) +
  theme(
    legend.position = "top",
    legend.margin = margin(0, 0, 5, 0),
    legend.justification = c(0, 1),
    legend.location = "plot"
  )
)

Created on 2024-10-04 with reprex v2.1.0

# %%
library(ggplot2)
beta <- seq(-0.2, 0.2, by = 0.001)
exp_minus_1 <- exp(beta) - 1
# %%
#| dpi: 200
#| fig.width: 8
#| fig.height: 6
(plot_pct_change_appxoimation <- ggplot() +
geom_line(
aes(x = beta, y = beta, color = "approx"),
linewidth = 2
) +
geom_line(
aes(x = beta, y = exp_minus_1, color = "exact"),
linewidth = 2
) +
scale_color_manual(
values = c("exact" = "#3B3B9A", "approx" = "#FFA500"),
labels = c(
"exact" = "exp(beta) - 1",
"approx" = "beta"
)
) +
labs(
x = "beta",
y = "% Change in $Y$",
color = NULL
) +
kfbmisc::theme_kyle(base_size = 18) +
theme(
legend.position = "top",
legend.margin = margin(0, 0, 5, 0),
legend.justification = c(0, 1),
legend.location = "plot"
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment