Data visualisation - correct outputs but failing unit tests

For the medical data visualisation project, my outputs are correct and I have correctly replicated the figures but two unit tests on the seaborn bar chart are failing. I used the catplot() function as instructed.
The first relates to the x label, which is automatically “variable”. The error is
AttributeError: 'numpy.ndarray' object has no attribute 'get_xlabel'.
The second relates to the number of bars in the chart. The error is

AttributeError: 'numpy.ndarray' object has no attribute 'get_children'.

I do not understand why the object required by the unit test seems to be incorrect, when I used the prescribed plotting function, or whether the problem is elsewhere.

Here is the code, in medical_data_visualizer.py:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('medical_examination.csv')

df['overweight'] = (df['weight']/((df['height']/100)**2) > 25).astype(int)

df['cholesterol'] = (df['cholesterol'] > 1).astype(int)
df['gluc'] = (df['gluc'] > 1).astype(int)

def draw_cat_plot():
 
    df_cat = pd.melt(df, id_vars=['cardio'], value_vars=['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke'])
 
    fig = sns.catplot(data=df_cat, x="variable", col="cardio", kind="count", hue = "value", errorbar = None)
    fig.set_ylabels("total")

    fig.savefig('catplot.png')
    return fig

The line in the main file running this is:

medical_data_visualizer.draw_cat_plot()

and the relevant portion of the test module is :

class CatPlotTestCase(unittest.TestCase):
    def setUp(self):
        self.fig = medical_data_visualizer.draw_cat_plot()
        self.ax = self.fig.axes[0]
    
    def test_line_plot_labels(self):
        actual = self.ax.get_xlabel()
        expected = "variable"
        self.assertEqual(actual, expected, "Expected line plot xlabel to be 'variable'")
        actual = self.ax.get_ylabel()
        expected = "total"
        self.assertEqual(actual, expected, "Expected line plot ylabel to be 'total'")
        actual = []
        for label in self.ax.get_xaxis().get_majorticklabels():
            actual.append(label.get_text())
        expected = ['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke']
        self.assertEqual(actual, expected, "Expected bar plot secondary x labels to be 'active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke'")

    def test_bar_plot_number_of_bars(self):
        actual = len([rect for rect in self.ax.get_children() if isinstance(rect, mpl.patches.Rectangle)])
        expected = 13
        self.assertEqual(actual, expected, "Expected a different number of bars chart.")

Hi @beverleyjg

I made a small editing in your request to highlight the errors.

@beverleyjg first of all, sorry for our late response.

Did you manage to solve this issue?

The unit test is not requiring an object - it is indicating that it is receiving an object that doesn’t have those attributes.

The error is not an assertion as defined in the test but an Attribute Error. Somehow it is getting an numpy.ndarray when it was expecting ax.

Here in the test_module.py: actual = self.ax.get_xlabel() is one of the errors. Same here: self.ax.get_children() - in the comprehension living in the test_bar_plot_number.... method.

Can you check why ax is incorrectly defined? Is the fig that you defined in your function really a fig?