Medical Data Visualizer Project Image Is Good but Errors Encountered

Hello, I finished the task on my replit that basically tells me to write python code that generates ‘bar’ graph and correlation matrix images using pandas and seaborn. While running the test_module.py, 2 errors were raised based on the former image result. Though the resulting ‘catplot.png’ and ‘Figure_1.png’ are very similar, if not exactly alike, I expect the errors are negligible in this case. My interpretation of the cause of the error is that the way my program is written doesn’t match the expected program.
The console response was this:

> python main.py
Matplotlib created a temporary config/cache directory at /tmp/matplotlib-gzcfs1m1 because the default path (/config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.
EE.[‘0.0’, ‘0.0’, ‘-0.0’, ‘0.0’, ‘-0.1’, ‘0.5’, ‘0.0’, ‘0.1’, ‘0.1’, ‘0.3’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.2’, ‘0.1’, ‘0.0’, ‘0.2’, ‘0.1’, ‘0.0’, ‘0.1’, ‘-0.0’, ‘-0.1’, ‘0.1’, ‘0.0’, ‘0.2’, ‘0.0’, ‘0.1’, ‘-0.0’, ‘-0.0’, ‘0.1’, ‘0.0’, ‘0.1’, ‘0.4’, ‘-0.0’, ‘-0.0’, ‘0.3’, ‘0.2’, ‘0.1’, ‘-0.0’, ‘0.0’, ‘0.0’, ‘-0.0’, ‘-0.0’, ‘-0.0’, ‘0.2’, ‘0.1’, ‘0.1’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.3’, ‘0.0’, ‘-0.0’, ‘0.0’, ‘-0.0’, ‘-0.0’, ‘-0.0’, ‘0.0’, ‘0.0’, ‘-0.0’, ‘0.0’, ‘0.0’, ‘0.0’, ‘0.2’, ‘0.0’, ‘-0.0’, ‘0.2’, ‘0.1’, ‘0.3’, ‘0.2’, ‘0.1’, ‘-0.0’, ‘-0.0’, ‘-0.0’, ‘-0.0’, ‘0.1’, ‘-0.1’, ‘-0.1’, ‘0.7’, ‘0.0’, ‘0.2’, ‘0.1’, ‘0.1’, ‘-0.0’, ‘0.0’, ‘-0.0’, ‘0.1’]
.
======================================================================
ERROR: test_bar_plot_number_of_bars (test_module.CatPlotTestCase)

Traceback (most recent call last):
File “/home/runner/boilerplate-medical-data-visualizer/test_module.py”, line 26, in test_bar_plot_number_of_bars
actual = len([rect for rect in self.ax.get_children() if isinstance(rect, mpl.patches.Rectangle)])
AttributeError: ‘numpy.ndarray’ object has no attribute ‘get_children’

======================================================================
ERROR: test_line_plot_labels (test_module.CatPlotTestCase)

Traceback (most recent call last):
File “/home/runner/boilerplate-medical-data-visualizer/test_module.py”, line 13, in test_line_plot_labels
actual = self.ax.get_xlabel()
AttributeError: ‘numpy.ndarray’ object has no attribute ‘get_xlabel’


Ran 4 tests in 6.373s

FAILED (errors=2)

This is the catplot.png:

I managed to generate the image as expected, yet I encountered 2 errors.

Generated ‘catplot.png’ (top ) vs Expected ‘Figure_1.png’ (bottom)

TERMINAL :

Matplotlib created a temporary config/cache directory at /tmp/matplotlib-eiikxiyh because the default path (/config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.
EE.['0.0', '0.0', '-0.0', '0.0', '-0.1', '0.5', '0.0', '0.1', '0.1', '0.3', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.2', '0.1', '0.0', '0.2', '0.1', '0.0', '0.1', '-0.0', '-0.1', '0.1', '0.0', '0.2', '0.0', '0.1', '-0.0', '-0.0', '0.1', '0.0', '0.1', '0.4', '-0.0', '-0.0', '0.3', '0.2', '0.1', '-0.0', '0.0', '0.0', '-0.0', '-0.0', '-0.0', '0.2', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.3', '0.0', '-0.0', '0.0', '-0.0', '-0.0', '-0.0', '0.0', '0.0', '-0.0', '0.0', '0.0', '0.0', '0.2', '0.0', '-0.0', '0.2', '0.1', '0.3', '0.2', '0.1', '-0.0', '-0.0', '-0.0', '-0.0', '0.1', '-0.1', '-0.1', '0.7', '0.0', '0.2', '0.1', '0.1', '-0.0', '0.0', '-0.0', '0.1']
.
======================================================================
ERROR: test_bar_plot_number_of_bars (test_module.CatPlotTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-medical-data-visualizer-forked/test_module.py", line 26, in test_bar_plot_number_of_bars
    actual = len([rect for rect in self.ax.get_children() if isinstance(rect, mpl.patches.Rectangle)])
AttributeError: 'numpy.ndarray' object has no attribute 'get_children'

======================================================================
ERROR: test_line_plot_labels (test_module.CatPlotTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-medical-data-visualizer-forked/test_module.py", line 13, in test_line_plot_labels
    actual = self.ax.get_xlabel()
AttributeError: 'numpy.ndarray' object has no attribute 'get_xlabel'

----------------------------------------------------------------------
Ran 4 tests in 6.308s

FAILED (errors=2)

CODE (link to repl) :

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

# Import data
df = pd.read_csv('medical_examination.csv', header=0)

# Add 'overweight' column
df['overweight'] = (df['weight']/((df['height']/100)**2)).where((df['weight']/((df['height']/100)**2))>25, 0).mask((df['weight']/((df['height']/100)**2))>25, 1).astype(np.int8())

# Normalize data by making 0 always good and 1 always bad. If the value of 'cholesterol' or 'gluc' is 1, make the value 0. If the value is more than 1, make the value 1.
df['cholesterol'] = df['cholesterol'].where(df['cholesterol'] > 1, 0).mask(df['cholesterol'] > 1, 1)
df['gluc'] = df['gluc'].where(df['gluc'] > 1, 0).mask(df['gluc'] > 1, 1)

# Draw Categorical Plot
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat = pd.melt(df, ['cardio'], value_vars=['cholesterol', 'gluc', 'smoke', 'alco', 'active', 'overweight'])

    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the columns for the catplot to work correctly.
    df_cat = pd.DataFrame(data=df_cat.value_counts(), columns=['total']).sort_index().reset_index()

    # Draw the catplot with 'sns.catplot()'
    fig = sns.catplot(x='variable', y='total', hue='value', col='cardio', data=df_cat, kind='bar')

    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig


# Draw Heat Map
def draw_heat_map():
    # Clean the data
    df_heat = df.drop(index=df.loc[df['ap_lo'] > df['ap_hi']].index.append(df.loc[df['height'] < df['height'].quantile(0.025)].index).append(df.loc[df['height'] > df['height'].quantile(0.975)].index).append(df.loc[df['weight'] < df['weight'].quantile(0.025)].index).append(df.loc[df['weight'] > df['weight'].quantile(0.975)].index))
    
    # Calculate the correlation matrix
    corr = df_heat.corr()

    # Generate a mask for the upper triangle
    mask = np.triu(np.ones_like(corr, dtype=bool))

    # Set up the matplotlib figure
    fig, ax = plt.subplots(figsize=(11, 9))

    # Draw the heatmap with 'sns.heatmap()'
    ax = sns.heatmap(corr, mask=mask, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=True, fmt='.1f')


    # Do not modify the next two lines
    fig.savefig('heatmap.png')
    return fig

I found out from this recent topic that some developers also had this problem and they had to dive deeper into documentations of seaborn.

It’s a common error. The short answer is: seaborn returns a facetgrid-object and the actual chart you are supposed to return is under the .figure attribute :wink:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.