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

使用plt.bar绘制柱状图时X轴刻度替换失败求助

解决X轴刻度标签不显示的问题

问题分析

你的代码里tick_locations完全等同于x_axis,这段循环属于冗余代码。X轴标签无法正常显示,大概率是以下两个原因:

  • drug_name是嵌套结构(比如每个元素是子列表/子数组),无法直接作为刻度标签使用
  • 标签内容过长导致挤压重叠,无法正常展示

修改后的代码

import numpy as np
import matplotlib.pyplot as plt

# 先处理drug_name的结构,确保是一维文本列表
# 如果原数据是嵌套格式,提取每个元素的实际药名
drug_name = [name[0] if isinstance(name, (list, np.ndarray)) else name for name in drug_name]

x_axis = np.arange(len(drug_name))
plt.bar(x_axis, total_tp_per_drug, facecolor="orangered", alpha=0.75, align="center")
# 设置刻度标签,同时旋转避免重叠,调整对齐方式
plt.xticks(x_axis, drug_name, rotation=45, ha='right')
plt.tight_layout()  # 自动调整布局,防止标签被图表边缘截断
plt.show()

关键调整点

  • 移除冗余的tick_locations循环,直接使用x_axis作为刻度位置
  • 扁平化drug_name结构,确保每个元素都是可直接显示的文本
  • 通过rotation=45和ha='right'旋转标签,避免横向挤压重叠
  • 用plt.tight_layout()自动适配图表布局,保证标签完整显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:06:27