【问题标题】:How to smooth plots with different x-coordinates in ggplot?如何在ggplot中平滑具有不同x坐标的图?
【发布时间】:2014-03-20 13:32:24
【问题描述】:

我想用 ggplot 绘制算法随时间的运行情况,但我想将它们平滑成一条线并添加这些漂亮的丝带。就像这里(ggplot 手册中的 lattice 和 ggplot2,我找不到代码):

但是!我有 100 次运行,全部由 1000 个左右的数据点组成。问题是这些数据点都有不同的 x 坐标。所以我认为不能很好地计算平均值以获得这条平滑线?真的吗?

如果是这样,我想绘制 100 条平滑线,并以固定的间隔对它们进行采样(比如在 x=100、x=200 等处),然后用这些丝带生成平滑线并平均线(显示方差或 90 % 间隔左右)。

一旦在固定 x 坐标处对数据进行采样,我就可以执行以下操作:

data
months <- c(1:12)
 High <- c(-6,-2,5,14,21,26,28,27,22,14,4,-3)
Low <- c(-16,-11,-5,2,9,14,17,16,11,4,-4,-12)
Mean <- c(-11,-7,0,8,15,20,23,22,16,9,1,-7)
Prepmm <- c(26.4 ,20.1 ,47.2 ,58.7 ,82.3 ,110.2 ,102.6 ,102.9 ,68.3 ,53.6 ,49.3 ,25.4 )
Prep <- Prepmm * 0.1 # converting to cm
minptemp <- data.frame(months, High, Low, Mean, Prep)



# plot
require(ggplot2)  # need to install ggplot2 
plt <- ggplot(minptemp, aes(x= months))
plt + geom_ribbon(aes(ymin= Low, ymax= High), fill="yellow") + geom_line(aes(y=Mean))+
geom_point(aes(x = months, y = Prep)) + theme_bw( ) # ribbon plus point plot months

要获得:

如何对 100 条平滑线进行采样?这甚至可能吗?还是有别的办法?

我的数据如下所示:

run 1
x  y
1  100
4  90
7  85
10 80

run 2
x  y
1  150
2  85
10 60

等 100 次运行...

如您所见,不完整:

x1; y1  ; x2 ; y3
1 ; 100 ; 1  ; 150
4 ; 90  ; 2  ; 85
7 ; 85  ; 10 ; 60
10; 80  ;

如果取 x = 4 的平均值,是否会考虑第二次运行的值在 85 到 60 之间?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我决定先用 R 预处理数据:

    xx <- read.table(text='x1; y1  ; x2 ; y2
    1 ; 100 ; 1  ; 150
    4 ; 90  ; 2  ; 85
    7 ; 85  ; 10 ; 60
    10; 80  ;',sep=';',fill=TRUE,header=TRUE)
    
    dm <- merge(xx[,1:2],xx[,3:4],by=1,all=T)
    dm <- dm[!is.na(dm$x1),]
    dm$y1 <- zoo::na.locf(dm$y1)
    dm$y2 <- zoo::na.locf(dm$y2)
    dm
      x1  y1  y2
    1  1 100 150
    2  2 100  85
    3  4  90  85
    4  7  85  85
    5 10  80  60
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2023-01-26
      • 2022-01-25
      相关资源
      最近更新 更多