Data Analysis with Python Projects - Medical Data Visualizer - Figure Settings

Tell us what’s happening:
Describe your issue in detail here.

I believe my problem is that figure settings are matching with the correct answer.
But I can’t see it.
Oh, and use the command in shell
pip install seaborn
But, in my code sns.catplot is in red, saying that :“catplot” is not a known member of module “seaborn” (function) catplot: Unknown

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_over = df['weight']/((df['height']/100)**2)
bynario = df_over > 25
df['overweight'] = bynario.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.loc[df['cholesterol'] == 1 , 'cholesterol'] = 0 ## troca 1 ------> 0
df.loc[df['cholesterol'] >= 2 , 'cholesterol'] = 1 ## troca 1 ------> 0
df.loc[df['gluc'] == 1 , 'gluc'] = 0 ## troca 1 ------> 0
df.loc[df['gluc'] >= 2 , 'gluc'] = 1 ## troca 1 ------> 0


# 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'.
  teste_sea = df[['cardio','cholesterol','gluc','smoke','alco','active','overweight']]
  df_cat = pd.melt(teste_sea,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.
  count = df_cat.groupby(['cardio', 'variable', 'value']).size().reset_index()
  df_cat = count.rename(columns={0 : 'total'}) 
    

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



    # Get the figure for the output
  fig = graph.fig


    # 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[(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(np.ones_like(corr)) 



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

    # Draw the heatmap with 'sns.heatmap()'
  sns.heatmap(corr, center = 0.0 ,vmax = 0.319, vmin = -0.159 ,annot=True, mask = mask, fmt='.1f')



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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36

Challenge: Data Analysis with Python Projects - Medical Data Visualizer

Link to the challenge:

For future reference, if you’re looking for help dealing with an error, it can be helpful to include the entire stack trace in your post.
Based on your statement
“But, in my code sns.catplot is in red, saying that :“catplot” is not a known member of module “seaborn” (function) catplot: Unknown”
Here are some first steps:

  1. catplot was introduced in version 0.9.0. If you have an older version of Seaborn installed, you won’t have access to it. You can either run 'pip install seaborn --upgrade
    ’ in your command line, or if you’re trying to run this code in an IDE, your IDE might require you to use their built-in package management system to install and upgrade packages.
  2. Some IDEs or editors cache libraries and sometimes this cache might be outdated or corrupted. Restarting your editor or clearing its cache (depending on the editor) might resolve the problem.
  3. Worst case scenario, if you need to just get this running fast and can’t track down the issue, , you can always use the older functions that catplot is built upon, like sns.factorplot.
2 Likes

But I can’t see it.

What do you mean here, you can’t see the chart or figures? It’s not generating an image? There’s an image but it’s blank?

Do you get any errors when you run the pytest?

Can you link to your replit?

Hi! Thank you very much for the answer.

I tried [3]…but I got this: AttributeError: module ‘seaborn’ has no attribute ‘factorplot’

I tried [1] , but I still got the erro message (below)

python3 test_module.py
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
E/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/_oldcore.py:1498: FutureWarning: is_categorical_dtype is deprecated and will be removed in a future version. Use isinstance(dtype, CategoricalDtype) instead
if pd.api.types.is_categorical_dtype(vector):
E/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/matrix.py:260: FutureWarning: Format strings passed to MaskedConstant are ignored, but in future may error or produce different behavior
annotation = (“{:” + self.fmt + “}”).format(val)
./home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/matrix.py:260: FutureWarning: Format strings passed to MaskedConstant are ignored, but in future may error or produce different behavior
annotation = (“{:” + self.fmt + “}”).format(val)
[‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’]
F

ERROR: test_bar_plot_number_of_bars (main.CatPlotTestCase)

Traceback (most recent call last):
File “/home/runner/boilerplate-medical-data-visualizer/test_module.py”, line 9, in setUp
self.fig = medical_data_visualizer.draw_cat_plot()
File “/home/runner/boilerplate-medical-data-visualizer/medical_data_visualizer.py”, line 35, in draw_cat_plot
graph = sns.catplot(data=df_cat, kind=“bar”, x=“variable”, y=“total”, hue=“value”, col=“cardio”)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 3244, in catplot
g.map_dataframe(plot_func, x=x, y=y, hue=hue, **plot_kws)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py”, line 819, in map_dataframe
self._facet_plot(func, ax, args, kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py”, line 848, in _facet_plot
func(*plot_args, **plot_kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 2763, in barplot
plotter.plot(ax, kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 1587, in plot
self.annotate_axes(ax)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 767, in annotate_axes
ax.legend(loc=“best”, title=self.hue_title)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/matplotlib/axes/_axes.py”, line 322, in legend
handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/matplotlib/legend.py”, line 1361, in _parse_legend_args
handles, labels = _get_legend_handles_labels(axs, handlers)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/matplotlib/legend.py”, line 1291, in get_legend_handles_labels
if label and not label.startswith('
'):
AttributeError: ‘numpy.int64’ object has no attribute ‘startswith’

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

Traceback (most recent call last):
File “/home/runner/boilerplate-medical-data-visualizer/test_module.py”, line 9, in setUp
self.fig = medical_data_visualizer.draw_cat_plot()
File “/home/runner/boilerplate-medical-data-visualizer/medical_data_visualizer.py”, line 35, in draw_cat_plot
graph = sns.catplot(data=df_cat, kind=“bar”, x=“variable”, y=“total”, hue=“value”, col=“cardio”)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 3244, in catplot
g.map_dataframe(plot_func, x=x, y=y, hue=hue, **plot_kws)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py”, line 819, in map_dataframe
self._facet_plot(func, ax, args, kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/axisgrid.py”, line 848, in _facet_plot
func(*plot_args, **plot_kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 2763, in barplot
plotter.plot(ax, kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 1587, in plot
self.annotate_axes(ax)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/seaborn/categorical.py”, line 767, in annotate_axes
ax.legend(loc=“best”, title=self.hue_title)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/matplotlib/axes/_axes.py”, line 322, in legend
handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/matplotlib/legend.py”, line 1361, in _parse_legend_args
handles, labels = _get_legend_handles_labels(axs, handlers)
File “/home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages/matplotlib/legend.py”, line 1291, in get_legend_handles_labels
if label and not label.startswith('
'):
AttributeError: ‘numpy.int64’ object has no attribute ‘startswith’

======================================================================
FAIL: test_heat_map_values (main.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: [‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, ‘–’, [36 chars]‘–’] != [‘0.0’, ‘0.0’, ‘-0.0’, ‘0.0’, ‘-0.1’, ‘0.5’[615 chars]0.1’]

First differing element 0:
‘–’
‘0.0’

Second list contains 77 additional elements.
First extra element 14:
‘0.0’

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


Ran 4 tests in 7.743s

FAILED (failures=1, errors=2)

Oh…I’m really sorry… I meant that I couldn’t see my mistake.

The link:

Could you respond with your seaborn version so we can rule that out?

1 Like

pip show seaborn
Name: seaborn
Version: 0.12.2
Summary: Statistical data visualization
Home-page: None
Author: None
Author-email: Michael Waskom mwaskom@gmail.com
License: None
Location: /home/runner/boilerplate-medical-data-visualizer/.pythonlibs/lib/python3.10/site-packages
Requires: pandas, numpy, matplotlib
Required-by:

Have you run ‘pip install seaborn’ in your command line? Does your IDE have its own package manager? If so does it say that it is installed when you check there?

1 Like

Same error many people have had lately: https://forum.freecodecamp.org/t/data-analysis-with-python-projects-medical-data-visualizer-heatmap-values/639407/1

Fork this new boilerplate template, and copy your code back in: https://replit.com/@pkdvalis/fcc-2023-Boilerplate-medical-data-visualizer

I haven’t found a root cause but this seems to get around the problem.

1 Like

Thank you, @j.tranquilli and @pkdvalis .

I followed the instructions … now ‘test_module.py’ and ‘main.py’ worked perfectly!

1 Like

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