Heatmap - Medical Data Visualizer

Hi everyone,

I’m struggling with, I think the last bit of this exercise.
This is the test failure that I receive:

FAIL: test_heat_map_values (test_module.HeatMapTestCase)
Traceback (most recent call last):
  File "/home/runner/Jims-medical-data-visualizer/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[36 chars]5', '-0.0', '0.1', '0.1', '0.2', '-0.0', '0.0'[571 chars]0.1'] != ['0.0[36 chars]5', '0.0', '0.1', '0.1', '0.3', '0.0', '0.0', [571 chars]0.1']

First differing element 6:

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

Ran 4 tests in 5.404s

FAILED (failures=1)

And this is the code that I wrote so far.

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

# Import data
df = pd.DataFrame(pd.read_csv("/Users/jimsmithuis/Desktop/medical_examination.csv",header=0))

# Add 'overweight' column
df['overweight'] = (df['weight'] / ((df['height'] / 100) ** 2)) > 25  # adds column to df with BMI bool
df['overweight'] = df['overweight'].astype(int)

# 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'] > 1
df['cholesterol'] = df['cholesterol'].astype(int)
df['gluc'] = df['gluc'] > 1
df['gluc'] = df['gluc'].astype(int)

# 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 = pd.DataFrame(df_cat.groupby(["cardio", "variable", "value"], as_index=True)["value"].count())

    df_cat.rename(columns={'value':'total'}, inplace=True)


    first_df = df_cat.iloc[:12, :]
    second_df = df_cat.iloc[12:, :]

    fig, ax = plt.subplots(1, 2, figsize=[12, 6])

    sns.barplot(data=first_df, x='variable', y='total', hue='value', ax=ax[0])
    sns.barplot(data=second_df, x='variable', y='total', hue='value', ax=ax[1])

    # Do not modify the next two lines
    return fig

# Draw Heat Map
def draw_heat_map():
    # Clean the data

    global df
    df = df.loc[(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()

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

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

    # Draw the heatmap with 'sns.heatmap()'
    sns.heatmap(corr, annot=True, cmap="YlGnBu", mask=mask, linewidths=0.5, vmin=-.10, vmax=.28, fmt=".1f", center=0)

    # Do not modify the next two lines
    return fig


The heat map looks exactly the same (number-wise) as the one in the example. So I don’t understand why it is giving an error.

In the previous posts I saw that I should add:

self.maxDiff = None

somewhere in Replit, to clear up what the problem is. Can anyone tell me where exactly I should add this block of code?

Thanks in advance!


1 Like

The error message you are encountering is related to a test case you have written that checks if the values in the heat map generated by your code are as expected. It seems that the actual values generated by your code are different from the expected values, and that’s why the test case is failing.

One way to resolve this issue is to inspect the actual and expected values, and determine why they are different. You can do this by setting the self.maxDiff to None, as mentioned in the error message, so you can see the complete difference. Once you know why the values are different, you can adjust your code to generate the expected values.

Another way to resolve the issue is to revise the expected values, if they were incorrect to begin with. After that, run your tests again to see if they are passing now.

Thanks for your answer Nathan.
The problem is solved.

This should not be done. These tests are written as standards to be met as part of the curriculum and so should not be modified to match the code output. User written code should conform to these tests, especially in this case as this is a common error encountered in this project.

1 Like

My problem was solved, with the following change:
I did not know I had to delete the images before running another test. After I did this, the test was correct.

Of course without changing test_module.py

1 Like

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