Code formatting

I'm having troubles deciding on how to format more complex R code, e.g. when creating plots with ggplot2. Here's an example:

   base_plot <- ggplot() +
      theme_minimal() +
      labs(x = "", y = "") +
      geom_abline(aes(color = "True line",
                      linetype = "True line",
                      slope = betas$vals[2],
                      intercept = betas$vals[1]),
                  size = 1) +
      geom_abline(aes(color = "Linear fit (without error)",
                      linetype = "Linear fit (without error)",
                      slope = coefs$vals[2],
                      intercept = coefs$vals[1]),
                  size = 1) +
      scale_color_manual(name = "",
                         values = c("True line" = "orange", "Linear fit (without error)" = "black")) +
      scale_linetype_manual(name = "",
                            values = c("True line" = 1, "Linear fit (without error)" = 2)) +
      geom_point(data = dat,
                 aes(x = x, y = y),
                 alpha = 0) +
      theme(legend.position = "bottom",
            text = element_text(size = 20))

How would you format the above code? Are there any documents or other resources you consult for code styling?

I will use styler package and styler add-in (style selection) to do this for me.

Which styler are you using. The default tidyverse_style() doesn't do much it seems.

What you have seems fine to me I would only split out long lines.

 scale_color_manual(name = "",
                         values = c("True line" = "orange", "Linear fit (without error)" = "black")) +
      scale_linetype_manual(name = "",
                            values = c("True line" = 1, "Linear fit (without error)" = 2)) +
scale_color_manual(name = "",
                   values = c("True line" = "orange", 
                              "Linear fit (without error)" = "black")) +
  scale_linetype_manual(name = "",
                        values = c("True line" = 1, 
                                   "Linear fit (without error)" = 2)) +
1 Like

That's a good suggestion. Thanks for that.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.