Groovy Goodness: Create Ascii Bar Charts
Groovy 5 adds a new utility method to create an ascii bar chart. You can use the bar
method in the org.codehaus.groovy.util.StringUtil
class. You can pass a value, a minimum and maximum value and optinally specify the width of the bar chart. The result is a String
value consisting of a number of "blocks". A block could be whole, but also 1/8 eights of the block are used to get a nice looking bar chart. How many of these values are needed is based on the input arguments. With this method you have a nice way to format number values on a command-line.
In the following example an ascii bar chart is created based on temperature values for cities:
import org.codehaus.groovy.util.StringUtil
// List of cities with temperature in Celcius.
def cities = [
[name: "Amsterdam", temp: 18],
[name: "Berlin", temp: 19],
[name: "Paris", temp: 22],
[name: "Madrid", temp: 27],
[name: "Rome", temp: 25]
]
// Method to return String with names of cities,
// a bar chart for the temperature value and
// the temperature value.
def barCharts(cities, width = 40 /* default value width for bar method */) {
// Calculate the maximum size of a city name.
def cityNameMaxSize = cities.name.collect { it.size() }.max()
// Calculate the max temperature found.
def cityTempMax = cities.temp.max()
cities
.collect { city ->
// Calculate bar chart with temperature.
// First argument is the value,
// second argument the minimum value,
// third argument the maximum value and
// fourth argument is optional for width and has a default value of 40.
def barChart = StringUtil.bar(city.temp, 0, cityTempMax, width)
// Create String with city name, bar chart and temperature.
"${city.name.padRight(cityNameMaxSize)} ${barChart} ${city.temp}"
}
// Join with line separator.
.join(System.lineSeparator())
}
assert barCharts(cities) == """\
Amsterdam ██████████████████████████▋ 18
Berlin ████████████████████████████▎ 19
Paris ████████████████████████████████▌ 22
Madrid ████████████████████████████████████████▏ 27
Rome █████████████████████████████████████▏ 25"""
assert barCharts(cities, 20) == """\
Amsterdam █████████████▍ 18
Berlin ██████████████▏ 19
Paris ████████████████▍ 22
Madrid ████████████████████▏ 27
Rome ██████████████████▌ 25"""
Written with Groovy 5.0.