FSharp.Charting icon indicating copy to clipboard operation
FSharp.Charting copied to clipboard

Colored bar chart

Open risinghero opened this issue 9 years ago • 2 comments

Is there any possibility to draw colored chart, i.e. to assign each bar in BarChart different color?

risinghero avatar Feb 23 '16 09:02 risinghero

As far I know there is no special method to do this. But GenericChart has function ApplyToChart. It allows you to apply whatever you want directly to inner chart.

So you can create simple function like this:

let difColors (colors:Color[]) (chart:Chart) = 
    let count = colors.Length
    for (series:Series) in chart.Series do
        if count = series.Points.Count then
            for i in 0..count - 1 do
                series.Points.[i].Color <- colors.[i]

and get colored chart

sample

Full code:

open System.Windows.Forms.DataVisualization.Charting
open System.Drawing

let countryData = 
    [ "Africa", 1033043; 
      "Asia", 4166741; 
      "Europe", 732759; 
      "South America", 588649; 
      "North America", 351659; 
      "Oceania", 35838  ]

let difColors (colors:Color[]) (chart:Chart) = 
    let count = colors.Length
    for (series:Series) in chart.Series do
        if count = series.Points.Count then
            for i in 0..count - 1 do
                series.Points.[i].Color <- colors.[i]

let colors = [| Color.Red; Color.Green; Color.Blue; Color.Orange; Color.DarkGray; Color.Black |]
(countryData |> Chart.Bar).ApplyToChart (difColors colors)

FoggyFinder avatar Nov 25 '18 20:11 FoggyFinder

It was just a one way. You can apply palette or something if you don't want to enumerate colors manually.

FoggyFinder avatar Nov 25 '18 20:11 FoggyFinder