在R / ggplot2中给定连续x,生成y的条件均值的图

时间:2017-04-01 23:50:35

标签: r ggplot2

我想在R中创建一个线图,显示给定x范围的y的条件均值,其中x均匀分布在0和1之间。我希望能够指定bin宽度为1%点宽,所以我的线将有100个数据点。我特别想知道如何在ggplot2中完成这项工作。

x=runif(10000,0,1)
y=rnorm(10000,50,10)
plot(x,y)

创建散点图会产生10000个点,这会使解释变得困难。

1 个答案:

答案 0 :(得分:1)

使用extension String { // Separate alphanumeric characters func split(_ number: Int = 1) -> [String] { let number = max(number, 1) return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { $0.characters.count > number - 1 } } } let string = "Appetizer: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3) * Main: (300: 50), (300: 90), (300: 100a), (300: D), (300: E) * Dessert: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)" let values = string.components(separatedBy: "*").map { $0.split() } var result: [String: [Int: [String]]] = [:] values.forEach { guard let key = $0.first else { return } result[key] = result[key] ?? [:] let values = $0.dropFirst() let name = values.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 } let code = values.enumerated().filter { $0.0 % 2 != 0 }.map { $0.1 } zip(name, code).forEach { guard let category = Int($0.0) else { return } result[key]?[category] = (result[key]?[category] ?? []) + [$0.1] } } n = 100(对于100个均匀分布点进行评估)对您来说已经足够了:

ggplot2::stat_smooth()

enter image description here