我正在尝试为数据框的每一行制作一个折线图traff。x轴表示从2006年到2012年。
最终结果应该是每行单独的图形。在下面的示例中,第一张图代表第三条线,第二张图代表第二条线(请参见下表):

我知道如何找到每一行的最大值以获取最大yaxis与:
xaxis <- colnames (traff[,(3:10)])
Run Code Online (Sandbox Code Playgroud)
但是我正在努力使每一行循环并生成一个折线图。如您所见,每个端口(a,b和c)具有三个类别(IntPass,Pass和Cruise)。
Port Category 2006 2007 2008 2009 2010 2011 2012
a IntPass 9046000 0 9579000 9683700 10404900 0 0
a Pass 270000 260000 360000 360000 342000 385000 368000
a Cruise 259 238 269 263 247 258 265
b IntPass 8249304 8222336 8692362 9015726 9107665 9177075 9050424
b Pass 0 272584 351267 437437 381141 407162 463770
b Cruise 260 255 265 293 261 263 274
c IntPass 6760000 6514294 7247366 7257646 7900000 8500000 8800000
c Pass 305026 294738 377522 416605 392000 443000 442000
c Cruise 289 268 298 305 279 293 294
Run Code Online (Sandbox Code Playgroud)
您不应使用for循环将线绘制到图表中。如果您的类别变量是一个因素,则ggplot软件包会为您完成此操作。看下面的代码:
library(reshape2) #install.packages("reshape2")
library(ggplot2) #install.packages("ggplot2")
#Import data into a Data frame
data <- c("
Port Category 2006 2007 2008 2009 2010 2011 2012
a IntPass 9046000 0 9579000 9683700 10404900 0 0
a Pass 270000 260000 360000 360000 342000 385000 368000
a Cruise 259 238 269 263 247 258 265
b IntPass 8249304 8222336 8692362 9015726 9107665 9177075 9050424
b Pass 0 272584 351267 437437 381141 407162 463770
b Cruise 260 255 265 293 261 263 274
c IntPass 6760000 6514294 7247366 7257646 7900000 8500000 8800000
c Pass 305026 294738 377522 416605 392000 443000 442000
c Cruise 289 268 298 305 279 293 294
")
traff <- read.table(text = data, header=TRUE)
#Reshape the data for ggplot
traff2 <- melt(traff,id=c("Port","Category"),variable.name = "Year")
#Remove the X in the Year column and convert it to number
traff2$Year <- as.numeric(gsub(pattern="X",replacement = "",x = as.character(traff2$Year)))
#The data is ready for ggplot
head(traff2)
#ggplot it...
ggplot(traff2, aes(x = Year, y = value, color = Port))+
facet_grid(facets = Category~., scales = "free_y")+
geom_line()+theme_bw()
Run Code Online (Sandbox Code Playgroud)
结果:

| 归档时间: |
|
| 查看次数: |
3279 次 |
| 最近记录: |