【问题标题】:How can I generate data from a plotted line in R?如何从 R 中的绘制线生成数据?
【发布时间】:2021-01-07 23:28:48
【问题描述】:

我没有数据集,只有两条绘制线,我想生成距离平均值 2 个标准差的分散 y 轴数据(绘制线)。这是我的代码:

ggplot() +
 lims(x = c(0,20), y = c(0,1)) + 
 annotate("segment",x = .1,xend = 5, yend = .25, y = .1) +
 annotate("segment",x = 5,xend = 20, yend = .35,y = .25)

对不起,如果这篇文章不清楚,但我不确定解释它的最佳方式。如果您有任何问题或者我想要做的事情是不可能的,请告诉我。

【问题讨论】:

  • 您尝试做的事情是可能的。 1)将线条拟合到您的段(这样您就可以得到每个段的 y=ax+b) 2)选择 x 值来获得您称为“平均值”的 y 值。 3) 对你的每个 x 使用 rnorm(n, mean) 以便你得到你想要的分布
  • 好的,我有点明白你在说什么。 1)我找到了斜率(0.09 和 0.0067)并且我改变了我的线,所以截距为 0 以简化事情。 2)我的 x 值离散为 1:20。我知道我可以将它们代入方程以找到 y。 3) 我不明白这一步的内容或原因。
  • 第 3 个是根据您的要求,即围绕每个 y(x) 值生成分散数据。你应该插入任何你想要的sd

标签: r scatter standard-deviation line-plot data-generation


【解决方案1】:

这是您拥有的其中一行的示例(我没有仔细检查 y = 0.09*x + 0 是否与您显示的内容一致,指导我从您的评论中回答)。

library(ggplot2)
library(dplyr)

df <- tibble(x=1:20,
       y1=0.09*x,
       y2=0.0067*x)

# generate dots for y1
# mean y1 and sd = 1

sapply(df$y1, function(tt) rnorm(10, tt)) %>% 
  # make it into tibble
  as_tibble() %>% 
  # pivot into longer format
  tidyr::pivot_longer(everything()) %>% 
  # names of the columns get assigned to V1 V2 ... 
  # we can clean that and get the actual x
  # this works nicely because your x=1:20, will fail otherwise
  mutate(X=as.numeric(stringr::str_remove(name, "V"))) %>%  
  # plot the thing
  ggplot(aes(X, value)) +
  geom_point() +
  # add the "mean" values from before
  geom_point(data=df, aes(x, y1), col="red", size=2)

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2015-09-25
    相关资源
    最近更新 更多