Two remarks on your code:
There seems to be an indentation error in your code, everything before your first for loop has too much indentation.
In general, it is a good idea to use telling names for variables. For example,
column
androw
instead ofa
andb
.
Following is my version of the code. It is not an exact reproduction of your plot, but the way I would approach an analysis like this:
from sklearn.datasets import load_iris
import pandas as pd
import seaborn as sns
iris = load_iris()
# convert dataset to pandas DataFrame
iris_df = pd.DataFrame(iris['data'])
iris_df.columns = iris['feature_names']
iris_df['species'] = iris['target']
iris_df['species'] = iris_df['species'].replace([0, 1, 2], iris['target_names'])
# alternative: load dataset from seaborn library (they use slightly different column names)
# iris_df = sns.load_dataset('iris')
sns.pairplot(data=iris_df, corner=True, hue='species')
This produces the following plot:
As you can see, the code has become much shorter and the resulting figure still contains all the plots you wanted (plus a few extra ones). Great thing about using pandas and other related libraries (e.g., seaborn) is that you can often write very compact code (e.g., by getting rid of many for loops).
First, I converted the iris dataset to a pandas DataFrame
(documentation). A DataFrame
is the main data type in pandas and makes analysis and processing of your data much easier. As shown in the code, there is an alternative way of loading the iris dataset into python using the seaborn library (sns.load_dataset('iris')
) This will give you the dataset directly as a DataFrame
, no more need to convert it.
Then, I call pairplot
from the seaborn library. seaborn is a plotting library based on matplotlib that works with DataFrame
objects. It has a high-level interface, meaning you can produce complex plots such as the one you see with often a few lines of code.
I just found out that pandas already has a very similar plot function, check out pd.scatter_matrix. So you don't necessarily need to use seaborn (even though it's a great library and I recommend it).