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

如何将Matplotlib生成的图表X轴数值替换为自定义名称?

解决X轴数值替换为名称的简便方法

以下是几种快速替换X轴刻度的方案,适配你的柱状图和饼图需求:

方案1:读取Excel时直接指定名称列为索引

如果你的Excel表格里有专门存储名称的列(比如列名是Name),读取数据时直接将该列设为DataFrame的索引,绘图时X轴会自动显示名称:

import pandas as pd
import matplotlib.pyplot as plt

def DrawGraphDamagePerSecond(data): 
    data.plot(kind='bar')  # 改用传入的data参数,避免写死变量
    plt.xlabel('Name')
    plt.ylabel('DPS')
    plt.title('Damage Per Second')
    plt.show()

excel = pd.ExcelFile('path to my excel')
# 假设名称列的列名是"Name",用index_col指定该列为索引
damageDone = pd.read_excel(excel, 'Damage Done', decimal=',', index_col='Name')
healingDone = pd.read_excel(excel, 'Healing Done', decimal=',')

DrawGraphDamagePerSecond(damageDone)

方案2:手动设置X轴刻度与标签

如果不想修改DataFrame结构,可在绘图后手动指定X轴的刻度位置和对应名称:

import pandas as pd
import matplotlib.pyplot as plt

def DrawGraphDamagePerSecond(data): 
    ax = data.plot(kind='bar')
    # 替换成你实际的名称列表,注意要和数据行顺序对应
    names = ["角色1", "角色2", "角色3"]
    ax.set_xticks(range(len(names)))
    ax.set_xticklabels(names, rotation=45)  # rotation调整标签角度,避免重叠
    plt.xlabel('Name')
    plt.ylabel('DPS')
    plt.title('Damage Per Second')
    plt.show()

excel = pd.ExcelFile('path to my excel')
damageDone = pd.read_excel(excel, 'Damage Done', decimal=',')
healingDone = pd.read_excel(excel, 'Healing Done', decimal=',')

DrawGraphDamagePerSecond(damageDone)

方案3:先修改DataFrame索引再绘图

如果已经读取了数据,可事后将名称列赋值给DataFrame的索引:

import pandas as pd
import matplotlib.pyplot as plt

def DrawGraphDamagePerSecond(data): 
    data.plot(kind='bar')
    plt.xlabel('Name')
    plt.ylabel('DPS')
    plt.title('Damage Per Second')
    plt.show()

excel = pd.ExcelFile('path to my excel')
damageDone = pd.read_excel(excel, 'Damage Done', decimal=',')
# 假设名称列是"Name",将其设为索引
damageDone.set_index('Name', inplace=True)
healingDone = pd.read_excel(excel, 'Healing Done', decimal=',')

DrawGraphDamagePerSecond(damageDone)

饼图适配提示

绘制饼图时,可通过labels参数直接替换默认数值标签:

def DrawPieChart(data):
    # 用DataFrame的索引作为饼图标签
    data.plot(kind='pie', y='DPS列名', labels=data.index)
    # 若名称在单独列中,可替换为:labels=data['Name']
    plt.title('DPS占比')
    plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:01:03