首页 > 解决方案 > + 的错误不支持的操作数类型:“int”和“method”

问题描述

我的条形图有什么问题?
当我在这个 y 轴上使用变量名称时,条形图不显示
y = [totalMales, totalFemales] # if I input numerical values it works, but it doesn't with variable names

#check total number of males
totalMales = newDF.loc[(newDF.Gender=='Male')].count #409
print("totalMales" + str(totalMales))


totalFemales = newDF.loc[(newDF.Gender=='Female')].count()  #77
print("totalFemales" + str(totalFemales))

#males are more likely to borrow than females 409 > 77

plt.style.use('ggplot')

x = ['Males', 'Females']
y = [totalMales, totalFemales]  # if I input numerical values it works, but it doesn't with variable names

x_pos = [i for i, _ in enumerate(x)]

plt.bar(x_pos, y, color='green')
plt.xlabel("Gender")
plt.ylabel("Total who Paid Off")
plt.title("Number of Males vs Females who Paid Off")

plt.xticks(x_pos, x)

plt.show()

图像图

标签: python-3.xpandasmatplotlib

解决方案


当您拥有 DataFrame 时,可以使用更多内置函数。随着value_counts某一列中的不同值被计算并作为一个系列返回。使用.plot.bar()它可以直接在条形图中绘制。x-as 上的标签直接代表不同的性别。

    # Count the values
    gender_count = newDF.Gender.value_counts()
    
    # Create plot
    gender_count.plot.bar()
    
    # Settings for plot
    plt.style.use('ggplot')
    plt.xlabel("Gender")
    plt.ylabel("Total who Paid Off")
    plt.title("Number of Males vs Females who Paid Off")
    plt.show()

推荐阅读