Skip to content

Instantly share code, notes, and snippets.

@shawnbot
Last active October 17, 2017 05:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shawnbot/38516ee593902680fd79d7020dbca4c0 to your computer and use it in GitHub Desktop.
Save shawnbot/38516ee593902680fd79d7020dbca4c0 to your computer and use it in GitHub Desktop.
Bar charts in Sketch? Yep.

This is a Sketch script to make bar charts.

bars

Here's how to run it:

  1. Make a selection of only shapes with names in the format:
(anything)value={number}
  1. Press Ctrl-Shift-K to bring up the "Run Custom Script" dialog.
  2. Copy and paste the script into the top text area.
  3. Press the Run button.
  4. Profit!
var items = map(context.selection, function(shape) {
return {
shape: shape,
value: getValue(shape),
size: shape.frame().width()
};
});
var min = 0;
var max = items.reduce(function(memo, d) {
return Math.max(memo, d.value);
}, min);
var maxSize = items.reduce(function(memo, d) {
return Math.max(memo, d.size);
}, 0);
items.forEach(function(d) {
var size = (d.value - min) / (max - min);
d.shape.frame().width = Math.max(size * maxSize, 0.5);
});
function getValue(shape) {
var match = shape.name().match(/value=(.+)\b/);
return (match ? +match[1] : 0) || 0;
}
function forEach(array, fn) {
var iter = array.objectEnumerator();
var item, i = 0;
while (item = iter.nextObject()) {
fn(item, i++);
}
}
function map(array, fn) {
var values = [];
forEach(array, function(d, i) {
values.push(fn(d, i));
});
return values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment