pythonpandasmatplotlibmosaic-plot

Change the default colors of a mosaic plot


I want to change the color of this mosaic plot to make it printable in black in white but can't find a way to change this parameter

the mosaic plot

from statsmodels.graphics.mosaicplot import mosaic
import matplotlib.pyplot as plt
import pandas

x = ['yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes']
y = ['yes', 'yes', 'yes', 'yes', 'no', 'no', 'no']
data = pandas.DataFrame({'x': x, 'y': y})
mosaic(data, ['x', 'y'])

plt.savefig("mosaicplot.pdf", figsize=[10,5])
plt.show()

Here is what I actually have : I saw I could change the color with mosaic(properties) on this link : http://www.statsmodels.org/stable/generated/statsmodels.graphics.mosaicplot.mosaic.html but I can only give 2 different colors and I need a different color for each plot, like this: enter image description here


Solution

  • The documentation mentions a properties= argument:

    properties function (key) -> dict, optional

    A function that for each tile in the mosaic take the key of the tile and returns the dictionary of properties of the generated Rectangle, like color, hatch or similar. A default properties set will be provided fot the keys whose color has not been defined, and will use color variation to help visually separates the various categories. It should return None to indicate that it should use the default property for the tile. A dictionary of the properties for each key can be passed, and it will be internally converted to the correct function

    Therefore, you can pass either a function (see the example in the link above), or more simply a dictionary, to properties= to change the appearance of the rectangles:

    x = ['yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes']
    y = ['yes', 'yes', 'yes', 'yes', 'no', 'no', 'no']
    data = pandas.DataFrame({'x': x, 'y': y})
    
    props = {}
    props[('yes', 'yes')] = {'color': 'xkcd:orange'}
    props[('yes','no')] = {'facecolor': 'xkcd:pale blue',
                           'edgecolor':'xkcd:light grey',
                           'hatch':'o'}
    data = pandas.DataFrame({'x': x, 'y': y})
    mosaic(data, ['x', 'y'], properties=props)
    

    enter image description here

    As far as I can tell, any argument accepted by Rectangle can be passed along in this dictionary.