2017-09-21 2 views
0

私はR種の「折れ線グラフ内の複数行」のチャートを作成しています。同じチャート内に5個ずつ6個のベクトルをプロットしたいと思います。折れ線グラフの複数の行に複数の行を追加しますか?

問題は、私は3行をプロットしようとすると2行以上をプロットしないことです。それは何も表示されません。

it1 <- c(1406, 1504, 1623, 1405, 1447) 
it2 <- c(1565, 1496, 1555, 1590, 1555) 
it3 <- c(459, 534, 534, 626, 626) 
it4 <- c(642, 643, 482, 661, 651) 
it5 <- c(538, 558, 456, 393, 551) 
it6 <- c(521, 517, 466, 456, 496) 

plot(it1,type="l",col="red") 
lines(it2, col="green") 
lines(it3, col="blue") #bad 

どのような問題がありますか?プロットの外に凡例をプロットするためにxを定義し、yは、プロットの外に位置座標:

答えて

0

matplot

it1 <- c(1406, 1504, 1623, 1405, 1447) 
    it2 <- c(1565, 1496, 1555, 1590, 1555) 
    it3 <- c(459, 534, 534, 626, 626) 
    it4 <- c(642, 643, 482, 661, 651) 
    it5 <- c(538, 558, 456, 393, 551) 


it = data.frame(it1, it2, it3, it4, it5) 

matplot(it, type = c("b"),pch=1,col = 1:5) 
legend("center", legend = 1:5, col=1:5, pch=1) 

EDITしてみてください。より多くのオプションについては?legendをチェックしてください。

par(xpd=TRUE) 
matplot(it, type = c("b"),pch=1,col = 1:5) 
legend(x = 2, y = 1850, legend = 1:5, col=1:5, pch=1, horiz= T) 

enter image description here

+0

こんにちは、あなたのソリューションのおかげで、どのように私はchの外に伝説を置くことができますアート? –

+0

こんにちはアレハンドロ、編集を確認してください。 – missuse

2

it3は完全に最初のプロットによって設定されたあなたの軸の範囲を下回ったので、それは現れていません。このような後続のプロットを追加すると、軸を再スケーリングせずに、最初のプロットに合わせて軸を使用します。最初のプロットで手動で軸範囲を指定すると、すべてが表示されます。しかし、私はこれを行うにはggplot2のようなものを使用することをお勧めします。

plot(it1,type="l",col="red", ylim = c(0, 1800)) 
lines(it2, col="green") 
lines(it3, col="blue") #now works 

あなたは一般的に使用されるggplot2パッケージでそれをやってみたかった場合は、long形式にデータを再構築する必要があります。 tidyrreshape2のようにこれによく使用されるいくつかのパッケージがあります。

it_lines <- data.frame(it1,it2,it3,it4,it5,it6) 
it_lines$index <- row.names(it_lines) 

# Reshape into long format for ggplot2 - requires tidyr, but can be done 
# with other approaches like reshape2's melt/cast 
it_lines <- tidyr::gather(it_lines, key = it, value = value, it1:it6) 

# Plot 
library(ggplot2) 
ggplot(it_lines, aes(x = index, y = value, group = it, colour = it)) + 
geom_line() 

+0

私はあなたが言っていることを理解しています、ありがとう! –

0

それとも、単にそれらのすべてをプロットし、matplotlibよりも立派に見える何かを作るためにggplot2といくつかのtidyverseツールを使用することができます:

it1 <- c(1406, 1504, 1623, 1405, 1447) 
it2 <- c(1565, 1496, 1555, 1590, 1555) 
it3 <- c(459, 534, 534, 626, 626) 
it4 <- c(642, 643, 482, 661, 651) 
it5 <- c(538, 558, 456, 393, 551) 
it6 <- c(521, 517, 466, 456, 496) 

library(tidyverse) 

data <- tibble(index = 1:5, it1,it2,it3,it4,it5,it6) %>% 
    gather(var, value, -index) 

ggplot(data, aes(x = index, y = value, colour = var)) + 
    geom_line() 

enter image description hereをそれは次のようになります

関連する問題