使用Jupyter Notebook绘制20个高盈利产品柱状图:product_id标签问题求解
解决柱状图中product_id未作为标签显示的问题
问题出在默认绘图逻辑上:你当前的代码没有指定x轴标签列,pandas会自动用行索引作为x轴标识,而product_id作为数值型列,并没有被当作分类标签展示。下面是几种可行的修正方案:
方案一:将product_id设为索引后绘图
Sales['total_revenue'] = Sales['unit_price']*Sales['quantity'] Sales = Sales.drop(['sales_id', 'unit_price', 'quantity', 'due_date', 'ship_date', 'discounted'], axis=1) # 取前20条并设置product_id为索引 Sales_top20 = Sales.sort_values(['total_revenue'], ascending=False).head(20) Sales_top20.set_index('product_id', inplace=True) Sales_top20.plot(kind='bar', figsize=(20,5))
方案二:绘图时明确指定x、y轴列
Sales['total_revenue'] = Sales['unit_price']*Sales['quantity'] Sales = Sales.drop(['sales_id', 'unit_price', 'quantity', 'due_date', 'ship_date', 'discounted'], axis=1) Sales_top20 = Sales.sort_values(['total_revenue'], ascending=False).iloc[:20] # 直接指定x为product_id,y为total_revenue Sales_top20.plot(kind='bar', x='product_id', y='total_revenue', figsize=(20,5))
方案三:将product_id转为字符串类型(强制作为分类标签)
如果product_id是数值类型但你希望它被当作纯标签而非数值处理,可以转成字符串:
Sales['total_revenue'] = Sales['unit_price']*Sales['quantity'] Sales = Sales.drop(['sales_id', 'unit_price', 'quantity', 'due_date', 'ship_date', 'discounted'], axis=1) Sales_top20 = Sales.sort_values(['total_revenue'], ascending=False).iloc[:20] # 转换为字符串类型 Sales_top20['product_id'] = Sales_top20['product_id'].astype(str) Sales_top20.plot(kind='bar', x='product_id', y='total_revenue', figsize=(20,5))
内容的提问来源于stack exchange,提问作者ggeryz
相关产品推荐
相关产品推荐

