1

I want to use ggplot to show points and lines, but I want there to be two legends - one for the points and one for the lines.

I managed to do this using the below code, but for some reason the 'size' option no longer responds in geom_point and they are stuck at the fairly ugly size you can see in the image .

Note that I chose stroke = NA because I do not want the points to have a border. The code is below.

Any ideas?

ggplot(data = plot_data) +
    geom_point(aes(x = z.1, y = obs, fill = treatcat), alpha = 0.4, shape = 21, stroke = NA, size = 1) +
    geom_line(aes(x = z.1, y = under, colour = "True"), linetype = "dashed") +
    geom_line(aes(x = z.1, y = crude, colour = "Crude"), size = 1.5) +
    scale_fill_manual(name = "Treatment",
                        values = c("0" = "#F8766D", "1" = "#C77CFF"),
                        breaks = c("0", "1"),
                        labels = c("Untreated", "Treated")) + 
    scale_colour_manual(name = "Model",
                        values = c("Crude" = "orange", "True" = "black"),
                        breaks = c("Crude", "True"),
                        labels = c("Crude", "True")) + 
    ylim(-30,27.5) +
    theme(plot.title = element_text(size = "12")) +
    labs(title = "Fitted Values for Crude Model", x = "Z", y = "Y(1)")
tjebo
  • 21,977
  • 7
  • 58
  • 94
Roger Hill
  • 13
  • 2
  • you've got size outside of aes - this makes then no legend. Not sure if this is what you want. In order to avoid any strokes, I am using `see::geom_point2` – tjebo Feb 15 '21 at 11:16

2 Answers2

0

Maybe you want two color scales, here a solution with ggnewscale. There are a couple of github packages with similar functionality on the horizon (relayer, and ggh4x), but currently this is the only CRAN option to my knowledge.

As per comment - I am using see::geom_point2 because I also don't like those strokes

library(ggplot2)
library(see)

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point2(aes(color = Petal.Width), alpha = 0.4, size = 10) +
  ggnewscale::new_scale_color() +
    geom_smooth(aes(color = Species), linetype = "dashed", method = "lm") 
tjebo
  • 21,977
  • 7
  • 58
  • 94
0

Currently, there is a bug in ggplot2 that makes it impossible to change size once stroke = NA (https://github.com/tidyverse/ggplot2/issues/4624). Apprarently, setting 'stroke = 0' also does not eliminate the border.

To do what you want, you need to set set color to 'transparent':

library(ggplot2)
df = data.frame(x=rnorm(100), y=rnorm(100))
ggplot(df, aes(x, y)) + geom_point(shape=21, stroke=0, fill="orange", color="transparent", size=8)

Created on 2021-09-20 by the reprex package (v2.0.1)

themeo
  • 162
  • 1
  • 9