Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ggplot2 - Combine two legends in R


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

1 Answer

0 votes
by (71.8m points)

Welcome to SO. I am posting this also for a suggestion how to create a reproducible example. I am using an inbuilt data set and do some quick data wrangling to get in a structurally similar shape as your data. For the question, it does not matter that we are dealing with dates, nor the actual values for that sake.

I am changing the legend margins, after assigning a name = NULL to the color legend.

Small tips re your code: I discovered several theme calls - this is redundant - try putting all in one single call to theme(). Also, you have used both labs and then xlab, ylab and ggtitles. The last three can be put into labs as arguments: labs(x = , y = , title = )

And - use a new line for every new plot layer (see my code). google "tidyverse style guide" for further code style tips. I am using RStudio and using the add-in package "styler" to fine-tune my code styling.

library(tidyverse)
mtcars %>% 
  group_by(carb) %>%
  summarise(av_disp = mean(disp)) %>%
ggplot(aes(carb, av_disp)) +
  geom_col(aes( fill = carb > 3)) +
  geom_line(aes(color = "7-day average")) +
  scale_color_discrete(name = NULL) +
  theme(legend.margin = margin(-0.5,0,0,0, unit="cm"))
#> `summarise()` ungrouping output (override with `.groups` argument)

Created on 2021-01-06 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...