在R中的ggplot中重新定位图例条目和轴标签

时间:2017-10-05 15:51:20

标签: r ggplot2 legend

嘿,我是R的新手并且有一个非常小的问题

我有以下数据集:

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

,如下图:

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

我对传奇的位置感到满意,但是可以将条目放在另一个下面而不是并排吗?

此外,出于美观原因,我想将轴标签移动一点距离轴。

1 个答案:

答案 0 :(得分:1)

最后我的主题()添加将解决您的两个问题:

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))
  )