Rspacer
Rspacer

Reputation: 2429

How to segregate by one factor but colour by another in ggplot2 R?

In my dataset, I have segregated the data by a parameter par for either Black or Red noise that are staggered in represtation. Now, for both species, I want to colour the "Black" noise as black, and "Red" as red. Furthermore, I want to join the points by par -- specifically, I want to join par -- No with a Dashed line, and Yes as a solid line. I tried the piece of code attached (and multiple versions of it)..but no luck. Any suggestions?

#Data

set.seed(100)
sp <- factor(c("A","A","A","A","B","B","B","B"))
par <- factor(c("No","No","Yes","Yes","No","No","Yes","Yes"))
y <- rnorm(8, 2,3)
noise <- factor(c("Black","Red","Black","Red","Black","Red","Black","Red"))

df <- data.frame(sp, par, y, noise)
df$noise <- factor(df$noise, levels = c("Black","Red"))

enter image description here

  library(ggplot2)
    ggplot(data = df, aes(x = noise, y = y, fill = par, color = par)) +
      geom_point(size = 4) + 
      facet_wrap(.~sp) +
      theme_classic() + 
      scale_fill_manual(values = c("black","red")) +   scale_color_manual(values = c("black","red")) +  
      geom_line(aes(linetype=par)) + scale_linetype_manual(name = "indicator", values = c(2,1,2))
      geom_path(aes(group = par,linetype=par), geom = "path") 
      

ERROR: geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

Upvotes: 0

Views: 105

Answers (1)

benson23
benson23

Reputation: 19142

In your code, you forget to add a + to link geom_path() with the ggplot(). Since the aes() of geom_point() and geom_path() doesn't match, you'll need to include them in the corresponding geom_*().

library(tidyverse)

ggplot(data = df, aes(x = noise, y = y, group = par, linetype = par)) +
  geom_point(aes(fill = noise, color = noise, ), size = 4) + 
  facet_wrap(.~sp) +
  theme_classic() + 
  scale_fill_manual(values = c("black","red")) +
  scale_color_manual(values = c("black","red")) +  
  geom_line() + 
  scale_linetype_manual(name = "indicator", values = c(2,1,2)) +
  geom_path() 

geom_group

Upvotes: 2

Related Questions