我正在尝试使用 plotly,如何将它转换为 plotly。
# Draw a nested barplot to show total loan amount for state and year
plt.style.use('bmh')
g = sns.factorplot(x="State", y="Loan_Amount_000", hue="As_of_Year", data=total_amount_group_year,
kind="bar",size=6, palette=sns.color_palette(flatui))
g.despine(left=True)
g.set_ylabels("Total Loan Amount",fontsize=15)
g.set_xlabels("State",fontsize=15)
g.set(title="Total Loan Amount aggregated by State and Year")
g.set_yticklabels(fontsize=15)
g.set_xticklabels(fontsize=15)
我正在使用下面的代码,但没有显示任何内容。
import cufflinks as cf
import plotly.plotly as py
import plotly.graph_objs as go
data = [go.Bar(x=total_amount_group_year['State'],
y=[total_amount_group_year.loc[total_amount_group_year['As_of_Year']==2012]['Loan_Amount_000'],
total_amount_group_year.loc[total_amount_group_year['As_of_Year']==2013]['Loan_Amount_000'],
total_amount_group_year.loc[total_amount_group_year['As_of_Year']==2014]['Loan_Amount_000']])]
layout = go.Layout(title='Iris Dataset - Species',
xaxis=dict(title='Iris Dataset - Species'),
yaxis=dict(title='Count')
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)
这是我的数据框也显示索引。数据框是一个熊猫数据框,是另一个熊猫数据框的子集。
State As_of_Year Loan_Amount_000
9 VA 2012 86144.960
10 VA 2013 72210.009
6 MD 2012 54095.591
11 VA 2014 48920.527
7 MD 2013 43640.475
8 MD 2014 28235.685
0 DC 2012 8368.582
1 DC 2013 7092.372
12 WV 2012 6023.641
13 WV 2013 5838.763
3 DE 2012 5253.819
2 DC 2014 5044.787
14 WV 2014 4984.216
4 DE 2013 4598.409
5 DE 2014 2991.961
希望我过度正确地复制了这些值。我认为问题在于您试图传递给
y=
的参数数量。您的 x=
关键字还使用了与 y=
具有不同长度索引的数据框,我不确定 plotly 是否可以解释。您可以使用以下 for 循环生成所需的数据跟踪,从而生成以下图表。
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
Years = [2012, 2013, 2014]
data = []
for Year in Years:
data.append(go.Bar(x = total_amount_group_year.loc[total_amount_group_year['As_of_Year']==Year]['State'],
y=total_amount_group_year.loc[total_amount_group_year['As_of_Year']==Year]['Loan_Amount_000'],
name=Year))
fig=go.Figure(data=data)
py.iplot(fig)
或者你可以使用袖扣,我假设你已经安装了。但是,这确实需要您重塑数据框以生成分组条形图。以下代码生成下面的图表。
import cufflinks as cf
df_pivot = total_amount_group_year.pivot(index='State', columns='As_of_Year', values='Loan_Amount_000').sort_values(2012, ascending=False)
cf.set_config_file(offline=True, world_readable=False, theme='ggplot')
df_pivot.iplot(kind='bar')
希望这有帮助!