2017-09-21 33 views
0

我正在做一个R类'折线图中的多条线'的图表,我想绘制6个向量,每个图表中有5个数字。在折线图中添加多行中的多行?

问题是我没有绘制超过2行,当我尝试绘制第3行时,它不显示任何东西。

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 

我有什么问题?

回答

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) 

编辑:绘制情节之外传说定义xy协调情节之外。检查?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

或者你可以简单地使用ggplot2有的tidyverse工具来绘制所有这些,使一些看起来更好比matplotlib

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