Error in Bar plot (Categorical Plot)

I got the following error message .

python main.py
Matplotlib created a temporary config/cache directory at /tmp/matplotlib-ufjcc47x 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.0', '0.3', '0.2', '0.1', '-0.0', '0.0', '-0.0', '-0.0', '0.2', '0.1', '0.1', '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.2', '0.0', '-0.0', '0.2', '0.1', '0.3', '-0.0', '-0.0', '-0.0', '-0.0', '0.1', '-0.1', '-0.1', '0.7', '0.0', '0.2', '-0.0', '0.0', '-0.0', '0.1']
F
======================================================================
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'

======================================================================
FAIL: test_heat_map_values (test_module.HeatMapTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-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[141 chars]1', '-0.0', '-0.0', '0.3', '0.2', '0.1', '-0.0[285 chars]0.1'] != ['0.0[141 chars]1', '0.0', '0.1', '-0.0', '-0.1', '0.1', '0.0'[466 chars]0.1']

First differing element 21:
'-0.0'
'0.0'

Second list contains 25 additional elements.
First extra element 66:
'0.0'

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

----------------------------------------------------------------------
Ran 4 tests in 12.378s

FAILED (failures=1, errors=2)


And my code is as follows:

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['weight']/((df['height']*0.01)**2)>25
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.

    # fig = sns.catplot(x=“variable”, y=“total”, hue=“value”, col=“cardio”, data=df_cat, kind=“bar”)

    fig = sns.catplot(data=df_cat, kind="count",  x="variable", hue="value", col="cardio")

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



    # 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_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_heat.corr()

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



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

   # Draw the heatmap with 'sns.heatmap()'
  ax = sns.heatmap(
     corr,
     linewidths=.5,
     annot=True,
     fmt='.1f',
     mask=mask,
     square=True,
     center=0,
     vmin=-0.1,
     vmax=0.25,
     cbar_kws={'shrink':.45, 'format':'%.2f'}
     )

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



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

Please help me to resolve this error. It would be very much helpful for me.

Your browser information:

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

Challenge: Medical Data Visualizer

Link to the challenge:

I vaguely remember encountering this, but don’t remember where I found the solution. However, change this line:

fig = sns.catplot(data=df_cat, kind="count",  x="variable", hue="value", col="cardio")

to this:

graph = sns.catplot(data=df_cat, kind="count",  x="variable", hue="value", col="cardio")
fig = graph.fig
1 Like

Thank You so much for your help @fuzzyray . It worked well for me.

your sns.catplot must call its .fig value, which is the plot represented as a matplotlib objects, which on its side has methods like .savefig("file_name"), which is used in the code to save the chart, or things like get_xlabel, which is used by the project tests to verify you used correct data to plot the figure. In its initial state, the sns.catplot returns a numpy.ndarray object, which does not posses those methods.