Soroosh - 1 year ago 43

R Question

Assume I have a function_3d with three parameters x, y, z . Assume the function is defined as the following:

`function_3d <- function(x, y, z) {`

return(x + y * 10 + z * 100)

}

I am plotting this function using ggplot2 for x in seq(0, 10, 1) while y has a value from c(1, 3, 5, 7) and z has a value from c(2, 4, 6).

Here is my approach:

`require('ggplot2')`

require('dplyr')

function_3d <- function(x, y, z) {

return(x + y * 10 + z * 100)

}

x_vec <- seq(0, 10, 1)

y_vec <- c(1, 3, 5, 7)

z_vec <- c(2, 4, 6)

allframes <-

lapply(z_vec, function(inp.z.val) {

(lapply(y_vec, function(inp.y.val)

{

data.frame(

x = x_vec,

y = function_3d(x = x_vec,

y = inp.y.val,

z = inp.z.val),

group_y = inp.y.val,

group_z = inp.z.val

)

}))

})

# Bind all the frames

# Note: we can use dply::bind_rows instead of rbind

df.out <- do.call(rbind, do.call(rbind, allframes))

ggplot(df.out,

aes(

x = x,

y = y,

shape = factor(group_y),

colour = factor(group_z),

group = interaction(group_y, group_z)

)) +

geom_line(aes(linetype=factor(group_y)), alpha = .9, size = 1) +

scale_x_continuous(name = "X Label") +

scale_y_continuous(name = "Y Label") +

ggtitle("Plot Title") +

scale_colour_brewer(palette = "Set1") +

labs(aes(colour = "Label of each plot z")) +

theme(legend.key.width=unit(3, "line"))

And the result is:

Now I have two questions:

1) How can I change the label of y group ( I mean change factor(group_y) text) ?

2) Is there a better way to create this plot?

Answer Source

You can drastically simplify the creation of your data.frame by using expand.grid which is made exactly for this situation.

I don't see why you need the interaction of `group_y, group_z`

in your ggplot?

What I would have done is the following:

```
library(ggplot2)
function_3d <- function(x, y, z) {
return(x + y * 10 + z * 100)
}
df.out <- expand.grid(x = seq(0, 10, 1),
group_y = c(1, 3, 5, 7),
group_z = c(2, 4, 6))
df.out$y <- function_3d(df.out$x, df.out$group_y, df.out$group_z)
ggplot(df.out, aes(x = x, y = y)) +
geom_line(aes(color = factor(group_z), linetype = factor(group_y))) +
xlab("Test label x") +
ylab("Test label y") +
ggtitle("testtitle") +
scale_color_brewer(palette = "Set1", name = "color label") +
scale_linetype_discrete(name = "linetype label")
```