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
304 views
in Technique[技术] by (71.8m points)

ggplot2 - Creating manually a legend in ggplot R


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

1 Reply

0 votes
by (71.8m points)

Find code below and what I believe is your desired plot. You will have to tweak labels to match what you need but I put place holder names. The key is using the scale_fill_manual with a named vector of colors and calling those color names in the aes of each layer you need to use that color in. Also a neat trick is using alpha() to apply alpha as a color rather than a separate scale. Finally the y axis transformation you were looking for is position = "right" so it ends up on top after coord_flip().

ggplot(data = mytable, aes(x = state, y = SpeedPerBilion)) +
  xlab("") +
  ylab("") +
  coord_flip() +
  geom_bar(stat = "identity", aes(fill = "Speeding")) +
  geom_bar(data = mytable,
           aes(x = state, y = num_drivers, fill = "All"),
           stat = "identity") +
  theme(plot.title = element_text(face = "bold")) +
  scale_y_continuous(position = "right") +
  scale_fill_manual(name = "Speeding Involved",
                    values = c("Speeding" = alpha("red", 1), "All" = alpha("red", 0.5))) +
  labs(title = "Drviers Involved In Fatal Collisions While Speeding",
       subtitle = "As a share of the number of fatal collisions per billion miles, 2009")

Which produces this plot:

plot output with adjusted alpha

Note: For some reason the image saved on imgur is distorting the transparency in the legend but it looks fine before I paste it in here. Please confirm the result on your own computer. To illustrate what I'm actually seeing, I turned down the alpha to 0.25 to generate this image.


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

...