Description
px.Constant
In certain cases to get the kind of output one would want with PX we need to create a dummy column containing the same string or number in each row. I propose to create a special kind of object that we could pass into the px
functions to do this like:
px.bar(df, y="the_y_value", x=px.Constant(1, label="the_optional_label"))
which would be a shortcut for:
px.bar(df, y="the_y_value", x=[1]*len(df), labels={"x": "the_optional_label"})
px.Identity
+ px.Direct
(identity option 1)
Relatedly, but on a different note, one might have a column that directly encodes something like the color, and we might want a similar mechanism for doing something like
px.bar(x=[1,2,3], y=[1,2,3], color=px.Identity(["red", "green", "blue"]))
px.bar(x=[1,2,3], y=[1,2,3], color=px.Identity("column_with_colors"))
which would be a shortcut for:
px.bar(x=[1,2,3], y=[1,2,3], color=["red", "green", "blue"],
color_discrete_map={"red":"red", "blue":"blue", "green": "green"})
Using the two together would allow you to force a single series to a single color:
px.bar(x=[1,2,3], y=[1,2,3], color=px.Identity(px.Constant("red")))
and this might warrant its own shortcut, maybe px.Direct
?
px.bar(x=[1,2,3], y=[1,2,3], color=px.Direct("red"))
which would be a more-intuitive shortcut for the following equivalent calls, in terms of their output:
px.bar(x=[1,2,3], y=[1,2,3], color=px.Constant("red"),
color_discrete_map={"red":"red"})
px.bar(x=[1,2,3], y=[1,2,3], color=["red"]*3,
color_discrete_map={"red":"red"})
px.bar(x=[1,2,3], y=[1,2,3],
color_discrete_sequence=["red"])
px.IDENTITY_MAP
(identity option 2)
A slightly different way of solving the "identity" problem would be to be able to pass in a magic value to *_map
(edit: which per @emmanuelle could be just the string "identity"
!) like this:
px.bar(x=[1,2,3], y=[1,2,3], color=["red", "green", "blue"],
color_discrete_map=px.IDENTITY_MAP)
which would also be the equivalent of
px.bar(x=[1,2,3], y=[1,2,3], color=["red", "green", "blue"],
color_discrete_map={"red":"red", "blue":"blue", "green": "green"})
This would avoid the need for nesting px.Constant
and px.Identity
when you want to use constant and identity together, and would mean no need for px.Direct
as shortcut for that:
px.bar(x=[1,2,3], y=[1,2,3], color=px.Constant("red"),
color_discrete_map=px.IDENTITY_MAP)
(note that the foregoing could also apply to any groupable attrs beyond color
like symbol
or line_dash
)