Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

python - Limit to a specific number of bar stacks in Plotly bar chart using pandas

I am making a Plotly graph object with stacked bars and I want only 10 stacks/categories on the x axis, sorted by total descending, regardless of how many are stacked vertically. The size of the stacks varies between 1 and 3 bars. Since Plotly is designed to show all of the data passed to it, I want to clip the data already in the dataframe.

My first instinct would be to use nlargest(), and then trace for each unique color value for which the bars stack:

n=???
dataframe.set_index(x_key).nlargest(n, y_key, keep='all').reset_index()
figure = go.Figure()

for color in df[color_column].unique():
    figure.add_trace(
        go.Bar(
            x=df.loc[df[color_column] == color][x_key],
            y=df.loc[df[color_column] == color][y_key],
            name=color
        )
    )

So I have to pass an 'n' limit that would result in up to 10 unique x values on the graph. 'n' could be anything from 10 to 30, depending on how much stacking occurs.

How would I do that? Is there a better way than nlargest and trying to determine 'n'?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...