简体   繁体   English

在ggplot2中绘制离散(或不连续)函数

[英]Plotting a discrete (or discontinuous) function in ggplot2

I have the following function, which I would like to plot using ggplot: 我有以下功能,我想用ggplot绘制:

f(x) = 3/4 for x between 0 and 1; f(x)= 3/4,x在0和1之间; 1/4 for x between 2 and 3; x为1/4,介于2和3之间; and 0 elsewhere. 其他地方0。

I have come up with the following R code: 我想出了以下R代码:

eq<-function(x) {
    if(x>=0 && x<=1) {
        y<-3/4
    } else if(x>=2 && x<=3) {
        y<-1/4
    } else {
    y<-0
    }
return(y)
}

library(ggplot2)

ggplot(data.frame(x=c(-5,5)), aes(x)) + stat_function(fun=eq)

However, this results in a plot with only a horizontal line centered on 0. What have I done wrong? 但是,这会产生一个只有以0为中心的水平线的情节。我做错了什么?

The function should be "vectorized", ie, accept a vector as argument. 该函数应该“向量化”,即接受一个向量作为参数。

eq <- function(x) 
  ifelse( x>=0 & x<=1, 3/4,
  ifelse( x>=2 & x<=3, 1/4, 0 ))
ggplot(data.frame(x=c(-5,5)), aes(x)) + 
  stat_function(fun=eq, geom="step")

I think this is another place where either switch could be used to great effect, or something along the lines of 我认为这是另一个地方,任何一个switch都可以用来产生很好的效果,或者类似的东西
ysteps <- c(.75,.25,0)
xsteps <- c(1,2,3)
y <- ysteps[which(x >= xsteps)]

Please feel free to edit this so it's correct -- my brain is slow and I don't have R available right now. 请随意编辑它,这是正确的 - 我的大脑很慢,我现在没有R可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM