Problems using ggplot aes_string, group and linetype

Let's say I have this dataset:

x <- rnorm(1000) y <- rnorm(1000, 2, 5) line.color <- sample(rep(1:4, 250)) line.type <- as.factor(sample(rep(1:5, 200))) data <- data.frame(x, y, line.color, line.type) 

I am trying to build a group of x and y variables when line.type and line.color interact. In addition, I want to specify the type of line using line.type and color using line.color. If I write this:

 ggplot(data, aes(x = x, y = y, group = interaction(line.type, line.color), colour = line.color, linetype = line.type)) + geom_line() 

This works, but if I try to use aes_string like this:

 interact <- c("line.color", "line.type") inter <- paste0("interaction(", paste0('"', interact, '"', collapse = ", "), ")") ggplot(data, aes_string(x = "x", y = "y", group = inter, colour = "line.color", linetype = "line.type")) + geom_line() 

I get an error message:

 Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line 

What am I doing wrong? I need to use aes_string because I have many variables to build.

+2
source share
2 answers

You almost defined a definition

 inter <- paste0("interaction(", paste0('"', interact, '"', collapse = ", "), ")") 

However, for aes_string to work aes_string you need to pass a character string of what will work if you called aes , i.e. you don't need to have arguments in interaction as strings. You want to create the line "interaction(line.color, line.type)" . therefore

  inter <- paste0('interaction(', paste0(interact, collapse = ', ' ),')') # or # inter <- sprintf('interaction(%s), paste0(interact, collapse = ', ')) # the result being inter ## [1] "interaction(line.color, line.type)" # and the following works ggplot(data, aes_string(x = "x", y = "y", group = inter, colour = "line.color", linetype = "line.type")) + geom_line() 
+2
source

Turns out I was wrong on a few points in my comments above. It works:

 data$inter <- interaction(data$line.type,data$line.color) ggplot(data, aes_string(x = "x", y = "y", group = "inter",colour = "line.color",linetype = "line.type")) + geom_line() 

(I was completely wrong about the graph defining the color, etc. within the same dashed line).

I take this as a small excuse, although relying on parsing the interaction code inside aes_string() is generally a bad idea. I assume ggplot has a small mistake to analyze what you give aes_string() in complex cases, forcing it to evaluate things in an order that makes it look like you are asking for aesthetics to change along the dotted / dashed lines.

+3
source

All Articles