无法打印键和值

2024-09-28 21:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录如下:

collect
Out[60]: 
[{'A01': 0.07,
  'A02': 0.1,
  'A03': 0.08,
  'A04': 0.11,
  'A05': 0.05,
  'A06': 0.09,
  'A07': 0.09,
  'A08': 0.15,
  'A09': 0.17,
  'A10': 0.09},
 {'A01': 0.07,
  'A02': 0.07,
  'A03': 0.02,
  'A04': 0.22,
  'A05': 0.09,
  'A06': 0.06,
  'A07': 0.07,
  'A08': 0.26,
  'A09': 0.09,
  'A10': 0.04}]

我需要绘制这些条形图,前10个键有标签“A”,后10个键有标签“B”。我尝试使用matplotlib使用以下代码绘制它:

import matplotlib.pyplot as plt
import pandas as pd
X_AS=[]
Y_AS=[]
for i in range(len(collect)):
    x_as=collect[i].keys()  
    y_as=collect[i].values()
    X_AS.append(x_as)
    Y_AS.append(y_as)
Xlist = pd.Series(v for v in X_AS)
Ylist = pd.Series(v for v in Y_AS)
plt.bar(Xlist,Ylist, align='center', alpha=0.5)
plt.show()

但我得到了以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'dict_values'

有人能帮帮我吗?桑克斯。你知道吗


Tags: inforaspltpdcollecta01a02
1条回答
网友
1楼 · 发布于 2024-09-28 21:01:09

我想这就是你想要的阴谋。熊猫根本不用。 您应该能够修改它以获得所需的输出。你知道吗

如果您想直接使用字典键,可以考虑使用matplotlib的“categories”功能:https://matplotlib.org/gallery/lines_bars_and_markers/categorical_variables.html

import matplotlib.pyplot as plt

# use these to generate positions and add legend labels
labels = {0:'A',
         1:'B'}

# this sets the position of each set of bars
offsets = {0:-0.15,
          1:+0.15}

# define the main positions
main_positions = [i for i in range(len(collect[0]))]

## loop  each set of data in the dict using the defined labels
for label in labels:

    # generate list of values to plot
    vals = [collect[label][i] for i in sorted(collect[label])]

    # plot the data and set the tick labels
    plt.bar([main_positions[i] + offsets[label]+1 for i in main_positions],vals,width=0.3,label=labels[label])

## tidy the xticks and add legend
plt.xticks([i+1 for i in main_positions])
plt.legend()
plt.show()

bar plot

相关问题 更多 >