python - 为什么我的格式化程序函数接收索引而不是轴值?

标签 python pandas matplotlib

我正在尝试使用 pandas 和 matplotlib 创建图表,同时关注 a tutorial 。我没有解决这个问题的现实世界问题,我只是想理解。

我试图缩短条形图轴上的一些名称,但由于某种原因,索引似乎被传递到我的格式化程序函数中。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

df = pd.DataFrame({'Name':['Jake', 'Finn'], 'Score':[4, 6]})

def does_nothing(value, pos):
    return value

fix, ax = plt.subplots()
df.plot(kind='bar', x="Name", y="Score", ax=ax)
formatter = FuncFormatter(does_nothing)
ax.xaxis.set_major_formatter(formatter)

无需尝试格式化轴,我就得到了我所期望的结果 - Jake 和 Finn 在我的轴上。但是如果我将它传递给格式化程序,我会得到 0 和 1。为什么会发生这种情况?那么我如何获取字符串呢?

最佳答案

使用它,ax=ax 将其重置为索引:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

df = pd.DataFrame({'Name':['Jake', 'Finn'], 'Score':[4, 6]})

def does_nothing(value, pos):
    return value

fix, ax = plt.subplots()
df.plot(kind='bar', x="Name", y="Score")
formatter = FuncFormatter(does_nothing)
ax.xaxis.set_major_formatter(formatter)

关于python - 为什么我的格式化程序函数接收索引而不是轴值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59450338/

相关文章:

python - 如何在python中使用带有mysql变量的select语句

python - AWS CDK : Invalid ARN for CloudWatch Logs when using LogGroup. log_group_arn

python - 同一索引的多个列

Python:根据这些分箱对一个坐标进行分箱并平均另一个坐标

python - 如何避免 python 在屏蔽数据后使用 UserWarning 进行隐式修复

pandas - Matplotlib:如何使用 pandas plot api 在散点图中绘制一个空圆?

python - 具有元组键和两个列表作为值的字典,其中一个值仅添加到列表之一

python - 如何将 python 表达式嵌入到 :s command in vim?

python - 如何使用 python 更改 matplotlib 中 x 轴值的日期时间格式?

python - Pandas - 在同一列中格式化不同格式的日期列