Data Analysis with Python Projects - Medical Data Visualizer

Tell us what’s happening:

Describe your issue in detail here.
I don’t know what is wrong with my code, It says my heatmap doesn’t match with the expected output. Also, I noticed that there is a gender column in the expected heatmap but in my case, the column name is sex instead of gender, and also I have done everything as per the instruction, but somehow my heatmap values are different than the ones in the expected version.
This is the error I got:

/home/runner/boilerplate-medical-data-visualizer-2/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py:123: UserWarning: The figure layout has changed to tight
  self._figure.tight_layout(*args, **kwargs)
/home/runner/boilerplate-medical-data-visualizer-2/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py:123: UserWarning: The figure layout has changed to tight
  self._figure.tight_layout(*args, **kwargs)
E/home/runner/boilerplate-medical-data-visualizer-2/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py:123: UserWarning: The figure layout has changed to tight
  self._figure.tight_layout(*args, **kwargs)
E.['0.0', '0.0', '-0.0', '-0.0', '-0.1', '0.5', '-0.0', '0.1', '0.2', '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.1', '-0.0', '-0.0', '0.1', '0.0', '0.0', '0.0', '0.1', '-0.0', '-0.0', '0.1', '0.0', '0.0', '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.1', '0.2', '0.1', '-0.0', '-0.0', '-0.0', '-0.0', '0.1', '-0.0', '-0.1', '0.6', '0.0', '0.0', '0.1', '0.1', '-0.0', '0.0', '-0.0', '0.2']
F
======================================================================
ERROR: test_bar_plot_number_of_bars (test_module.CatPlotTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-medical-data-visualizer-2/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-2/test_module.py", line 13, in test_line_plot_labels
    actual = self.ax.get_xlabel()
AttributeError: 'numpy.ndarray' object has no attribute 'get_xlabel'

======================================================================
FAIL: test_heat_map_values (test_module.HeatMapTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-medical-data-visualizer-2/test_module.py", line 47, in test_heat_map_values
    self.assertEqual(actual, expected, "Expected different values in heat map.")
AssertionError: Lists differ: ['0.0[14 chars]0', '-0.0', '-0.1', '0.5', '-0.0', '0.1', '0.2[594 chars]0.2'] != ['0.0[14 chars]0', '0.0', '-0.1', '0.5', '0.0', '0.1', '0.1',[593 chars]0.1']

First differing element 3:
'-0.0'
'0.0'

Diff is 1287 characters long. Set self.maxDiff to None to see it. : Expected different values in heat map.

----------------------------------------------------------------------
Ran 4 tests in 10.968s

FAILED (failures=1, errors=2)
### Your code so far
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')

# Add 'overweight' column
df['overweight'] = df.apply(lambda x: 1 if (x.weight/np.square(x.height/100))> 25  else 0,axis=1)

# 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.apply(lambda x: 0 if x==1 else 1)
df['gluc']=df.gluc.apply(lambda x: 0 if x==1 else 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,id_vars=['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['total']=1
    df_cat = df_cat.groupby(['cardio','variable','value'],as_index=False).count()


    # Draw the catplot with 'sns.catplot()'

    # Get the figure for the output
    fig = sns.catplot(x='variable',y='total',col='cardio',hue='value',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.rename(columns={'sex':'gender'})
    df_heat=df[(df['ap_lo'] <= df['ap_hi']) &(df['height']>=df['height'].quantile(0.025)) &(df['height']<=df['height'].quantile(0.975))
                                                                                          &(df['weight']>=df['weight'].quantile(0.025))
                                                                                          &(df['weight']<=df['weight'].quantile(0.975))]

    # Calculate the correlation matrix
    corr = df.corr(method='pearson')


    # Generate a mask for the upper triangle
    mask = np.triu(corr)



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


    # Draw the heatmap with 'sns.heatmap()'
    sns.heatmap(corr,mask=mask,annot=True,fmt='.1f',linewidths=0.5,square=True,center=0.08,cbar_kws={'shrink':0.5})


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

Data Analysis with Python Projects - Medical Data Visualizer

There are 3 errors here, but regarding the first two:

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

You can find a bit more info here:
https://forum.freecodecamp.org/t/draw-bar-plot-test-failure/424240/2?u=pkdvalis

https://forum.freecodecamp.org/t/medical-data-visualizer-attributeerror-numpy-ndarray-object-has-no-attribute/609590

I find this problem poorly documented and not clear at all tbh. I’ve solved it by putting fig = fig.figure before the save, like this:

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

This converts the seaborn facet grid into a figure that the tests can read. This will clear the first two errors. I’m providing the solution here because I can’t find good documentation that actually explains this, and it seems to only be needed for this test. The image is still generated. All I can find is this:

http://seaborn.pydata.org/generated/seaborn.FacetGrid.html

figure
	Access the matplotlib.figure.Figure object underlying the grid.

The heatmap error is generated by the line where you calculate the correlation matrix

Thanks! That worked :slight_smile:

1 Like