将图例显示为可绘制python中条形图的x轴标签

时间:2020-03-17 11:30:45

标签: python charts plotly visualization

我正在以图表方式绘制组条形图,其中我已在条形图中映射了多行。这是解释我所做的代码:

data = [{"Project":"Project A","Features":{"AC":95,"Elec":130, "Area":2349.46, "Cars":30, "Rent":2345.00},"ScaledFeatures":{"AC":95,"Elec":130, "Area":2349.46, "Cars":30, "Rent":2345.00}},
{"Project":"Project B","Features":{"AC":95,"Elec":130, "Area":2120.00, "Cars":42, "Rent":5432},"ScaledFeatures":{"AC":95,"Elec":130, "Area":2120.00, "Cars":42, "Rent":2345}}
       ]
featureKeys = list(data[0]["Features"].keys())

for key in featureKeys:
    featureData = ([d["ScaledFeatures"][key] for d in data])
    minimumFeatureValue = min(featureData)
    for d in data:
        d["ScaledFeatures"][key] = d["ScaledFeatures"][key]/minimumFeatureValue

barData = []
for d in data:
    barData.append(go.Bar(name=d['Project'], x=featureKeys, y=list(d["ScaledFeatures"].values()),text=list(d["Features"].values()),textposition='auto'))

# set plot layout  
layout = go.Layout(
    xaxis={"mirror" : "allticks", 'side': 'top'} # x-axis also at top
)

fig = go.Figure(data=barData,layout=layout)

# Change the bar mode
#fig.update_traces(textposition='outside')
fig.update_layout(barmode='group')
fig.show()

这是它生成的输出:

Current Output

我想从中生成以下类似输出,其中图例在x轴上出现:

Required Output

到目前为止,我所做的是使用多个轴,但是在同一张图表上绘制了自己的条形图。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

您可以在此处使用多类别x轴,如this example中所示。但是,您将在同一侧同时使用A / B和AC / Elec等。如果您不想使用此功能,则可以使用注释https://plot.ly/python/text-and-annotations/#simple-annotation。另外,在这里您可以考虑使用px.bar中的plotly.expresshttps://plot.ly/python/bar-charts/