rbonac
rbonac

Reputation: 125

Relocate legend entries and axis labels in ggplot in R

Hey there I'm new to R and have a very small question

I have the following dataset:

head(risk_free_rate_comparison)

   Dates `       Swap rate` `Sovereign bond yield rate` `Swap rate - Sovereign bond yield rate`
  <dttm>         <dbl>       <dbl>                       <dbl>
1 2007-01-02     408.9       380.9568                    27.9432
2 2007-01-03     410.3       380.4535                    29.8465
3 2007-01-04     409.2       381.3993                    27.8007
4 2007-01-05     414.3       385.0663                    29.2337
5 2007-01-08     413.1       384.2545                    28.8455
6 2007-01-09     415.5       384.9770                    30.5230

,with the following plot:

ggplot(d, aes(Dates, value, color = variable, linetype = variable)) +
+     geom_line() +
+     labs(color = NULL, linetype = NULL) +
+     theme_classic() +
+     theme(legend.position = "bottom") +
+     ylab("Rates in bp")

riskfreeratecomparison

I'm satisfied with the position of the legend, but it is it possible to have the entries one below the other instead of side by side?

Furthermore I would like to move the axis labels a little bit away from the axis for aesthetic reasons.

Upvotes: 0

Views: 259

Answers (1)

Joe
Joe

Reputation: 3796

My theme() addition at the end will address both of your problems:

library(tidyverse)

mtcars %>% 
  mutate(am = factor(am, labels = c("auto", "manu"))) %>% 
  ggplot(., aes(wt, mpg, color = am, linetype = am)) +
  geom_line() +
  labs(color = NULL, linetype = NULL) +
  theme_classic() +
  ylab("Rates in bp") + 
  theme(
    legend.position = "bottom",
    legend.direction = "vertical",
    legend.box.margin = margin(t = 30),
    axis.title.x = element_text(margin = margin(t = 20))
  )

Upvotes: 1

Related Questions