Matplotlib图表针对特定输入数据时轴标注与文本不显示的问题排查求助
Matplotlib图表针对特定输入数据时轴标注与文本不显示的问题排查求助
我在用Python的Matplotlib绘图时碰到了一个头疼的问题:针对某些特定的输入数据,图表的轴标注和文本注释完全不显示,但换另一些数据又能正常展示。我翻来覆去对比了多组数据,实在找不到出问题的数据有什么共性,想请大家帮忙看看我的代码是不是有哪里遗漏的问题。
我的代码如下:
df = pd.read_csv(os.path.join(input_path, "data.csv"), sep=",") category = df.columns[1] items = df[df.columns[0]] _, ax = plt.subplots(figsize=(10, 6)) x_coordinates = np.arange(len(items)) ax.plot( x_coordinates, list(df[category]), label=category.title(), ) ax.set_xlabel(items.name.title()) ax.set_ylabel(category.title()) ax.set_title("Test chart", wrap=True) ax.set_xticks(x_coordinates, [str(item).title() for item in items]) y_coordinates = list(df[df.columns[1]]) x_coordinates = list(items) for x_coordinate, y_coordinate in zip(x_coordinates, y_coordinates): ax.text( x_coordinate - 1, y_coordinate, y_coordinate, # This is the text that should be displayed dict(zorder=10, size=10, color="black", ha="center"), ) plt.savefig("output.png")
先看第一组能正常显示的data.csv数据:
week,attendance 1,74788 2,74884 3,57677 4,74879 5,52632 6,74997 7,74292 8,49699 9,74908 10,74482 11,74379 12,42910 13,74186 14,37886 15,60038
这组数据生成的图表,文本/注释都能正确显示:
但换成下面这组data.csv数据时,问题就出现了:
year,purse 2001,60000 2002,60000 2003,60000 2004,70000 2005,70000 2006,85000 2007,100000 2008,100000 2009,110000 2010,120000 2011,120000 2012,100000 2013,100000
生成的图表里完全看不到标注内容:
我还试了用ax.annotate(它本质也是基于ax.text实现的),结果遇到了同样的问题:
ax.annotate( value_label, xy=(x_coordinate - 1, y_coordinate), textcoords="offset points", xytext=(0, 0), zorder=10, )
我特意调试了传入.text和.annotate的所有参数,确认数值都是正确的,但就是看不到标注。真的快愁死了,希望有人能帮我找出问题所在!
备注:内容来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

