我正在尝试使用 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/