我正在尝试使用以下代码创建一个图以显示不同的饱和度水平及其对通话采样动态的影响:
max <- 2
decay <- function(x, k, C) {
C * (1 - exp(-k*x))
}
require("ggplot2")
ggplot(NULL, aes(x=x, colour = C)) +
stat_function(data = data.frame(x = 0:max, C = factor(1)), fun = function(x) { decay(x, k=10, C=1e1) }) +
stat_function(data = data.frame(x = 0:max, C = factor(2)), fun = function(x) { decay(x, k=10, C=1e2) }) +
stat_function(data = data.frame(x = 0:max, C = factor(3)), fun = function(x) { decay(x, k=10, C=1e3) }) +
stat_function(data = data.frame(x = 0:max, C = factor(4)), fun = function(x) { decay(x, k=10, C=1e4) }) +
stat_function(data = data.frame(x = 0:max, C = factor(5)), fun = function(x) { decay(x, k=10, C=1e5) }) +
stat_function(data = data.frame(x = 0:max, C = factor(6)), fun = function(x) { decay(x, k=10, C=1e6) }) +
scale_colour_manual(values = c("red", "orange", "yellow", "green", "blue", "violet"), labels = c(1, 2, 3, 4, 5, 6)) + scale_colour_discrete(name=expression(paste(C, " value"))) +
ylab(label="count") + ylim(0, 100)
Run Code Online (Sandbox Code Playgroud)
目的是表明对于高C值情况,曲线将显示为线性。但是,当我希望仅将曲线截断为最大值时,ylim会阻止显示任何曲线,而该曲线的值大于ylim的最大值。
如何获得所需的行为?
您已经注意到限制scale(使用scale_y_continuous(limits=...))或限制坐标空间(使用)之间的区别coord_cartesian(ylim=...)。
当您调用ylim它时,它使用的等效项scale_y_continuous并丢弃不在范围内的观测值
对此的帮助ylim和xlim描述(并指出coord_cartesian替代方法)
# here is your example rewritten
ggplot(data = NULL, aes(x=x,colour=C)) +
lapply(1:6, function(y){
stat_function(data = data.frame(x=0:max,C=factor(y)),
fun = function(x) decay(x,k=10, C = 10^y))) +
scale_colour_manual(values = c("red", "orange", "yellow", "green", "blue", "violet"),
labels = c(1, 2, 3, 4, 5, 6)) +
scale_colour_discrete(name=expression(paste(C, " value"))) +
ylab(label="count") +
coord_cartesian(ylim = c(0,100))
Run Code Online (Sandbox Code Playgroud)