要更改颜色,您需要提供与名称匹配的映射。不要以为可以轻易改变标签颜色:
from statsmodels.graphics.mosaicplot import mosaic
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1,figsize=(6,6))
gender = np.repeat(['male','female'],30)
heart_disease = [np.random.choice(['heart disease','no heart disease'],30,p=[0.8,0.2]),
np.random.choice(['heart disease','no heart disease'],30,p=[0.5,0.5])]
data = pd.DataFrame({'gender': gender, 'heart disease': np.array(heart_disease).flatten()})
cols = {('male', 'heart disease'):'#9a1f40',('male', 'no heart disease'):'#d9455f',
('female','heart disease' ):'#74d4c0', ('female', 'no heart disease'):'#def4f0'}
x = mosaic(data,['gender','heart disease'],
properties = lambda key: {'color': cols[key]} ,
ax=ax,gap=0.01)