如何在python中获得堆积条形图

时间:2017-10-08 15:37:06

标签: python pandas plotly

这段代码:

import plotly
from plotly.graph_objs import *

import pandas as pd
import datetime

date = ['2017-01-01', '2017-01-04', '2017-01-05', '2017-02-01', '2017-02-10']
date_dt = map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'), date)

attribute = ['a', 'b', 'a', 'a', 'b']
json_file = {'attribute':attribute}

df = pd.DataFrame(json_file, index=date_dt)

weekly_summary = pd.DataFrame()

weekly_summary['summation'] = df.attribute.resample('W', closed='left').count()

trace1 = Bar(
    x=weekly_summary.index.tolist(),
    y=weekly_summary.summation
)

layout = Layout(
    xaxis=XAxis(
        ticks=weekly_summary.index.tolist(),
        tickvals=weekly_summary.index.tolist(),
    ),
    yaxis=YAxis(
        ticks=weekly_summary.summation
    )
)

data = Data([trace1])

figure = Figure(data=data, layout=layout)
plotly.offline.plot(figure)

将生成以下图表,即每周对象的计数: enter image description here

我会更喜欢叠条。例如,我希望第一个条形由两个堆叠的条形组成,第一个条形图具有高度2(因为有两个与该条形相关的“a”属性)和一个高度为1的条形图。因此,第一个杆可以由两个堆叠的杆组成;一个高度为2的红色条和一个高度为1的蓝色条。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

我设法做了一些事情,但这很乏味。这是代码和结果:

import plotly
from plotly.graph_objs import *

import matplotlib.pyplot as plt

import pandas as pd
import datetime

date = ['2017-01-01', '2017-01-04', '2017-01-05', '2017-02-01', '2017-02-10']

date_dt = map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'), date)

attribute = ['a', 'b', 'a', 'a', 'b']
json_file = {'attribute':attribute}

df = pd.DataFrame(json_file, index=date_dt)

first_df = df[df['attribute'] == 'a'].copy()
first_df.reindex([date_dt])
first_df_modified = pd.DataFrame()
first_df_modified['counter'] = first_df.attribute.resample('W', closed='left').count()




second_df = df[df['attribute'] == 'b'].copy()
second_df.reindex([date_dt])
second_df_modified = pd.DataFrame()
second_df_modified['counter'] = second_df.attribute.resample('W', closed='left').count()



trace1 = Bar(
    x=first_df_modified.index,
    y=first_df_modified.counter,
    name='a'
)

trace2 = Bar(
    x=second_df_modified.index,
    y=second_df_modified.counter,
    name='b'
)


layout = Layout(
    xaxis=XAxis(
        ticks=second_df_modified.index,
        tickvals=second_df_modified.index,
    ),
    barmode='stack'
)


data = Data([trace1, trace2])
figure = Figure(data=data, layout=layout)
plotly.offline.plot(figure)

图表: enter image description here 但我认为应该有一个更聪明的方法来做到这一点。