Skip to main content
 首页 » 编程设计

python之如何旋转 matplotlib 条形图

2024年11月24日8落叶无声

以下代码用于生成条形图。我想旋转它,使其变得垂直,例如x 轴上的当前标签到 y 轴,当前 y 轴标签到 x 轴,并且条形相应地旋转。

我是 matplotlib 和 python 的新手,所以欢迎任何帮助。

def plot_coefficients(classifier, feature_names, top_features=40): 
 
    if classifier.__class__.__name__ == 'SVC': 
        coef = classifier.coef_ 
        coef2 = coef.toarray().ravel() 
        coef1 = coef2[:len(feature_names)]   
    else: 
        coef2 = classifier.coef_.ravel() 
        coef1 = coef2[:len(feature_names)] 
 
    top_positive_coefficients = np.argsort(coef1)[-top_features:] 
    top_negative_coefficients = np.argsort(coef1)[:top_features] 
    top_coefficients = np.hstack([top_negative_coefficients, top_positive_coefficients]) 
     # create plot 
    plt.figure(figsize=(15, 5)) 
    colors = ['red' if c < 0 else 'blue' for c in coef1[top_coefficients]] 
    plt.bar(np.arange(2 * top_features), coef1[top_coefficients], color=colors) 
    feature_names = np.array(feature_names) 
    plt.xticks(np.arange(1, 1 + 2 * top_features), feature_names[top_coefficients], rotation=90, ha='right') 
    plt.show() 
 

更新 预期输出:

请您参考如下方法:

查看matplotlib方法barh。您可以从以下位置找到示例:https://matplotlib.org/gallery/lines_bars_and_markers/barh.html