2011-08-02 107 views
1

我創建了一個非常簡單的動態條形圖(CSS/PHP),其中基本上我需要顯示的是用戶聯繫人的總數,其中每個條寬度是px中的觸點(每個觸點= 1像素)非常平凡嗎?數學 - 動態圖表,維持約束比例

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

現在,我的問題是,圖的容器應固定寬度的假設600px的,所以,如果theese的一個有600個多觸點發生什麼事?是的,我知道,它搞砸了。 ;-)

那麼,如何轉換爲百分比的方式,每個總規模相應,永遠不會達到圖的結尾?

提前致謝。

回答

3

將所有值(54 + 65 + 40 +70 = 229)相加,計算每個值的百分比(54/229 = 23.58%),然後將該百分比應用到600像素(600 * .2358 = 141.48 )。然後,您可以將該值設置爲條形的寬度(因此第一個條形將爲141px)。

在代碼中它可能看起來像這樣(雖然你可能會計算在一個循環中這些值):

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

+1謝謝;-) –

+0

嗨,我有另一個小問題,什麼是公式,如果我想在下面添加該圖表經典視覺比例如0% - 10% - 20% - ... - 100%總是基於600?多謝,夥計! –

+0

'$ bar1/$ total'會給你百分比作爲一個分數(例如0.754)來得到類似於74%的東西,乘以100和round。所以像'round(($ bar1/$ total)* 100)。 「%」' –

1

喜歡的東西

current_width = current_value *(MAX_WIDTH/MAX_VALUE)

凡MAX_WIDTH = 600px的。

請注意,這只是僞代碼。我不能寫下任何具體的東西,因爲你的問題沒有提供任何細節。

+0

+1謝謝;-) –

1

如果可用寬度的條是totalWidth,你做這樣的事情(在C僞代碼,我不知道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 
}