2016-08-12 3 views
0

に変更します.3つのパラメータx、y、zを持つfunction_3dがあるとします。 Iは、配列中xのggplot2を使用してこの機能をプロットしていggplot2の2番目のグループのタイトルをR

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

(0、10、1)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

今、私は2つの質問があります。

1)どのように私は、yのラベルを変更することができますグループ(私は変更係数(group_y)テキストを意味する)?

2)このプロットを作成するには、より良い方法がありますか?終わりに追加

答えて

1

^^私には良いggplot2ですこの状況に対して正確に作成されたexpand.gridを使用します。

あなたの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") 
:私が行っているだろうか

は以下のとおりです。

0

1) '+ scale_linetype_discrete(名= 'FOO')

2)あなたが劇的にしてdata.frameの作成を簡素化することができます

関連する問題