[英]Multiple line plot in a loop
我有不同國家/地區,不同年份的數據,以及每個國家/地區年份的多個變量的不同值。 我正在嘗試繪制每個國家的多個線圖(線是這些變量/年)。
由於某些未知的原因,當運行以下命令時,我得到的圖是空的:
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")
這是我的數據的圖像:
我高度,高度,強烈建議在嘗試在R中進行復雜繪圖時不要使用基礎繪圖軟件包。Laterow指出,您的問題是使用par(mfrow=c(5,5))
調用。 而不是嘗試調試那里出了什么問題。 請考慮使用ggplot,它是用於進行r繪圖的更健壯,易讀和靈活的庫。 用Hadley Wickham的話來說,〜“基礎R繪圖用於創建圖形,ggplot用於理解數據”
例如,我相信您嘗試生成的圖形可以通過以下方式實現。 注意,沒有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")
產生:
請注意,您的樣本數據僅具有“ AU”國家/地區的值。 但是,無論該領域中有多少國家/地區,這都將自動包裹您的各個方面。 which appears to be what you were doing in the original attempt. 這比必須靜態地說 (似乎是您在最初嘗試中所做的事情)要強大得多 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.