How do I pass a list to a bar chart using matplotlib?

16 Views Asked by At

housing_data.feature_names returns a list of features, i'm trying to plot those features on the x-axis of the bar chart.

I have tried passing it directly using this {feature_names = list(housing_data.feature_names)}

import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn import datasets
from sklearn.metrics import mean_squared_error, explained_variance_score
from sklearn.model_selection import cross_validate
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle

# Load housing data
housing_data = datasets.fetch_california_housing()
# Split data into training and testing datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=7)
# AdaBoost Regressor model
regressor = AdaBoostRegressor(DecisionTreeRegressor(max_depth=4), n_estimators=400, random_state=7)

regressor.fit(X_train, y_train)
# Evaluate performance of AdaBoost regressor
y_pred = regressor.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
evs = explained_variance_score(y_test, y_pred )
print("\nADABOOST REGRESSOR")
print("Mean squared error =", round(mse, 2))
print("Explained variance score =", round(evs, 2))
# Extract feature importances
feature_importances = regressor.feature_importances_
feature_names = list(housing_data.feature_names)
# Sort the values and flip them
index_sorted = np.flipud(np.argsort(feature_importances))
# Arrange the X ticks
pos = np.arange(index_sorted.shape[0]) + 0.5
index_labels = np.arange(len(feature_names))
plt.figure()
plt.bar(pos, feature_importances[index_sorted], color ='maroon', width = 0.4)
plt.xticks(pos, feature_names[index_sorted])
plt.ylabel('Relative Importance')
plt.title('Feature importance using AdaBoost regressor')
plt.show()````
0

There are 0 best solutions below