循环中的多线图

时间:2016-02-18 13:43:27

标签: r loops plot

我在每个国家/地区都有不同国家,不同年份和不同价值的数据。我试图为每个国家绘制几个多线图(线条是这些变量/年)。

由于某些未知原因,当我运行以下命令时,我得到的图表是空的:

par(mfrow=c(5,5))
mysplits<-split(A,A$country)
for (ii in 1:length(mysplits)) {
  adf<-mysplits[[ii]]
  snames<- names(mysplits)[ii]
  p<-plot(1, 
       main=paste(snames),
       type = "n", xlim=c(1993,2015),
       ylab = "value", xlab="years", ylim=c(-50,50))
  lines(adf$year, adf$tone, col = "steelblue", lty=5)
  lines(adf$year, adf$articles, col = "pink", lty=2) 
  lines(adf$year, adf$num, col = "red", lty=3) 
  lines(adf$year, adf$gold, col = "green", lty=6)
  legend("bottomright", legend = c("EPE Public","Tone","Coverage","No of Events",
  "Conflictual"), col = c("black","steelblue","pink","red","green"),
     lty = c(1,5,2,3,6),
     cex = 1.5, seg.len=4)
     }

以下是dput(head(A))的输出:

structure(list(X = 1:6, country = structure(c(1L, 1L, 1L, 1L, 
1L, 1L), .Label = c("AU", "BE", "BU", "DA", "EN", "EZ", "FI", 
"FR", "GM", "HR", "HU", "IT", "LG", "LH", "LO", "LU", "MT", "NL", 
"PL", "RO", "SI", "SP", "SW"), class = "factor"), year = 1994:1999, 
gold = c(-0.571428571, -2.4, 1.26, -0.2, -0.966666667, 0.316666667
), tone = c(324L, 239L, 251L, 72L, 61L, 159L), articles = c(3.571428571, 
4.5, 8.2, 4.6, 9.333333333, 6.166666667), num = c(7L, 4L, 
5L, 5L, 6L, 6L), yepe = 1995:2000, couepe = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("AU", "BE", "BU", "DA", "EN", 
"EZ", "FI", "FR", "GM", "HR", "HU", "IT", "LG", "LH", "LO", 
"LU", "MT", "NL", "PL", "RO", "SI", "SP", "SW"), class = "factor"), 
epepub = c(2.01, 1.87, 0.55, 0.63, 0.52, 0.82), epepriv = c(NA, 
NA, 2.63, 2.71, 2.59, 2.12), epeind = c(0.65, 0.66, 0.72, 
0.63, 0.57, 0.53)), .Names = c("X", "country", "year", "gold", 
"tone", "articles", "num", "yepe", "couepe", "epepub", "epepriv", 
"epeind"), row.names = c(NA, 6L), class = "data.frame")

以下是我的数据图片:

Header data

1 个答案:

答案 0 :(得分:1)

我非常高度,强烈建议在尝试在R中进行复杂的绘图时远离基础绘图包。您的问题是,在Laterow指出,par(mfrow=c(5,5))调用。而不是试图调试那里出了什么问题。请考虑使用ggplot,这是一个更强大,可读和灵活的库,用于执行r绘图。用Hadley Wickham的话来说,〜&#34;基础R绘图用于创建绘图,ggplot用于理解数据&#34;

例如,我相信您尝试生成的图表可以通过以下方式完成。注意,没有for循环。一般来说,在R中,如果你使用的是for循环,那么你做错了。另请注意,它大约有一半的代码行,并且比您最初组合的内容更具可读性。

library(ggplot2)
ggplot(A, aes(x=year)) + 
  geom_line(aes(y=tone, colour="Tone")) + 
  geom_line(aes(y=articles, colour="Coverage")) + 
  geom_line(aes(y=num, colour="No of Events")) +
  geom_line(aes(y=gold, colour="Conflictual")) + 
  facet_wrap(~country) + 
  scale_colour_manual("Legend", 
                      breaks = c("Tone", "Coverage", "No of Events", "Conflictual"),
                      values = c("steelblue", "pink", "red", "green")) +
  xlab("value") + 
  ylab("years")

产地:

Graph

请注意,您的示例数据仅包含&#34; AU&#34;国家。但是,无论此字段中有多少个国家/地区,这都将自动包裹您。这比我有25个国家静态地说更强大,这似乎是你在原始尝试中所做的。