I have been trying to figure this out for a while, so any help would be appreciated.
I am able to run fig_test_reg
just fine, but then when I try to run the same parameters through a function I get a ValueError: ValueError: Value of 'pattern_shape' is not the name of a column in 'data_frame'. Expected one of ['Fruit', 'Amount', 'City'] but received: group
code:
import plotly.express as px
import pandas as pd
df_test = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
def to_bar(data,x,y,color,barmode):
bar_chart = px.bar(data,x,y,color,barmode)
return bar_chart
fig_test_func = to_bar(df_test, x="Fruit", y="Amount",color='City',barmode='group')
fig_test_reg = px.bar(df_test, x="Fruit", y="Amount",color='City',barmode='group')
fig_test_func.show()
why is this happening? how can I run this through a function? what am i missing?
CodePudding user response:
The issue here is in how you are passing function arguments. If you look at the documentation for the .bar()
method, you can see the order of keyword arguments:
plotly.express.bar(
data_frame=None,
x=None,
y=None,
color=None,
pattern_shape=None,
# more kwargs here
barmode='relative',
# more kwargs here
)
Inside your function, you are passing parameters as positional arguments, rather than keyword arguments: bar_chart = px.bar(data,x,y,color,barmode)
. So, your group
value that you are trying to pass to the barmode=
parameter actually gets passed to the pattern_shape=
parameter, as it is located in that fifth position in the function's signature.
So, to resolve the problem, you can just convert the positional arguments to keyword arguments in your call to the px.bar()
function:
bar_chart = px.bar(data,x=x,y=y,color=color,barmode=barmode)