JuliaPy / PythonPlot.jl

Plotting for Julia based on matplotlib.pyplot
MIT License
74 stars 8 forks source link

ColorMap not working #18

Closed ZaynChen closed 1 year ago

ZaynChen commented 1 year ago

I want to use a custom colormap in Jupyter. In the code below, the first display only shows the text ColorMap “cm1”, and the second shows the coolwarm color image correctly.

using PythonPlot
c = [
    0 0 0
    255 0 0
    0 255 0
    0 0 255
    255 255 255
] ./ 255

cm1 = ColorMap("cm1", c)
register_cmap("cm1", cm1)
display(get_cmap("cm1"))
display(get_cmap("coolwarm"))

and using show to display cm1 causes error:

show(stdout, MIME("image/svg+xml"), get_cmap("cm1"))

Python: TypeError: Julia: MethodError: objects of type Vector{Tuple{Float64, Float64, Float64}} are not callable
Use square brackets [] for indexing an Array.

And this may due to Dict{String, Vector{Tuple{Float64, Float64, Float64}}} can not automatically convert to Dict{String, Py} or something. Below only shows text,

seg = Dict(
    "blue" => [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)],
    "green" => [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 1.0, 1.0), (0.75, 0.0, 0.0), (1.0, 1.0, 1.0)], 
    "red" => [(0.0, 0.0, 0.0), (0.25, 1.0, 1.0), (0.5, 0.0, 0.0), (0.75, 0.0, 0.0), (1.0, 1.0, 1.0)])
ColorMap(PythonPlot.LinearSegmentedColormap("cm", seg, 5, 1))
ColorMap "cm"

after using the pylist to wrap the Vector, it shows the color image successfully.

seg = Dict(
    "blue" => pylist([(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)]),
    "green" => pylist([(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 1.0, 1.0), (0.75, 0.0, 0.0), (1.0, 1.0, 1.0)]), 
    "red" => pylist([(0.0, 0.0, 0.0), (0.25, 1.0, 1.0), (0.5, 0.0, 0.0), (0.75, 0.0, 0.0), (1.0, 1.0, 1.0)]))
ColorMap(PythonPlot.LinearSegmentedColormap("cm", seg, 5, 1))
stevengj commented 1 year ago

Should be fixed on main.

It looks like this is one of those cases where Python is picky about types — it apparently wants a genuine list object, not some other list-like type (e.g. a Julia VectorValue wrapper), and assumes that any other type is a function that it should call to get the RGB value or something.

stevengj commented 1 year ago

A new version with the fix should be tagged shortly: https://github.com/JuliaRegistries/General/pull/78717