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

求助排查Python数据可视化代码中的语法错误

Python数据可视化代码语法错误排查

问题现象

运行员工年龄分组性别对比水平条形图代码时,触发SyntaxError,错误提示为:

SyntaxError: positional argument follows keyword argument

错误指向代码中tabel["Perempuan"].plot(...)里的xlim[0, 550]部分。

错误原因

代码中这一行的xlim[0, 550]缺少赋值符号=,导致Python将其解析为位置参数,但它前面已经出现了fontsize=14这类关键字参数。根据Python语法规则,位置参数必须放在关键字参数之前,因此触发语法错误。

对比正确写法:tabel["Laki-laki"].plot(...)中使用的是xlim=[-550, 0](带=的关键字参数形式),这是符合语法要求的。

修正后的完整代码

import pandas as pd
import matplotlib.pyplot as plt

tabel = (pd.read_csv("https://storage.googleapis.com/dqlab-dataset/usia_karyawan.csv")
         .sort_values("Kelompok Usia", ascending=False)
         .set_index("Kelompok Usia")
        )
tabel["Laki-laki"] = -tabel["Laki-laki"]

fig, axes = plt.subplots(1, 2, figsize=(14, 6))
fig.suptitle("Perbandingan Jumlah Karyawan Laki-laki dan Perempuan\nBerdasarkan Kelompok Usia",
            x=0., y=1.0, fontsize=24, fontweight="bold", ha="left")
tabel["Laki-laki"].plot(kind="barh", ax=axes[0], color="tab:blue", xlim=[-550, 0])
# 修正:给xlim加上赋值符号=
tabel["Perempuan"].plot(kind="barh", ax=axes[1], color="tab:orange", fontsize=14, xlim=[0, 550])
axes[0].set_ylabel("")
axes[0].tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)
axes[0].legend(["Laki-laki"], fontsize=14, bbox_to_anchor=(0., 0., 1., .05))
axes[0].set_frame_on(False)
axes[1].set_ylabel("")
axes[1].tick_params(left=False, bottom=False, labelbottom=False)
axes[1].legend(["Perempuan"], fontsize=14, bbox_to_anchor=(0., 0., 0.3, .05))
axes[1].set_frame_on(False)
for i, m, w in zip(range(tabel.shape[0]), list(tabel["Laki-laki"]), list(tabel["Perempuan"])):
    axes[0].annotate(str(abs(m)), (m+20, i), xytext=(m+20, i),
                     color="w", va="center", ha="center", fontsize=14)
    axes[1].annotate(str(abs(w)), (w-20, i),xytext=(w-20, i),
                     color="w", va="center", ha="center", fontsize=14)
plt.tight_layout(rect=(0,0,1,0.88))
plt.show()

内容的提问来源于stack exchange,提问作者Dian Fadlu Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:15:43