2014-12-03 81 views
1

必須繪製從遠足/騎自行車路線的.gpx軌道計算出的高度計剖面,我有正常的XY圖,其中X是覆蓋的漸進距離,Y是高度:
我也知道軌道(瀝青,地面,鵝卵石,...)的每一段的表面,所以我data.table TRACKS的格式爲:
XY圖:使用不同顏色的x範圍

PROGDIST ALTITUDE SURFACE 
     50  110 asphalt 
    100  123 asphalt 
    150  146 asphalt 
    200  124 asphalt 
    250  141 asphalt 
    300  141 asphalt 
    350  148 ground 
    400  118 ground 
    450  120 ground 
     …   …  … 

我想以此信息豐富圖表, 獲得如下內容:

我試圖用的geom = C(「區域」,「行」)與qplot,並從GGPLOT2 GEOM =「絲帶」,但我的這些包的實際知識是不夠的,所以任何幫助將受到歡迎!

回答

1

使用你的數據,這是一種方式,你可以做到這一點:

df <- read.table(header=T,text=" 
PROGDIST ALTITUDE SURFACE 
50  110 asphalt 
100  123 asphalt 
150  146 asphalt 
200  124 asphalt 
250  141 asphalt 
300  141 asphalt 
350  148 asphalt #you need to add this line in your data so that the colouring goes up to 350 and not stop at 300. #remove this comment to run read.table() 
350  148 ground 
400  118 ground 
450  120 ground") 

ggplot(aes(x=PROGDIST,y=ALTITUDE) , data=df) + geom_line() + 
    geom_ribbon(data=subset(df, SURFACE=='asphalt') , aes(ymax=ALTITUDE) ,ymin=0, fill='red', colour=NA, alpha=0.5) + 
    geom_ribbon(data=subset(df, SURFACE=='ground') , aes(ymax=ALTITUDE) ,ymin=0, fill='blue', colour=NA, alpha=0.5) 

enter image description here

但是,請注意你的數據,你需要添加一個額外的行來實現這個圖表,否則你會在情節中有一個缺口。檢查上面的評論。

希望它有幫助。

+0

非常感謝你Lyzande!而且,我還沒有在表格中添加這些行,我已經擁有它們了! :-) (我的例子是一個簡單的例子,但在註冊GPS軌道時暫停/恢復,將它分成幾段,中斷點被註冊兩次:作爲舊段的最後一點,作爲新段的第一點) – mbranco 2014-12-03 11:30:23

1

您可以輕鬆地在ggplotfill選項做到這一點。但你首先必須改變你的數據,使變化點獨特:

# original data 
df <- read.table(text = 'PROGDIST ALTITUDE SURFACE 
     50  110 asphalt 
    100  123 asphalt 
    150  146 asphalt 
    200  124 asphalt 
    250  141 asphalt 
    300  141 asphalt 
    350  148 ground 
    400  118 ground 
    450  120 ground', header=TRUE) 
# find points where SURFACE changes 
df.change <- df[diff(as.numeric(df$SURFACE)) > 0, ] 
df.change$SURFACE <- df[c(0, diff(as.numeric(df$SURFACE))) > 0, "SURFACE"] 
# add points with new surface to plot 
df.new <- rbind(df, df.change) 
df.new <- df.new[order(df.new$PROGDIST), ] 
# plot 
ggplot(df.new, aes(PROGDIST, ALTITUDE)) + 
    geom_line() + 
    geom_ribbon(aes(ymin=0, ymax=ALTITUDE, fill=SURFACE)) + 
    theme_bw() 
+0

也謝謝你,我也想嘗試你的解決方案,即使看起來有更多的計算 – mbranco 2014-12-03 11:40:34