这是我最后的字典
{'1': {'Pen': [0.99], 'Note': [1.62]},
'2': {'Pen': [1.94], 'Note': [2.17]}}
我试图在python中使用plotly绘制组条形图,我得到了我的x值。 [x for x in cdict.keys() for k,v in cdict.items()]
我无法正确地获得Y值。
试试。
y_pen = [cdict[j]["Pen"][0] for j in cdict]
y_note = [cdict[j]["Note"][0] for j in cdict]
y_pen:
[0.99, 1.94]
y_note:
[1.62, 2.17]
在我看来,这就是你要找的东西。
如果是这样的话,你必须为x值做一个列表,比如说 ['Pen', 'Note']
并检索y值的列表,如 [[0.99, 1.94], [1.62, 2.17]]
.
完整的代码。
# imports
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
import numpy as np
cdict = {'1': {'Pen': [0.99], 'Note': [1.62]},
'2': {'Pen': [1.94], 'Note': [2.17]}}
# get x-values, in this case ['Pen', 'Note']
xVals = list([cdict[k].keys() for k in cdict.keys()][0])
# get y-values, in this case [[0.99, 1.94], [1.62, 2.17]]
yVals = []
for x in xVals:
yVals.append([cdict[j][x][0] for j in cdict])
# set up plotly figure
fig=go.Figure()
# add trace for each element in yVals
for i, y in enumerate(yVals):
fig.add_traces(go.Bar(x=xVals, y=y, name = 'Group'+str(i+1)))
fig.show()