ValueError:FixedLocator 位置的数量 (5),通常来自对 set_ticks 的调用,与滴答标签的数量 (12) 不匹配

新手上路,请多包涵

这段代码之前是工作的,但是,在创建一个新环境之后,它停止工作了

plt.xticks(x, months, rotation=25,fontsize=8)

如果我评论这一行然后没有错误,把这行错误抛出后

ValueError: The number of FixedLocator locations (5), usually from a call to set_ticks, does not match the number of ticklabels (12).


 import numpy as np
import matplotlib.pyplot as plt

dataset = df
dfsize = dataset[df.columns[0]].size
x = []
for i in range(dfsize):
    x.append(i)

dataset.shape
# dataset.dropna(inplace=True)
dataset.columns.values
var = ""
for i in range(dataset.shape[1]):  ## 1 is for column, dataset.shape[1] calculate length of col

    y = dataset[dataset.columns[i]].values
    y = y.astype(float)
    y = y.reshape(-1, 1)
    y.shape
    from sklearn.impute import SimpleImputer

    missingvalues = SimpleImputer(missing_values=np.nan, strategy='mean', verbose=0)
    missingvalues = missingvalues.fit(y)
    y = missingvalues.transform(y[:, :])

    from sklearn.preprocessing import LabelEncoder, OneHotEncoder
    from sklearn.compose import ColumnTransformer

    labelencoder_x = LabelEncoder()
    x = labelencoder_x.fit_transform(x)

    from scipy.interpolate import *

    p1 = np.polyfit(x, y, 1)
    # from matplotlib.pyplot import *
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    plt.figure()
    plt.xticks(x, months, rotation=25,fontsize=8)
    #print("-->"+dataset.columns[i])
    plt.suptitle(dataset.columns[i] + ' (xyz)', fontsize=10)
    plt.xlabel('month', fontsize=8)
    plt.ylabel('Age', fontsize=10)
    plt.plot(x, y, y, 'r-', linestyle='-', marker='o')
    plt.plot(x, np.polyval(p1, x), 'b-')
    y = y.round(decimals=2)
    for a, b in zip(x, y):
        plt.text(a, b, str(b), bbox=dict(facecolor='yellow', alpha=0.9))

    plt.grid()
    # plt.pause(2)
    # plt.grid()

    var = var + "," + dataset.columns[i]
    plt.savefig(path3 + dataset.columns[i] + '_1.png')
    plt.close(path3 + dataset.columns[i] + '_1.png')
    plt.close('all')

原文由 user5635636 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 5.2k
2 个回答

我也偶然发现了这个错误,发现让你的 xtick_labels 和 xticks 成为一个等长的列表是可行的。所以在你的情况下是这样的:

 def month(num):
  # returns month name based on month number

num_elements = len(x)
X_Tick_List = []
X_Tick_Label_List=[]

for item in range (0,num_elements):
    X_Tick_List.append(x[item])
    X_Tick_Label_List.append(month(item+1))

plt.xticks(ticks=X_Tick_List,labels=X_Tick_LabeL_List, rotation=25,fontsize=8)


原文由 Eugene_E 发布,翻译遵循 CC BY-SA 4.0 许可协议

我正在使用子图并遇到了同样的错误。我注意到如果重新标记的轴(在我的例子中是 y 轴)显示所有标签,错误就会消失。如果没有,则会出现您标记的错误。我建议增加图表高度,直到默认显示所有 y 轴标签(见下面的屏幕截图)。

或者,我建议使用 ax.set_xticks(...) 定义 FixedLocator 刻度位置,然后 ax.set_xticklables(...) 设置标签。

绘制第 2 个 y 轴标签

使用自定义标签绘制和覆盖的每个 y 轴标签

原文由 Vlad Stefan Zamfir 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题