答案 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创建。