Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

r - Combined line & bar geoms: How to generate proper legend?

The legend for d2 looks fine; for d1, I would like to show just the hoizontal line against a white/transparent backgounnd.

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

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not an elegant solution but at least it gives some result.

I added aes(fill="d2") in geom_bar() and removed fill="red". Then I added separate scales for line and for bars. Then in theme() I removed grey background from legend entry.

To ensure that d1 in legend is shown before d2 in scale_colour_manual(" ") there should be extra space between quotes ("longer" name).

To keep legend keys in one line, legend.box="horizontal" added to 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")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...