Skip to content Skip to sidebar Skip to footer

Sort Bar Chart By List Values In Matplotlib

I am encountering an issue regarding the sorting my features by their value. I would like to see my image with bars getting shorter based on high they are on the y axis. Unfortunat

Solution 1:

EDIT (based on the comments)

Your code works fine on matplotlib 2.2.2 and the issue seems to be with your list naming convention and some confusion among them. It will work as expected on 3.0.2. Nevertheless, you might be interested in knowing the workaround

features_sorted = []
importance_sorted = []

for i in sorted_list:
    features_sorted += [i[1]]
    importance_sorted += [i[0]]

plt.title("Feature importance", fontsize=15)
plt.xlabel("Importance", fontsize=13)

plt.barh(range(len(importance_sorted)), importance_sorted, color="green", edgecolor='green')
plt.yticks(range(len(importance_sorted)), features_sorted);

enter image description here

Alternative suggested by @tmdavison

plt.barh(range(len(importance_sorted)), importance_sorted, color="green", 
     edgecolor='green', tick_label=features_sorted)

Solution 2:

To avoid confusion from the other answer here, note that the code in the question runs fine and gives the desired output for any version of matplotlib >= 2.2.

import matplotlib
print(matplotlib.__version__)import matplotlib.pyplot as pltsorted_list= [(0.0017821837085763366, 'Activity'),
 (0.002649111136700579, 'PeakAccel'),
 (0.012697214182994502, 'VerticalPeak'),
 (0.014534726412631642, 'ROGState'),
 (0.016099772399198357, 'VerticalMin'),
 (0.022745210003295983, 'LateralPeak'),
 (0.028845102569277088, 'SagittalPeak'),
 (0.029479112475744584, 'LateralMin'),
 (0.04062328177704225, 'BR'),
 (0.08653071485979484, 'SagittalMin'),
 (0.09011618483921582, 'Posture'),
 (0.13598729040097057, 'HRV'),
 (0.22986192060475388, 'ROGTime'),
 (0.28804817462980353, 'HR')]

features_sorted = []
importance_sorted = []

for i in sorted_list:
    features_sorted += [i[1]]
    importance_sorted += [i[0]]

plt.title("Feature importance", fontsize=15)
plt.xlabel("Importance", fontsize=13)

plt.barh(features_sorted, importance_sorted, color="green", edgecolor='green')
plt.show()

enter image description here

The issue OP reports about is most probably caused by naming distinct lists by the same name and not restarting the kernel in between or similar non-reproducible things.

Post a Comment for "Sort Bar Chart By List Values In Matplotlib"