在R中的ggplot2中更改第二组的标题

时间:2016-08-12 16:51:50

标签: r ggplot2

假设我有一个带有三个参数x,y,z的function_3d。假设该函数定义如下:

function_3d <- function(x, y, z) {
  return(x + y * 10 + z * 100)
}

我正在使用ggplot2为seq(0,10,1)中的x绘制此函数,而y具有来自c(1,3,5,7)的值,z具有来自c的值(2,4,6) )。

这是我的方法:

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")) 

结果是:

Plot of function_3d

现在我有两个问题:

1)如何更改y组的标签(我的意思是更改因子(group_y)文本)?

2)有没有更好的方法来创建这个情节?

2 个答案:

答案 0 :(得分:1)

您可以使用完全针对这种情况制作的expand.grid,大大简化data.frame的创建。

我不知道为什么你需要在你的ggplot中进行group_y, group_z的互动?

我将做的是以下内容:

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")

答案 1 :(得分:0)

1)最后添加'+ scale_linetype_discrete(name ='foo')

2)对我来说似乎很好ggplot2 ^^