0

I have a plot with variables A (bars) and B (line) where legend is not showing. I have a couple of questions I'd like a hand with please:

  • Legend is not showing.
  • Location (x-axis) is only showing 3 of the 7

    My data:

)

Location <- c(1,2,3,4,5,6,7)
A <- c(0.81, 0.94, 2.31, 12.2, 11.52, 4.7, 10.13)
B <- c(3304, 97025, 187012, 25962, 383875, 96233, 227291)

df = data.frame(Location, A, B)

My code:

ggplot(df) + 
    geom_col(aes(Location, A), color = "black", fill = "tan1") +
    geom_line(aes(Location, B/40000), size = 1.5, color="black") +
    scale_y_continuous(sec.axis = sec_axis(~.*40000))

Trying to add the legend:

+ theme(legend.position = c(0.8, 0.2))+
        scale_fill_manual(name = "", values = c("A" = "grey")) +
        scale_color_manual(name = "", values = c("B" = "black")) +

        theme_bw()

enter image description here

Ecg
  • 908
  • 1
  • 10
  • 28

1 Answers1

3

I believe you want to make sure you have color in your aes to create the legend.

Also added guides to remove the fill from the black line in legend.

You can add breaks to scale_x_continuous to show all x-axis labels, if that's what you were looking for.

ggplot(df) + 
  geom_col(aes(Location, A, color = "A"), fill = "tan1") +
  geom_line(aes(Location, B/40000, color = "B"), size = 1.5) +
  scale_y_continuous(sec.axis = sec_axis(~.*40000)) + 
  scale_x_continuous(breaks = 1:7) +
  #theme(legend.position = c(0.8, 0.2))+
  #scale_fill_manual(name = "", values = c("A" = "grey")) +
  scale_color_manual(name = "", values = c("A" = "tan1", "B" = "black")) +
  theme_bw() +
  guides(color=guide_legend(override.aes=list(fill=c("tan1", NA))))

plot with legend

Ben
  • 28,684
  • 5
  • 23
  • 45