2012-09-08 106 views
6

我在ggplot2中有一個線圖,我想爲每個數據行添加點(=形狀)以清楚地標識它。我不需要(!)在每個數據點都需要一個形狀/點,但是一些值就足夠了。請看下面的例子:ggplot2:將點添加到geom_line

library(ggplot2) 
library(data.table) 
d=data.table(x=seq(0, 100, by=0.1), y=seq(0,1000))) 
ggplot(d, aes(x=x, y=y))+geom_line() 
ggplot(d, aes(x=x, y=y))+geom_line()+geom_point() 

Line Only With added points

由於樣本數量巨大,形狀是不可見的了,但透支了對方。我只需要其中一些,或許等距離的間距看起來最好,但我願意接受任何其他解決方案。

+0

見[這個問題](http://stackoverflow.com/questions/6893959/r-how-do-i-draw-a-line -with-multiple-arrows-in-it/6904434#6904434)把一條線分成等間距點 – baptiste

+0

當然答案應該取決於你是否有簡單的直線或曲線路徑 – baptiste

回答

8

您也可以通過索引加點分,只是瘦了數據。

library(ggplot2) 
library(data.table) 
d=data.table(x=seq(0, 100, by=0.1), y=seq(0,1000)) 
ggplot(d, aes(x=x, y=y))+geom_line() 
#Change the length parameter for fewer or more points 
thinned <- floor(seq(from=1,to=dim(d)[1],length=70)) 
ggplot(d, aes(x=x, y=y))+geom_line()+geom_point(data=d[thinned,],aes(x=x,y=y)) 

enter image description here

5

你可以用quantile來繪製某些分位數的點。例如,以下序列生成十進制。

quantile(rnorm(100), probs = seq(0, 1, .1)) 
#   0%   10%   20%   30%   40%   50%   60%   70%   80%   90%  100% 
#-2.43934306 -1.17208001 -0.91497203 -0.69489868 -0.46306926 -0.24133438 -0.03434118 0.39989589 0.72331902 1.06402664 2.02892420 

library(ggplot2) 
library(data.table) 
d <- data.table(x = seq(0, 100, by=0.1), y = seq(0,1000)) 

ggplot(d, aes(x=x, y=y))+ 
geom_line()+ 
geom_point(aes(x = quantile(x, probs = seq(0, 1, .1)), 
       y = quantile(y, probs = seq(0, 1, .1)))) 

Plot with points at deciles

2

只是想添加一個data.table解決方案,可以使用分組數據以及工作:

library(ggplot2) 
library(data.table) 

# Creates data from the Weibull distribution 
weib_dt <- function(x = seq(0, 4.0, 0.01), w_shape = 1, w_scale = 1) { 
    y = dweibull(x, shape = w_shape, scale = w_scale) 
    data.table("shape" = as.factor(w_shape), "scale" = as.factor(w_scale), "x" = x, "y" = y) 
} 

dt_a <- weib_dt(w_shape = 0.5) 
dt_b <- weib_dt(w_shape = 1.0) 
dt_c <- weib_dt(w_shape = 2.0) 
# Bind multiple Weibull samples together, created from different parametrizations 
dt_merged <- rbindlist(list(dt_a, dt_b, dt_c)) 

# Create the plot, using all the points for the lines, and only 9 points per group for the points. 
ggplot(dt_merged, aes(x, y, group=shape, color=shape)) + 
    coord_cartesian(ylim = c(0, 1.5)) + 
    geom_line() + 
    geom_point(data=dt_merged[, .SD[floor(seq(1, .N, length=9))], by=shape], 
      aes(x, y, group = shape, color = shape, shape = shape)) 

這裏的技巧是利用seq與上述建議的解決方案,但是這次它在組內完成(使用.SD)。請注意,目前.SD的性能可能不佳,如果速度較慢,則可以使用更詳細的dt[dt[, ..., by =shape]$V1]

這將產生下面的輸出:

Weibull plots