-1

I need help to create the following composable

Option

All I know is that the shape is a bell curve but I dont know how to achive this using canvas. Thanks in advance

Shura
  • 1

1 Answers1

1

Edit:

When I first answered this 2 months ago, I had no idea I would eventually need to do this exact thing. My suggestion at that time was to use the normal equation to plot points. This is what that looks like. I'm hardcoding floats and dp because it would be easier for people to tailor low-level logic than it would to rewrite high-level logic to their use case.

First off, the probability density function for a normal distribution is $\frac{1}{\sigma\sqrt{2\pi}}e^{-.5(frac{x-\mu}{sigma})^{2}}$.

Because we only want a graphic and don't need actual probabilities, I'm just going to throw away the $\frac{1}{\sigma\sqrt{2\pi}}$. The reason for this is that changing sigma is the easiest way to adjust the width of the central peak of the bell curve (66% of cases fall between -sigma and sigma). So by throwing away the $\frac{1}{\sigma\sqrt{2\pi}}$, we can freely play with the width of the curve while retaining a fixed height.

To my taste, 4 standard deviations to the left and to the right is a good range for a bell curve, since it captures like 99.99% of cases and doesn't waste too much screen width. If that's what you want, set sigma=width/4. For 5 standard deviations, use sigma=width/5, and so forth.

So altogether, a minimal demo of the concept looks like this:

@Composable
fun BellCurveDemo(){
    fun normalValueY(mu:Float,sigma:Float,x:Float):Float{
        return (Math.pow(2.718,-.5*Math.pow(((x-mu).toDouble()/sigma.toDouble()),2.0))).toFloat()
    }
    val height=200f
    val width=400f
    val heightdp= with(LocalDensity.current){height.toDp()}
    val widthdp=with(LocalDensity.current){width.toDp()}

    Canvas(Modifier.height(heightdp).width(widthdp)){
    val path= Path()
    path.moveTo(0f,height-height*normalValueY(width/2,width/4,0f))
    for (i in 1 .. 20){
        path.lineTo(i*width/20,height-height*normalValueY(width/2,width/4,i*width/20))
        }
    drawPath(path,color=Color.Blue,style= Stroke(3f,pathEffect= PathEffect.cornerPathEffect(1f)))
    }
}
D. Kupra
  • 343
  • 1
  • 9