0

I am trying to create a legend for my scatterplot however, the colors do not match. Rather the output is displayed like the image below. plot output

Any help is appreciated, thank you!

Here is my code:

ggplot() +
  geom_point(data = dfreq, aes(x = as.numeric(month), y = dnorm, color = "Dallas"), shape = 21, fill = "#899AD6", size = 3) + 
  geom_line(data = dfreq, aes(x = as.numeric(month), y = dnorm, color = "Dallas")) +
  geom_point(data = lfreq, aes(x = as.numeric(month), y = lnorm, color = "Los Angeles"), shape = 21, fill = "#E47080", size = 3) +
  geom_line(data = lfreq, aes(x = as.numeric(month), y = lnorm, color = "Los Angeles")) +
  ggtitle("Crime by Month in Dallas vs. Los Angeles") +
  xlab("Month") + ylab("Frequency of Crime") +
  scale_color_manual(name = "City", values = c("Dallas" = "#899AD6", "Los Angeles" = "#E47080")) +
  theme(axis.text = element_text(size = 7)) +
  scale_x_continuous(name = "Month", breaks = 1:12, labels = month.name[1:12])
stefan
  • 90,330
  • 6
  • 25
  • 51
ari
  • 1
  • 1
  • 1
    your plotting approach is ineffective. Your data seems to have the same column names. Merge your data and plot those lines / dots following the suggestions for example in this thread.https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph (and in this case only do not follow Hadley's advice) – tjebo Apr 18 '23 at 19:30
  • 1
    Also useful, arguably the same, but maybe from a different perspective: https://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot – tjebo Apr 18 '23 at 19:33
  • Drop `shape = 21, fill = "#899AD6"` from your code and you should be fine. Nonetheless the proper `ggplot2` way would be to bind your datasets into one using e.g. `dat <- list("Dallas" = dfreq, "Los Angeles" = lfreq) |> lapply(dplyr::rename, norm = 2) |> dplyr::bind_rows(.id = "city")`. Doing so you could simplify your plotting code as you now have a city column which could be mapped on `color` and you can create your plot with just one geom_line and geom_point. – stefan Apr 18 '23 at 22:07

0 Answers0