2
votes

I'm trying to do something that I think should be simple, but has taken me all morning to do! I want to plot regression lines on a figure and then add a one to one line (1:1) on the figure too. The legend should have 5 lines, four derived from the data and one created from outside the data. I have almost all but figured out how to label the lines and color them, but I can't seem to set the linetype. ggplot seems to have 2 overlapping linetypes for the dashed line: one short fat line overtop the skinny dashed line I want. How can I make the dashed line appear dashed in the legend?

Here's some example code to help diagnose the problem.

dat <- data.frame(Automatic_count = rnorm(100), Manual_count=rnorm(100), Dataset=c(rep("cuticle_db_test",25), rep("ginkgo_test", 25), rep("forty_x_test",25), rep("twenty_x_test",25)))

p1 <- ggplot(dat, aes(x=Automatic_count, y=Manual_count)) +
  geom_point() +
  geom_smooth(data=dat,aes(fill=Dataset, colour=Dataset), method='lm', se=FALSE) +
  scale_color_manual(values=c("red","#F8766D","#7CAE00","#00BFC4","#C77CFF"),
                     labels=c("Cuticle Database", "40x", "Ginkgo", "20x","1:1"),
                     breaks=c("cuticle_db_test","forty_x_test","ginkgo_test","twenty_x_test","1:1"),
                     name="Dataset",
                     guide=guide_legend(override.aes=list(linetype=c(1,1,1,1,2)))) +
  geom_segment(aes(x=-2,y=-2,xend=2,yend=2,colour='1:1'), linetype=2, show.legend = TRUE) +
  guides(fill=FALSE) +
  ylab("Human Count") +
  xlab("Automatic Count")

Output of the above code

Thanks in advance!

1

1 Answers

3
votes

You need to specify the linewidth lwd in guide_legend, e.g.

p1 <- ggplot(dat, aes(x=Automatic_count, y=Manual_count)) +
  geom_point() +
  geom_smooth(data=dat,aes(fill=Dataset, colour=Dataset), method='lm', se=FALSE) +
  scale_color_manual(values=c("red","#F8766D","#7CAE00","#00BFC4","#C77CFF"),
                     labels=c("Cuticle Database", "40x", "Ginkgo", "20x","1:1"),
                     breaks=c("cuticle_db_test","forty_x_test","ginkgo_test","twenty_x_test","1:1"),
                     name="Dataset",
                     guide=guide_legend(override.aes=list(linetype=c(1,1,1,1,2), lwd=c(1,1,1,1,0.5)))) +
  geom_segment(aes(x=-2,y=-2,xend=2,yend=2,colour='1:1'), linetype=2, show.legend = TRUE) +
  guides(fill=FALSE) +
  ylab("Human Count") +
  xlab("Automatic Count")