1

I have 2 simple scatterplot datasets that I combined, and the resulting graph (in ggplot2) is exactly what I want except for the lines connecting the data. I'm trying to make it so there are two separate dashed lines with two different colors, but right now messing around with geom_line I'm only getting one line that connects all of the datasets. Below I'll attach my code and my desired/current outcome for the graph. I appreciate any help!

dfplus<-data.frame(Mean=c(2.20e7,6.18e7,3.28e7,3.46e8,1.09e9),
               sd=c(0e0,1.05e8,4.45e7,2.26e7,0e0),Category=c("2","3","4","5","6"))
dfminus<-data.frame(Mean=c(1.86e7,3.92e6,1.30e7,8.10e7,3.20e8),
                   sd=c(0e0,5.28e6,2e7,1.41e7,0e0),Category=c("2","3","4","5","6"))

dat <- rbind(dfplus, dfminus)
dat$dataset <- factor(c(rep("dfplus", dim(dfplus)[1]), rep("dfminus", dim(dfminus)[1])))
ggplot(dat, aes(x=Category, y=Mean, color=dataset, line=dataset,group=1))+ 
scale_color_manual(values=c('#56B4E9','#E69F00'))+geom_point(size=5,shape=21,aes(color=dataset))+
theme_classic()+geom_line()

Here's my desired graph (made in MS paint, imagine the lines are dashed): enter image description here Here's my current graph: enter image description here

  • 2
    Use group =dataset and not the 1 – Dave2e Jan 26 '22 at 03:28
  • FYI, three ways to automatically assign `dataset` *programmatically* instead of having to do it manually: (1) `dat <- rbind(transform(dfplus, dataset="dfplus"), transform(...))`, a little cumbersome. (2) `dat <- dplyr::bind_rows(dataset::lst(dfplus, dfminus), .id="dataset")`. (3) `dat <- data.table::rbindlist(list(dfplus=dfplus, dfminus=dfminus), idcol="dataset")`. – r2evans Jan 26 '22 at 03:32

1 Answers1

2

You were right there! Instead of group = 1, use group = dataset.

ggplot(dat, aes(x=Category, y=Mean, color=dataset, 
                line=dataset,group= dataset))+ 
  scale_color_manual(values=c('#56B4E9','#E69F00'))+
  geom_point(size=5,shape=21,aes(color=dataset))+
  theme_classic()+geom_line()

enter image description here

Kat
  • 15,669
  • 3
  • 18
  • 51