组合线条和条形图:如何生成合适的图例?

Fra*_*ert 6 r linechart legend bar-chart ggplot2

d2看起来很好的传奇; 因为d1,我想在白色/透明的背景上展示水平线.

df = data.frame(
  Date = c("2012-11-30", "2012-12-03", "2012-12-04"),
  d1 = c(9, 5, 11),
  d2 = c(4, 6, 3)
)
ggplot(df, aes(Date)) + 
  geom_bar(aes(y = d2, color = "d2"), stat="identity", fill = "red") +
  geom_line(aes(y = d1, group = 1, color = "d1"))  +
  scale_colour_manual("", values=c("d1" = "blue", "d2" = "red")) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Did*_*rts 8

它不是一个优雅的解决方案,但至少它给出了一些结果.

我说aes(fill="d2")geom_bar()和删除fill="red".然后我为线条和条形添加了单独的比例.然后在theme()我从图例条目中删除了灰色背景.

为了确保在d2之前显示图例中的d1,scale_colour_manual(" ")引号之间应该有额外的空格("更长"的名称).

要将图例键保持在一行中,请legend.box="horizontal"添加到theme()

  ggplot(df, aes(Date)) + 
    geom_bar(aes(y = d2,fill="d2"), stat="identity") +
    geom_line(aes(y = d1, group = 1, color = "d1")) +
    scale_colour_manual(" ", values=c("d1" = "blue", "d2" = "red"))+
    scale_fill_manual("",values="red")+
    theme(legend.key=element_blank(),
          legend.title=element_blank(),
          legend.box="horizontal")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述