Plotly stacked bar chart pandas dataframe

可紊 提交于 2021-02-16 09:26:32

问题


I have a dataframe with a varying number of columns. With positive and negative values. Is it possible to make a stacked bar chart with all of these columns in the dataframe?

    A    B     C
0   34   34    -12
1   34   223   -12
2  34    56    -12
3   34   86    -12
4   56   86    -12
5   56   43    -12
6   78   34    -12

回答1:


(Updated answer for newer versions of plotly)

Using px.bar will give you a stacked bar chart directly. If your bar chart for some reason is not stacked, try:

fig.update_layout(barmode='stack')

Complete code:

import pandas as pd
import plotly.express as px

# data
df = pd.DataFrame({'A': {0: 34, 1: 34, 2: 34, 3: 34, 4: 56, 5: 56, 6: 78},
                     'B': {0: 34, 1: 223, 2: 56, 3: 86, 4: 86, 5: 43, 6: 34},
                     'C': {0: -12, 1: -12, 2: -12, 3: -12, 4: -12, 5: -12, 6: -12}})

colors = px.colors.qualitative.T10

# plotly
fig = px.bar(df, 
             x = df.index,
             y = [c for c in df.columns],
             template = 'plotly_dark',
             color_discrete_sequence = colors,
             title = 'Stacked bar chart using px.bar()', 
             )

fig.show()

Old answer:


Here's a stacked bar chart using plotly offline in a Jupyter Notebook. Just make sure you have the packages listed under imports installed. df = cf.datagen.lines() produces a pandas dataframe with sample data from cufflinks.

Plotly stacked bar chart:

Reproducible snippet:

# imports
import plotly
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import numpy as np

# setup
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')

# qtconsole for debugging
#%qtconsole --style vim #src# https://qtconsole.readthedocs.io/en/stable/

# Random data using cufflinks
df = cf.datagen.lines()
df = df[['UUN.XY', 'MJF.XV', 'XBB.AO']].head(50)
df=np.abs(df)

# make figure
fig = df.iplot(asFigure=True, kind='bar', barmode = 'stack',
               xTitle='Dates',yTitle='Returns',title='Returns')

# plot figure
iplot(fig)

Edit - Test with negative values


Here's the same thing run without the line df=np.abs(df)




回答2:


Pandas DataFrame's plot can also be used here.

df.plot(kind='bar', stacked=True)

Also, here is a similar thread.



来源:https://stackoverflow.com/questions/55138359/plotly-stacked-bar-chart-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!