Change the colors of the result of group by

Question:

Data (train) is taken from Kaggle Titanic.

I have a following plot:

train.groupby(["Survived", "Sex"])['Age'].plot(kind='hist', legend = True, histtype='step', bins =15)

I want to change the colors of the lines. The problem is that I cannot simply use the color argument here. So how do I address them?
plot

Asked By: Alina

||

Answers:

You cannot directly use the color argument because the histograms are divided over several axes.

A workaround may be to set the color cycler for the script, i.e. specify which colors should subsequently be used one by one by any function that plots anything. This would be done using the rcParams of pyplot.

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b','c'])))

Full working example:

import seaborn.apionly as sns
import pandas as pd
import matplotlib.pyplot as plt
from cycler import cycler

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b','c'])))

titanic = sns.load_dataset("titanic")

gdf = titanic.groupby(["survived", "sex"])['age']
ax = gdf.plot(kind='hist', legend = True, histtype='step', bins =15)

plt.show()

enter image description here

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.