【解决方案】使用matplotlib报错 TypeError: unsupported operand type(s) for -: ‘str‘ and ‘float‘

【解决方案】使用matplotlib报错 TypeError: unsupported operand type(s) for -: ‘str’ and ‘float’

绘制柱状图时

"""
yolo格式标注文件统计
"""
import os

img_path = './images'
label_path = img_path.replace('images', 'labels') 

label_names = ['car', 'chair']
label_files = os.listdir(label_path)

object_struct = {}

for name in label_files:
    file_path  = os.path.join(label_path, name)
    with open(file_path) as f:
        for f1 in f.readlines():
            box = []
            f1 = f1.replace('\n', '').strip().split(' ')
            box = [x for x in f1]
            # print(box)
            cls_id = box[0]
            x1 = box[1]
            y1 = box[2]
            x2 = box[3]
            y2 = box[4]
            if cls_id not in object_struct:
                object_struct[cls_id] = 0
            object_struct[cls_id] += 1

print(object_struct)
        

import matplotlib.pyplot as plt
object = []
number = []
for name_key in object_struct:
    if len(label_names) != 0:
        object.append(label_names[int(name_key)])
    else:
        object.append(name_key)
    
    number.append(object_struct[name_key])

print(object, '\n', number)

plt.figure()

# 低版本matplotlib方法
# idx = range(len(object))
# plt.xticks(idx, object)
# plt.bar(idx, number)

# 高版本matplotlib方法
plt.bar(object, number)

plt.title('result')
plt.show()

报错以下信息:
在这里插入图片描述
报错原因:
轴不能用 字符串列表

解决方案:
字符串列表转化为数字列表,再把数字列表和字符串列表组合起来
使用高版本的matplotlib=3.x就不存在这个问题,matplotlib=2.x会出现这个报错

# 低版本matplotlib方法
# idx = range(len(object))
# plt.xticks(idx, object)
# plt.bar(idx, number)

# 高版本matplotlib方法
plt.bar(object, number)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

修炼清爽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值