Search code examples
plotlyjuliauicolorplotly.js

Julia: How to change color of a group in plotly scatterplot


Say I have the following example code

using PlotlyJS
using CSV, DataFrames

df = dataset(DataFrame, "iris")
plot(
    df, x=:sepal_width, y=:sepal_length, color=:species,
    mode="markers"
)

enter image description here How could I go about specifying the color for each group e.g. if I want setosa to be yellow instead?

It's exactly this Plotly-Express: How to fix the color mapping when setting color by column name but I need it in julia. I could not get the color_discrete_map to work...


Solution

  • Not quite as convenient as just setting a color_discrete_map, but you can do it like this:

    julia> species_color_map = Dict("setosa"     => "yellow",
                                    "versicolor" => "aqua",
                                    "virginica"  => "red")
    Dict{String, String} with 3 entries:
      "virginica"  => "red"
      "setosa"     => "yellow"
      "versicolor" => "aqua"
    
    julia> plot([scatter(
               subdf,
               x = :sepal_width,
               y = :sepal_length,
               name = subdf[1, :species],
               marker_color = species_color_map[ subdf[1, :species] ],
               mode = "markers"
           )
           for subdf in groupby(df, :species)])
    
    
    

    This is pretty much what the plot(df, ..., color=:species) call does underneath, in a more generic way. Unfortunately, I don't see a way to plug into that and just customize the colours based on value.