简体   繁体   English

如何缩放条形图列以使其正确且成比例地装入其容器?

[英]How can I scale a bar graph column to fit properly and proportionately inside its container?

I am building a simple bar chart library with vanilla JS and jQuery. 我正在使用香草JS和jQuery构建一个简单的条形图库。 I have this code, which works: 我有这段代码,它可以工作:

var userData = {
'Black': 8,
'Latino': 6,
'Native': 4,
'Asian': 10,
'White': 12,
'Indian': 9,
'Other': 5
};

var addColumns = function(dataObject) {
  var values = Object.values(dataObject);

  var columnContainer = document.createElement("div");
  $(columnContainer).css({
  "display": "flex",
  "flex-direction": "row",
  "align-items": "flex-end",
  "position": "relative",
  "padding-top": "8px",
  "margin-left": "50px",
  "padding-bottom": "10px"
  });

 for (i = 0; i < values.length; i++) {
  var column = document.createElement("div");
  column.innerHTML = '<br>' + values[i];
  $(column).css({
    "margin-right": "30px",
    "width": "90px",
    "background-color": "#68b24a",
    "text-align": "center",
    "text-padding": "20px",
    "height": values[i] * 20 + "px",
    "z-index": "1"
  });
  $(mainContainer).append(columnContainer);
  $(columnContainer).append(column);
}

But since I'm drawing the height based directly on the value of the data converted to pixels, it's not possible to deal with larger numbers (like 400, 450, 430, 500). 但是由于我是直接根据转换为像素的数据值绘制高度,因此无法处理较大的数字(例如400、450、430、500)。 The column just turns into a huge bar that you have to scroll through. 该列只是变成一个巨大的栏,您必须滚动浏览。 My math isn't very great; 我的数学不是很好。 How can I draw the column height in a better way, based on a percentage maybe? 如何根据百分比更好地绘制列高?

Or maybe there is a way to simply scale the values down to be proportionate to the size of the container? 还是有一种方法可以简单地将值按比例缩小以与容器的大小成比例? Really not sure how to go about it. 真的不确定如何去做。

You can set up a proportion where you define the max height equal to the container size (assume 150px height) and then you calculate the size of the current value basing on that. 您可以设置一个比例,在该比例中定义等于容器尺寸的最大高度(假设高度为150px),然后在此基础上计算当前值的尺寸。

20 : X = 500 : 150

where 20 is the current element value, X is your variable to calculate and on the other side you have 500 (max array value) and 150 (max height you can support in px) 其中20是当前元素值,X是您要计算的变量,另一边则有500(最大数组值)和150(您可以支持的最大高度(以px为单位))

So resolving it would be equal to 500 * X = 150 * 20 => X = (150*20) / 500 which is equal to 6 (px). 因此解决它等于500 * X = 150 * 20 => X =(150 * 20)/ 500等于6(px)。

You can use percentage also just putting 100 instead of 150 and assuming that the values are all relative (percentage) 您也可以使用百分比,而只需输入100而不是150,并假设所有值都是相对的(百分比)

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

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