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

解决Python透视表绘图中'px未定义'错误及转垂直柱状图

问题解决:NameError及折线图转垂直柱状图

一、解决NameError: name 'px' is not defined错误

px是Plotly Express库的常用别名,出现该错误是因为未导入对应库。解决步骤:

  1. 若未安装Plotly,先通过pip安装:
pip install plotly
  1. 在代码开头添加导入语句:
import plotly.express as px

完成后原折线图代码即可正常运行。

二、将折线图修改为垂直柱状图

只需把px.line替换为px.bar,推荐添加barmode='group'让不同用户类型的柱子并排展示,其余配置参数可复用原代码。修改后的完整代码:

fig_2 = union3.groupby(['year', 'month', 'member_casual'], as_index=False).count()
fig_2 = fig_2[fig_2['ride_id'] != 0]

fig_2_bar = px.bar(fig_2, x = 'month', y = 'ride_id', range_y = [0,450000],
        color = 'member_casual', 
        barmode='group',  # 使不同类别柱子并排显示
        labels = {'ride_id': 'No. of Rides', 'month': 'Months (Oct 2020 - Sep 2021)', 'member_casual': 'Member/Casual'},
        hover_name = 'member_casual', hover_data = {'member_casual': False, 'month': True, 'ride_id': True}, 
        color_discrete_map = {'casual': '#FF934F', 'member': '#058ED9'})

fig_2_bar.show()  # 展示生成的柱状图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:20:27