Reputation: 17164
I was wondering how to change the color of matplotlib AxisSubplot
object.
Here is the MWE:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
p = df.hist('sepal_length',by='species',layout=(3,1))
p[0].set(title='Changed')
p[0].set(facecolor='b')
plt.tight_layout()
plt.show()
print(type(p[0])
matplotlib.axes._subplots.AxesSubplot
I want the color of histogram to be blue, not the background.
p[0] ==> red
p[1] ==> green
p[2] ==> blue
something like
p[0].set_color('r')
p[1].set_color('g')
p[2].set_color('b')
Upvotes: 2
Views: 1247
Reputation: 17164
You can try this:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
n_unq = df['species'].nunique()
colors = (list('rgbcmyk')*100)[:n_unq]
xmin = np.min(df['sepal_length'])
xmax = np.max(df['sepal_length'])
fig, ax = plt.subplots(n_unq,1,figsize=(12,8))
for i, (label,grp) in enumerate(df.groupby('species')):
series = grp['sepal_length']
p = series.hist(ax=ax[i],color=colors[i],label=label)
p.set(xlim=(xmin, xmax))
p.legend()
plt.tight_layout()
plt.show()
Upvotes: 1
Reputation: 3401
I've done it using seaborn
's distplot
, first i've found unique strings in the species
column, for each of them, i draw a distinct histogram in each subplot based on sepal_length
. as you can see i set the color of first histogram to be Blue, and the remaining plots are Red !
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
unique_species = np.unique(df['species'])
for i in range(len(unique_species)):
plt.subplot(1,len(unique_species),i+1)
temp = df.loc[np.where(df['species']==unique_species[i])]
if i == 0 :
sns.distplot(temp['sepal_length'],bins=10,kde=False,rug=False,color='b')
else:
sns.distplot(temp['sepal_length'],bins=10,kde=False,rug=False,color='r')
plt.title(unique_species[i])
plt.show()
the resulting plot would be :
Upvotes: 1