Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate matplotlib bar-chart?

The following code is used to produce a barchart. I would like to rotate it so that it becomes vertical e.g. the current labels at the x axis go to the y axis ,the current y axis labels to the x axis and the bars rotate accordingly.

I am new to matplotlib and python so any help would be welcomed.

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()

enter image description here

Update Expected output: enter image description here

like image 350
Stamatis Tiniakos Avatar asked Jul 12 '19 09:07

Stamatis Tiniakos


People also ask

How do I rotate a graph in Matplotlib?

MatPlotLib with PythonMake a tuple of axes extremes. Add a mutable 2D affine transformation, "t". Add a rotation (in degrees) to this transform in place. Add a transform from the source (curved) coordinate to target (rectilinear) coordinate.

How do you rotate the Xticks in a bar chart?

Using plt. xticks(x, labels, rotation='vertical'), we can rotate our tick's label.


1 Answers

Look at the matplotlib method barh. You can find example from: https://matplotlib.org/gallery/lines_bars_and_markers/barh.html

like image 197
msi_gerva Avatar answered Sep 30 '22 09:09

msi_gerva