开发者

math - dynamic chart, maintain constrain proportions

开发者 https://www.devze.com 2023-03-25 21:19 出处:网络
i\'m creating a very simple dynamic bar-chart ( CSS / PHP ) where basically what i need to display is the total number of user contacts where each bar-width is the number of the contacts in px (each c

i'm creating a very simple dynamic bar-chart ( CSS / PHP ) where basically what i need to display is the total number of user contacts where each bar-width is the number of the contacts in px (each contact = 1 pixel) ver开发者_如何学Cy trivial no?

 _______.____________________600px
|       |                        |
| mario | ===== (54) px          |
| julie | ========= (65) px      |
| john  | === (40) px            |
| mary  | ============= (70) px  |
|_______|________________________|
        0%   30%   50%   80%   100%

now, my problem is that the graph-container should be of fixed width let's say 600px, so, what happen if one of theese have more than 600 contacts? yes i know, it screw up. ;-)

so, how to convert to percentage in a way that each total scale accordingly and never reach the end of the graph?

thank's in advance.


Sum all of your values (54 + 65 + 40 +70 = 229), calculate the percentage of each value (54/229 = 23.58%), and then apply that percentage to 600px (600 * .2358 = 141.48). You can then set that value as the width of your bar (so the first bar would be 141px).

In code it might look something like this (although you would probably calculate these values in a loop):

$total = 229;
$bar1 = 54;
$bar1Length = round(600 * ($bar1/$total)); // 141


Something like

current_width = current_value * (max_width / max_value)

Where max_width = 600px.

Note that this is just pseudo code. I can't write down anything specific, because your question doesn't provide any details.


If the width available for the bars is totalWidth, you do something like this (in C pseudocode, I don't know PHP):

int maxContacts = 0;

for (int i = 0; i < numberOfUsers; i++)
{
    if (users[i].numberOfContacts > maxContacts)
        maxContacts = users[i].numberOfContacts;
}

// now you have the max number of contacts

for (int i = 0; i < numberOfUsers; i++)
{
    widthPercent = users[i].numberOfContacts / maxContacts; // this is the percentage
    display_width_for_this_user = totalWidth * widthPercent; // gives the relative width
}
0

精彩评论

暂无评论...
验证码 换一张
取 消