4

This is a little tricky, I'd like to generate some graph lines for a frequency spectrum.

e.g.

Ableton

See how the x-axis graph lines change logarithmically in this way...

enter image description here

What i need is the maths to do this above. And then a way to plot x coordinates accurately upon it.

I want to be plotting frequencies between 20Hz to 16000Hz across the x-axis in this way.

(I'm not too worried about the drawing part I can use canvas, i'm just stuck on the maths)

I think i would then need a function to convert say 1525Hz into px (or%) to be plotted on it.

Many thanks

Mulhoon
  • 1,852
  • 21
  • 26

1 Answers1

5

i'd use something like this (live example on jsFiddle):

var min_f = Math.log(20) / Math.log(10),
    max_f = Math.log(16000) / Math.log(10),
    range = max_f - min_f,
    position_px = (Math.log(frequency) / Math.log(10) - min_f) / range * width_px
Aprillion
  • 21,510
  • 5
  • 55
  • 89
  • Excellent. This works, thank you. At first I thought it would need to be repeated as it looks like there are a few next to each other. But that's not the case, only the unit division change. Thanks. – Mulhoon Feb 21 '12 at 15:14
  • Why are you dividing it by Math.log(10)? You could use Math.log(freq, 10) to have it in the base of 10. Also I noticed, that even if you don't divide or even if you change the base from e to anythig, the result is always the same. – Ruuza Dec 23 '21 at 20:56
  • 1
    @Ruuza because [`Math.log`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log) only accepts 1 paremater, you cannot change the base in JS... – Aprillion Dec 24 '21 at 07:55
  • Thanks. And why the base of 10? Seems the result is the same for any base given – Ruuza Dec 24 '21 at 13:34
  • 1
    no idea, this answer is from 2012, I probably didn't realize that the answer is independent of base – Aprillion Dec 24 '21 at 13:43