Skip to content

color_continuous_scale incompatible with marginal distributions in density_heatmap #4377

Open
@MoustHolmes

Description

@MoustHolmes

I was trying out the examples from https://plotly.com/python/2D-Histogram/ and wanted to use the density heat map with marginal distribution on x and y but wanted to change the colour map to align with some previous work.
I found when combining the two subsequent examples from the 2D-Histogram page I got an error. If the marginal distribution and color_continuous_scale aren't meant to be used together there should at least be a better error message.
I btw also test other kinds of distributions like box, violin and rug with the same result.

plotly Version: 5.17.0

My code:

import plotly.express as px
df = px.data.tips()

fig = px.density_heatmap(df, x="total_bill", y="tip", nbinsx=20, nbinsy=20, marginal_x="histogram", marginal_y="histogram", color_continuous_scale="Viridis")
fig.show()

Traceback:

ValueError                                Traceback (most recent call last)
[/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/attention_weight_event_viewer.ipynb](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/attention_weight_event_viewer.ipynb) Cell 10 line 4
      [1](vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a226865705f475055227d/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/attention_weight_event_viewer.ipynb#Y130sdnNjb2RlLXJlbW90ZQ%3D%3D?line=0) import plotly.express as px
      [2](vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a226865705f475055227d/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/attention_weight_event_viewer.ipynb#Y130sdnNjb2RlLXJlbW90ZQ%3D%3D?line=1) df = px.data.tips()
----> [4](vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a226865705f475055227d/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/attention_weight_event_viewer.ipynb#Y130sdnNjb2RlLXJlbW90ZQ%3D%3D?line=3) fig = px.density_heatmap(df, x="total_bill", y="tip", nbinsx=20, nbinsy=20, marginal_y="histogram", color_continuous_scale="Viridis")
      [5](vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a226865705f475055227d/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/attention_weight_event_viewer.ipynb#Y130sdnNjb2RlLXJlbW90ZQ%3D%3D?line=4) fig.show()

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/express/_chart_types.py:187](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/express/_chart_types.py:187), in density_heatmap(data_frame, x, y, z, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, hover_name, hover_data, animation_frame, animation_group, category_orders, labels, orientation, color_continuous_scale, range_color, color_continuous_midpoint, marginal_x, marginal_y, opacity, log_x, log_y, range_x, range_y, histfunc, histnorm, nbinsx, nbinsy, text_auto, title, template, width, height)
    145 def density_heatmap(
    146     data_frame=None,
    147     x=None,
   (...)
    180     height=None,
    181 ) -> go.Figure:
    182     """
    183     In a density heatmap, rows of `data_frame` are grouped together into
    184     colored rectangular tiles to visualize the 2D distribution of an
    185     aggregate function `histfunc` (e.g. the count or sum) of the value `z`.
    186     """
--> 187     return make_figure(
    188         args=locals(),
    189         constructor=go.Histogram2d,
    190         trace_patch=dict(
    191             histfunc=histfunc,
    192             histnorm=histnorm,
    193             nbinsx=nbinsx,
    194             nbinsy=nbinsy,
    195             xbingroup="x",
    196             ybingroup="y",
    197         ),
    198     )

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/express/_core.py:2256](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/express/_core.py:2256), in make_figure(args, constructor, trace_patch, layout_patch)
   2251         group[var] = 100.0 * group[var] [/](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/) group_sum
   2253 patch, fit_results = make_trace_kwargs(
   2254     args, trace_spec, group, mapping_labels.copy(), sizeref
   2255 )
-> 2256 trace.update(patch)
   2257 if fit_results is not None:
   2258     trendline_rows.append(mapping_labels.copy())

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:5141](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:5141), in BasePlotlyType.update(self, dict1, overwrite, **kwargs)
   5139         BaseFigure._perform_update(self, kwargs, overwrite=overwrite)
   5140 else:
-> 5141     BaseFigure._perform_update(self, dict1, overwrite=overwrite)
   5142     BaseFigure._perform_update(self, kwargs, overwrite=overwrite)
   5144 return self

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:3921](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:3921), in BaseFigure._perform_update(plotly_obj, update_obj, overwrite)
   3915 validator = plotly_obj._get_prop_validator(key)
   3917 if isinstance(validator, CompoundValidator) and isinstance(val, dict):
   3918 
   3919     # Update compound objects recursively
   3920     # plotly_obj[key].update(val)
-> 3921     BaseFigure._perform_update(plotly_obj[key], val)
   3922 elif isinstance(validator, CompoundArrayValidator):
   3923     if plotly_obj[key]:
   3924         # plotly_obj has an existing non-empty array for key
   3925         # In this case we merge val into the existing elements

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:3942](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:3942), in BaseFigure._perform_update(plotly_obj, update_obj, overwrite)
   3939                 plotly_obj[key] = val
   3940         else:
   3941             # Assign non-compound value
-> 3942             plotly_obj[key] = val
   3944 elif isinstance(plotly_obj, tuple):
   3946     if len(update_obj) == 0:
   3947         # Nothing to do

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:4876](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:4876), in BasePlotlyType.__setitem__(self, prop, value)
   4872         self._set_array_prop(prop, value)
   4874     # ### Handle simple property ###
   4875     else:
-> 4876         self._set_prop(prop, value)
   4877 else:
   4878     # Make sure properties dict is initialized
   4879     self._init_props()

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:5220](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:5220), in BasePlotlyType._set_prop(self, prop, val)
   5218         return
   5219     else:
-> 5220         raise err
   5222 # val is None
   5223 # -----------
   5224 if val is None:
   5225     # Check if we should send null update

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:5215](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/plotly/basedatatypes.py:5215), in BasePlotlyType._set_prop(self, prop, val)
   5212 validator = self._get_validator(prop)
   5214 try:
-> 5215     val = validator.validate_coerce(val)
   5216 except ValueError as err:
   5217     if self._skip_invalid:

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:1374](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:1374), in ColorValidator.validate_coerce(self, v, should_raise)
   1372     validated_v = self.vc_scalar(v)
   1373     if validated_v is None and should_raise:
-> 1374         self.raise_invalid_val(v)
   1376     v = validated_v
   1378 return v

File [~/miniconda3/envs/icet2/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:287](https://vscode-remote+ssh-002dremote-002b7b22686f73744e616d65223a226865705f475055227d.vscode-resource.vscode-cdn.net/groups/icecube/moust/work/IceCubeEncoderTransformer/notebooks/~/miniconda3/envs/icet2/lib/python3.8/site-packages/_plotly_utils/basevalidators.py:287), in BaseValidator.raise_invalid_val(self, v, inds)
    284             for i in inds:
    285                 name += "[" + str(i) + "]"
--> 287         raise ValueError(
    288             """
    289     Invalid value of type {typ} received for the '{name}' property of {pname}
    290         Received value: {v}
    291 
    292 {valid_clr_desc}""".format(
    293                 name=name,
    294                 pname=self.parent_name,
    295                 typ=type_str(v),
    296                 v=repr(v),
    297                 valid_clr_desc=self.description(),
    298             )
    299         )

ValueError: 
    Invalid value of type 'builtins.str' received for the 'color' property of histogram.marker
        Received value: 'V'

    The 'color' property is a color and may be specified as:
      - A hex string (e.g. '#ff0000')
      - An rgb/rgba string (e.g. 'rgb(255,0,0)')
      - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
      - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
      - A named CSS color:
            aliceblue, antiquewhite, aqua, aquamarine, azure,
            beige, bisque, black, blanchedalmond, blue,
            blueviolet, brown, burlywood, cadetblue,
            chartreuse, chocolate, coral, cornflowerblue,
            cornsilk, crimson, cyan, darkblue, darkcyan,
            darkgoldenrod, darkgray, darkgrey, darkgreen,
            darkkhaki, darkmagenta, darkolivegreen, darkorange,
            darkorchid, darkred, darksalmon, darkseagreen,
            darkslateblue, darkslategray, darkslategrey,
            darkturquoise, darkviolet, deeppink, deepskyblue,
            dimgray, dimgrey, dodgerblue, firebrick,
            floralwhite, forestgreen, fuchsia, gainsboro,
            ghostwhite, gold, goldenrod, gray, grey, green,
            greenyellow, honeydew, hotpink, indianred, indigo,
            ivory, khaki, lavender, lavenderblush, lawngreen,
            lemonchiffon, lightblue, lightcoral, lightcyan,
            lightgoldenrodyellow, lightgray, lightgrey,
            lightgreen, lightpink, lightsalmon, lightseagreen,
            lightskyblue, lightslategray, lightslategrey,
            lightsteelblue, lightyellow, lime, limegreen,
            linen, magenta, maroon, mediumaquamarine,
            mediumblue, mediumorchid, mediumpurple,
            mediumseagreen, mediumslateblue, mediumspringgreen,
            mediumturquoise, mediumvioletred, midnightblue,
            mintcream, mistyrose, moccasin, navajowhite, navy,
            oldlace, olive, olivedrab, orange, orangered,
            orchid, palegoldenrod, palegreen, paleturquoise,
            palevioletred, papayawhip, peachpuff, peru, pink,
            plum, powderblue, purple, red, rosybrown,
            royalblue, rebeccapurple, saddlebrown, salmon,
            sandybrown, seagreen, seashell, sienna, silver,
            skyblue, slateblue, slategray, slategrey, snow,
            springgreen, steelblue, tan, teal, thistle, tomato,
            turquoise, violet, wheat, white, whitesmoke,
            yellow, yellowgreen
      - A number that will be interpreted as a color
        according to histogram.marker.colorscale
      - A list or array of any of the above

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3backlogbugsomething brokensev-2serious problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions