You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas绘制子图报错:float()参数应为字符串或数字而非'AxesSubplot'

解决Pandas子图绘制报错:float() argument must be a string or a number, not 'AxesSubplot'

错误原因分析

你代码里的核心问题出在最后两行:

ax[0].plot(graph_sex_and_wellbeing)
ax[1].plot(graph_sex_and_wellbeing3)
  • graph_sex_and_wellbeing3是你调用sex_and_wellbeing.plot()后得到的**AxesSubplot对象**(也就是已经画好的坐标轴实例),而ax[1].plot()方法需要的是可绘制的数值数据(比如DataFrame、Series),不是现成的轴对象,这就导致了类型不匹配的报错。
  • 另外graph_sex_and_wellbeing这个变量你没在代码里定义,推测你是想指代处理好的sex_and_wellbeing数据框?

修复方案:直接在子图轴上绘制数据

正确的做法是先创建子图,然后指定每个子图的轴来绘制数据,而不是先单独绘图再把轴对象塞进子图里。下面是修正后的完整代码:

import pandas as pd
import matplotlib.pyplot as plt

colours = ['#F5DEB3', '#528B8B', '#9E9E9E', '#FFA500']

# 数据处理部分保持不变
sex_and_wellbeing = results_redditThread_df.groupby(['pay_for_sex'])[['bodyweight']].apply(lambda x: pd.DataFrame(x['bodyweight'].value_counts()))
sex_and_wellbeing = sex_and_wellbeing.unstack()

# 创建2行1列的子图,设置整体尺寸
fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(20, 26))  # 调整高度适配两个子图

# 在第一个子图绘制柱状图
sex_and_wellbeing.plot(kind='bar', ax=ax0, color=colours, rot=0, fontsize=21)
ax0.set_title('Number of People who would Pay for Sex based on Bodyweight', fontsize=24)
ax0.set_xlabel('Sex payments', fontsize=21)
ax0.set_ylabel('Number of People with Certain Weight', fontsize=21)
ax0.legend(['Normal Weight', 'Obese', 'Overweight', 'Underweight'], loc='best', ncol=1, fontsize=15)

# 第二个子图示例:如果要绘制同一数据的折线图(你可以根据需求替换成其他数据/图表类型)
sex_and_wellbeing.plot(kind='line', ax=ax1, color=colours, fontsize=21)
ax1.set_title('Trend of Bodyweight vs Sex Payment Preference', fontsize=24)
ax1.set_xlabel('Sex payments', fontsize=21)
ax1.set_ylabel('Count', fontsize=21)
ax1.legend(['Normal Weight', 'Obese', 'Overweight', 'Underweight'], loc='best', fontsize=15)

# 调整子图间距,避免标题和标签重叠
plt.tight_layout()
plt.show()

关键改动说明

  • 直接通过plt.subplots()创建子图轴对象ax0和ax1,然后在调用plot()时通过ax参数指定要绘制的子图轴。
  • 移除了单独创建graph_sex_and_wellbeing3的步骤,转而直接在子图轴上完成绘图和样式设置。
  • 添加了plt.tight_layout()自动调整子图间距,避免元素重叠。

内容的提问来源于stack exchange,提问作者Blank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:07:51