I am trying to add a legend to my graph. I made a bar plot with an overlay line plot. I was under the impression that if you put col, fill, ect. in aes(), however, I'ed tried this many different times and many different ways, and it does not work for me.
If someone could help me, I would be so grateful!
My code is as follows:
Welcome! I'm afraid you'll need to supply some more info in order for helpers to be able to understand your problem.
The best thing would be if you can make your question into a reproducible example (follow the link for instructions and explanations). To include your data, you'll want to follow one of the methods discussed here.
If you try all that and get stuck, here's a fallback option...
Edit your post and add in some of the code you have tried. It's OK it doesn't work! It's really helpful to see what you've been attempting. Be sure to format your code as code (it's hard to read unformatted code, and it can get garbled by the forum software)
Include sample data:
If your data set is OK to share, run the following line and paste the output into your post. Again, be sure to format it as code
dput(head(your_dataframe_name, 10))
If your data set can't be shared, run this line instead and paste the output into your post (and yes, format as code!) This will still share some information about your data. If it's truly confidential, I'm afraid you'll need to make a fake sample dataset to share.
Sorry, I should have clarified. I have all of the bars the same color and the line is a different color and I want a legend to represent that. So say, orange for the line and blue for the bars.
I think this is what you are looking for? Because in general ggplot2 doesn't really encourage secondary axes, I'm not sure if there is a cleaner way to do it.
library(tidyverse)
df <- tibble(
Day = c("1", "2", "3"),
Tests = c(25, 15, 30),
Rate = c(50, 20, 66)
)
df %>%
ggplot() +
geom_col(aes(x = Day, y = Tests, fill = "Bars")) +
geom_line(aes(x = Day, y = Rate * 0.33, color = "Line"), group = 1) +
scale_y_continuous(sec.axis = sec_axis(~.*3, name = "Rate of Positive Tests")) +
scale_fill_manual(name = NULL, values = c("Bars" = "blue")) +
scale_color_manual(name = NULL, values = c("Line" = "orange"))