fslaborg / FSharp.Charting

Charting library suitable for interactive F# scripting
http://fslab.org/FSharp.Charting/
Other
213 stars 67 forks source link

Colored bar chart #105

Open risinghero opened 8 years ago

risinghero commented 8 years ago

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

FoggyFinder commented 5 years ago

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 commented 5 years ago

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