0

I would like to create a mosaic plot with statsmodels.graphics.mosaicplot.mosaic() with data that casts empty cells. They look ugly in the resulting plot, because a cell is created irrespective of its size.

Example:

import matplotlib.pyplot as plt

import pandas as pd
from statsmodels.graphics.mosaicplot import mosaic

df = pd.DataFrame({'size' : ['small', 'large', 'large'],
                   'length' : ['long', 'short', 'long']})

print(df)  # note that the 'short'-'small' combination is missing

fig = plt.figure()
ax = fig.add_subplot(111)
mosaic(df, ax=ax)

creates a plot with an empty cell for value "short small":

enter image description here

Is there a way to either avoid the creation of this cell or to remove it from the plot afterwards?

MERose
  • 4,048
  • 7
  • 53
  • 79
  • What exactly do you want? I don't see any empty cell which is to be expected. So what exactly is wrong here? The image is also super tiny and hard to read given that size. – sascha Nov 11 '16 at 12:24
  • Thanks for the edit. Now i see what you mean. Is Nickil's answer what you wanted? (keep in mind, that the code is python3-tailored in regards to dict-iteration) – sascha Nov 11 '16 at 13:55
  • @sascha: For convenience I enlarged the image (from middle to large). Between the red block for a and the green block for c you'll find the thick white stripe, with c in the center. That's the empty cell. The thick white stripe is due to the margin around cells. – MERose Nov 11 '16 at 13:55
  • @sascha No it doesn't, but that's my fault. I updated my question because I am actually using a DataFrame to create a two-dimensional mosaic plot. – MERose Nov 11 '16 at 14:07

1 Answers1

2

Send an anonymous function to exclude labels whose values are 0:

labels = lambda k: "\n".join(k) if df[k] != 0 else ""
mosaic(df, ax=ax, labelizer=labels)
  • I get a long traceback with `KeyError: ('small', 'long')` at the end. I tried `df.get(k, 0)` instead with an even longer traceback giving a `ValueError: Can only output finite numbers in PDF`. – MERose Feb 19 '17 at 10:23
  • 1
    I just used lambda _: "" – Andrew Cassidy Dec 01 '17 at 02:25