如何为辅助轴ggplot添加图例

时间:2018-07-21 12:55:57

标签: r ggplot2

我正在尝试在以下代码中为辅助轴添加图例

{{1}}

plot

我也想为折线图添加图例。

1 个答案:

答案 0 :(得分:1)

您可以在linetype调用的aes内添加geom_line,为该行创建一个单独的图例,然后将其图例移近fill图例

另请参阅此answer

library(reshape2)
library(tidyverse)

ggplot(data = df_bar, aes(x = period, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  theme(
    axis.text = element_text(size = 9),
    axis.title = element_text(size = 14, face = "bold")
  ) +
  ylab("primary axis") +
  geom_line(data = df_line, aes(x = period, y = (d) / 10, group = 1, linetype = "My line"), inherit.aes = FALSE) +
  scale_linetype_manual(NULL, values = 1) +
  geom_point(data = df_line, aes(x = period, y = (d) / 10, group = 1), inherit.aes = FALSE) +
  scale_y_continuous(sec.axis = sec_axis(~. * 10, name = "secondary axis")) +
  theme(legend.background = element_rect(fill = "transparent"), 
      legend.box.background = element_rect(fill = "transparent", colour = NA),
      legend.key = element_rect(fill = "transparent"), 
      legend.spacing = unit(-1, "lines"))

要获得同一图例中的点和线,我们可以将color映射到aes并使用scale_color_manual

ggplot(data = df_bar, aes(x = period, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  theme(
    axis.text = element_text(size = 9),
    axis.title = element_text(size = 14, face = "bold")
  ) +
  ylab("primary axis") +
  geom_line(data = df_line, aes(x = period, y = (d) / 10, group = 1, color = "My line"), inherit.aes = FALSE) +
  scale_color_manual(NULL, values = "black") +
  geom_point(data = df_line, aes(x = period, y = (d) / 10, group = 1, color = "My line"), inherit.aes = FALSE) +
  scale_y_continuous(sec.axis = sec_axis(~. * 10, name = "secondary axis")) +
  theme(legend.background = element_rect(fill = "transparent"), 
        legend.box.background = element_rect(fill = "transparent", colour = NA),
        legend.key = element_rect(fill = "transparent"), 
        legend.spacing = unit(-1, "lines"))

reprex package(v0.2.0.9000)于2018-07-21创建。