【问题标题】:Matplotlib, limiting number of bars in chartMatplotlib,限制图表中的条形数量
【发布时间】:2020-02-28 02:35:31
【问题描述】:

如何截断条形图以仅显示前 10 个条形图,而忽略其余的条形图? 它所绘制的数组将根据所选的特征而具有不同的大小,但通常会太多而无法有效显示。所以我想设置一个最大值。

nFeatures = dataSample.select_dtypes(include=['int64', 'float64']).columns
cFeatures = dataSample.select_dtypes(include=['category']).columns

ohe = (mainPipe.named_steps['preprocessor']
         .named_transformers_['cat']
         .named_steps['onehot'])
feature_names = ohe.get_feature_names(input_features=cFeatures)
feature_names = np.r_[feature_names, nFeatures]

tree_feature_importances = (
    mainPipe.named_steps['classifier'].feature_importances_)
sorted_idx = tree_feature_importances.argsort()

y_ticks = np.arange(0, len(feature_names))
fig, ax = plt.subplots()
ax.barh(y_ticks, tree_feature_importances[sorted_idx])
ax.set_yticklabels(feature_names[sorted_idx])
ax.set_yticks(y_ticks)
ax.autoscale(tight=True)
ax.set_title("Random Forest Feature Importances")
fig.tight_layout()
plt.show()

【问题讨论】:

  • @Kaushal28 看到了,我尝试了 [:10] 和 .head(10) 但都没有成功,但也有可能我不知道正确的传递位置。
  • ax.barh(y_ticks[:10], tree_feature_importances[sorted_idx][:10])
  • 如果两者都是 python/numpy 列表
  • 那一半有效,它给了我左侧 10 个标签的列表,但没有显示条形。我尝试添加 ax.set_yticklabels(feature_names[sorted_idx][:10]) ax.set_yticks(y_ticks[:10]) 但没有帮助。

标签: python pandas matplotlib scikit-learn


【解决方案1】:

使用 iloc。

df.iloc[0:10].plot.bar()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2016-01-02
    相关资源
    最近更新 更多