MonkeybreadSoftware Posted June 30 Posted June 30 Recently we had the idea that we could draw charts ourselves with the GraphicsMagick functions. It's more a fun project, but I was able to draw a simple bar chart with a few drawing commands. We use a few filled rectangles to draw bars and calculate them on the fly in the while loop. Let ( [ We start here with a few values. You could of course pass them as parameters in a custom function. But for the example we just pass some example data: cities = List ( "Hamburg" ; "Berlin" ; "Munich" ; "Cologne" ) ; values = List ( 1800000 ; 3700000 ; 1500000 ; 1100000 ) ; And we define a color palette to pick the colors for each bar: colors = List ( "#4e79a7" ; "#f28e2b" ; "#e15759" ; "#76b7b2" ; "#59a14f" ) ; We create an image with a given width, height and white as background color. img = MBS( "GMImage.New"; "600x400"; "white" ) ; We need to find the maximum value for scaling the bars. Usually you would make a loop over the list, but here we just call Max() function and pass all values: maxValue = Max ( 1800000 ; 3700000 ; 1500000 ; 1100000 ) ; Using black stroking color, we draw the axes with simple lines: r = MBS( "GMImage.SetStrokeColor"; img; "black" ) ; r = MBS( "GMImage.DrawLine"; img; 50; 350; 550; 350 ) ; // X-axis r = MBS( "GMImage.DrawLine"; img; 50; 50; 50; 350 ) ; // Y-axis Now we define the sizes for the bars, the size for the spacing and where to start for the x-coordinate. These values could be made parameters to just defined as needed in the calculation like we do here:s barWidth = 80 ; spacing = 30 ; baseX = 70 ; Next we have a while loop embedded to loop over the values. In the loop we pick the city name, the value and the color from the lists. For the colors we use Mod() already to pick the next color if you have more values than colors and reuse them. Then we calculate the bar position and size and draw the rectangles. Below that we draw the text with the name of the city. count = ValueCount ( cities ) ; colorCount = ValueCount ( colors ) ; r = While ( [ i = 1 ] ; i ≤ count ; [ city = GetValue ( cities ; i ) ; val = GetValue ( values ; i ) ; color = GetValue ( colors ; Mod ( i - 1 ; colorCount ) + 1 ) ; height = (val / maxValue) * 300 ; x1 = baseX + (i - 1) * (barWidth + spacing) ; x2 = x1 + barWidth ; y1 = 350 - height ; y2 = 350 ; r = MBS( "GMImage.SetFillColor"; img; color ) ; r = MBS( "GMImage.DrawRectangle"; img; x1; y1; x2; y2 ) ; r = MBS( "GMImage.SetFontPointsize"; img; 16 ); geometry = barWidth & "x20+" & x1 & "+360" ; r = MBS( "GMImage.Annotate"; img; city; geometry; 5 ) ; // 5 = CenterGravity i = i + 1 ] ; r ) Finally we encode the image as PNG and return with the result variable. result = MBS( "GMImage.WriteToPNGContainer"; img; "test.png" ); r = MBS("GMImage.Free"; img) ] ; result ) Please try and see what you can build.
Recommended Posts