Heart disease is one of the leading causes of death worldwide. Uncovering risk patterns from patient records with heart disease can help clinicians make better-informed decisions. Going through hundreds of patient records by hand to spot which combinations of age, cholesterol levels, and chest pain types tend to appear together is slow and error prone. Pairing a high-performance database like GridDB with an AI model lets you store medical records once and then query them in natural language to identify meaningful patterns.
In this article, you will see how to build an AI-powered heart disease analysis chatbot using the Anthropic Claude API and GridDB Cloud. The chatbot reads patient medical records that include age, sex, chest pain type, resting blood pressure, cholesterol, fasting blood sugar, maximum heart rate achieved, and other clinical attributes. It identifies which risk factors appear most often among heart disease patients, compares risk profiles across age groups, and produces AI-generated insights and recommendations. You will also use Claude to create matplotlib visualizations so you can explore the data visually.
Prerequisites:
You will need the following to run scripts in this article:
- A GridDB cloud account. Refer to this quick start guide to set up a GridDB cloud account.
- Anthropic API Key. You can obtain one from the Anthropic console.
Note: You can find the complete code for this tutorial in my GridDB Blogs GitHub repository.
Installing and Importing Required Libraries
The following installs the libraries you will need to run the scripts in this article.
!pip install python-dotenv
!pip install anthropic
The script below imports the required libraries.
import pandas as pd
import matplotlib.pyplot as plt
import base64
import os
import requests
import json
import re
import anthropic
from dotenv import load_dotenv
load_dotenv()
Importing the Dataset
The dataset used in this article is the UCI Heart Disease dataset containing patient medical records. Each row represents a single patient and includes clinical measurements such as age, sex, chest pain type, resting blood pressure, serum cholesterol, fasting blood sugar, resting electrocardiographic results, maximum heart rate achieved during exercise, exercise-induced angina, and a target column called num. The num column ranges from 0 to 4, where 0 means no heart disease and 1, 2, 3, and 4 represent progressive stages of heart disease. You can download the dataset from Kaggle.
The following script loads the dataset, keeps the columns we will work with, and removes rows with missing values in those columns so the chatbot has clean numbers to reason over. We also convert the num target into a binary heart_disease flag that is 1 whenever any stage of heart disease is present.
dataset = pd.read_csv("heart_disease_uci.csv", encoding='utf-8')
keep_cols = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs',
'restecg', 'thalch', 'exang', 'oldpeak', 'num']
dataset = dataset[keep_cols].dropna().reset_index(drop=True)
# Convert the multi-class target to a binary heart disease flag
dataset['heart_disease'] = (dataset['num'] > 0).astype(int)
print(dataset.shape)
dataset.head()
Output:
The dataset has roughly 740 patients after cleaning, which is well within what we can store and query through GridDB Cloud.
Inserting Data in GridDB
We will insert the patient records into GridDB Cloud.
Creating a GridDB Connection
Run the following script to test your connection with the GridDB cloud. You can retrieve the connection credentials from your GridDB cloud account.
username = os.environ.get("username")
password = os.environ.get("password")
base_url = os.environ.get("base_url")
url = f"{base_url}/checkConnection"
credentials = f"{username}:{password}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
headers = {
'Content-Type': 'application/json',
'Authorization': f'Basic {encoded_credentials}',
'User-Agent': 'PostmanRuntime/7.29.0'
}
response = requests.get(url, headers=headers)
print(response.status_code)
Output:
200
If you do not see the above response, check this quick start guide for troubleshooting.
Creating a GridDB Container for Patient Records
Before inserting data, we need to create a container in GridDB with the correct schema. The following script maps pandas data types to GridDB types.
dataset.insert(0, "SerialNo", dataset.index + 1)
dataset.columns.name = None
# Mapping pandas dtypes to GridDB types
type_mapping = {
"int64": "LONG",
"float64": "DOUBLE",
"bool": "BOOL",
"datetime64": "TIMESTAMP",
"object": "STRING",
"category": "STRING",
}
# Generate the columns part of the payload dynamically
columns = []
for col, dtype in dataset.dtypes.items():
griddb_type = type_mapping.get(str(dtype), "STRING")
columns.append({
"name": col,
"type": griddb_type
})
print(columns)
Output:
Output:
[{'name': 'SerialNo', 'type': 'LONG'}, {'name': 'age', 'type': 'LONG'}, {'name': 'sex', 'type': 'STRING'}, {'name': 'cp', 'type': 'STRING'}, {'name': 'trestbps', 'type': 'DOUBLE'}, {'name': 'chol', 'type': 'DOUBLE'}, {'name': 'fbs', 'type': 'STRING'}, {'name': 'restecg', 'type': 'STRING'}, {'name': 'thalch', 'type': 'DOUBLE'}, {'name': 'exang', 'type': 'STRING'}, {'name': 'oldpeak', 'type': 'DOUBLE'}, {'name': 'num', 'type': 'LONG'}, {'name': 'heart_disease', 'type': 'LONG'}]
Next, we create the container using the GridDB REST API.
container_name = "heart_disease_db"
url = f"{base_url}/containers"
payload = json.dumps({
"container_name": container_name,
"container_type": "COLLECTION",
"rowkey": True,
"columns": columns
})
response = requests.post(url, headers=headers, data=payload)
print(f"Status Code: {response.status_code}")
Output:
Status Code: 201
The 201 status code confirms the container has been created successfully.
Inserting Patient Records into the GridDB Container
With the container ready, we can now push the patient records into it. The format_row function takes care of type conversions, including turning any remaining NaN values into None so GridDB accepts them.
url = f"{base_url}/containers/{container_name}/rows"
def format_row(row):
formatted = []
for item in row:
if pd.isna(item):
formatted.append(None)
elif isinstance(item, bool):
formatted.append(str(item).lower())
elif isinstance(item, (int, float)):
formatted.append(item)
else:
formatted.append(str(item))
return formatted
rows = [format_row(row) for row in dataset.values.tolist()]
payload = json.dumps(rows)
response = requests.put(url, headers=headers, data=payload)
print(f"Status Code: {response.status_code}")
print(f"Response Text: {response.text}")
Output:
Status Code: 200
Response Text: {"count":740}
All patient records are now sitting inside the GridDB container.
Using AI to Analyze Patient Records and Get Insights
With the data stored in GridDB, we can pull it back out and feed a pre-computed summary to Claude. The flow has three stages: fetch records from GridDB, build a structured summary of the dataset, and pass that summary as context so Claude can answer questions about risk factors and patient groups.
Retrieve Data from GridDB
The script below fetches every patient row from the GridDB container and loads them into a pandas DataFrame.
url = f"{base_url}/containers/{container_name}/rows"
payload = json.dumps({
"offset": 0,
"limit": 10000,
"condition": "",
"sort": ""
})
response = requests.post(url, headers=headers, data=payload)
print(f"Status Code: {response.status_code}")
if response.status_code == 200:
try:
data = response.json()
print("Data retrieved successfully!")
rows = data.get("rows", [])
heart_disease_db = pd.DataFrame(rows, columns=[col for col in dataset.columns])
except json.JSONDecodeError:
print("Error: Failed to decode JSON response.")
else:
print(f"Error: Failed to query data from the container. Response: {response.text}")
print(heart_disease_db.shape)
heart_disease_db.head()
Output:
The patient records have been pulled back from GridDB and are ready for analysis.
Build Dataset Summary
Sending hundreds of raw rows to Claude in a single prompt is wasteful and can hurt response quality. Instead, we compute a structured summary of the dataset and hand that to the model. This way Claude reasons over real statistics derived from every patient in the database, not just a sampled handful.
NUMERIC_COLS = ['age', 'trestbps', 'chol', 'thalch', 'oldpeak']
STAGE_LABELS = {
0: 'stage 0 (no disease)',
1: 'stage 1',
2: 'stage 2',
3: 'stage 3',
4: 'stage 4'
}
def build_summary(df):
parts = []
# Overview
total = len(df)
diseased = int(df['heart_disease'].sum())
healthy = total - diseased
parts.append(f"Records: {total} patients")
parts.append(f"Heart disease present (num > 0): {diseased} ({diseased/total*100:.1f}%)")
parts.append(f"No heart disease (num = 0): {healthy} ({healthy/total*100:.1f}%)")
# Stage breakdown using the original num column (0 to 4)
stage_counts = df['num'].value_counts().sort_index()
stage_table = pd.DataFrame({
'patients': stage_counts,
'pct': (stage_counts / total * 100).round(1)
})
stage_table.index = [STAGE_LABELS.get(int(i), str(i)) for i in stage_table.index]
parts.append(f"\n--- Heart Disease Stage Distribution (num column) ---\n{stage_table.to_string()}")
# Sex distribution
sex_counts = df['sex'].value_counts()
parts.append(f"\n--- Sex Distribution ---\n{sex_counts.to_string()}")
# Numeric stats overall
parts.append(f"\n--- Numeric Stats (overall) ---\n{df[NUMERIC_COLS].describe().round(2).to_string()}")
# Numeric stats split by heart disease status
grouped = df.groupby('heart_disease')[NUMERIC_COLS].mean().round(2)
grouped.index = ['no disease', 'disease']
parts.append(f"\n--- Avg by Heart Disease Status ---\n{grouped.to_string()}")
# Numeric stats split by stage (0 to 4)
stage_grouped = df.groupby('num')[NUMERIC_COLS].mean().round(2)
stage_grouped.index = [STAGE_LABELS.get(int(i), str(i)) for i in stage_grouped.index]
parts.append(f"\n--- Avg by Stage ---\n{stage_grouped.to_string()}")
# Chest pain type vs disease (cp is already a string in the Kaggle file:
# typical angina, atypical angina, non-anginal, asymptomatic)
cp_counts = df.groupby('cp')['heart_disease'].agg(['count', 'sum'])
cp_counts['rate_pct'] = (cp_counts['sum'] / cp_counts['count'] * 100).round(1)
parts.append(f"\n--- Chest Pain Type vs Disease ---\n{cp_counts.to_string()}")
# Chest pain type vs stage (cross tab)
stage_named = df['num'].map(STAGE_LABELS)
cp_stage = pd.crosstab(df['cp'], stage_named)
parts.append(f"\n--- Chest Pain Type vs Stage (counts) ---\n{cp_stage.to_string()}")
# Age groups
bins = [0, 40, 50, 60, 70, 100]
labels = ['<40', '40-49', '50-59', '60-69', '70+']
df_local = df.copy()
df_local['age_group'] = pd.cut(df_local['age'], bins=bins, labels=labels, right=False)
age_stats = df_local.groupby('age_group').agg(
patients=('age', 'count'),
disease_count=('heart_disease', 'sum'),
avg_stage=('num', 'mean'),
avg_chol=('chol', 'mean'),
avg_bp=('trestbps', 'mean'),
avg_max_hr=('thalch', 'mean')
).round(2)
age_stats['disease_rate_pct'] = (age_stats['disease_count'] / age_stats['patients'] * 100).round(1)
parts.append(f"\n--- Age Group Breakdown ---\n{age_stats.to_string()}")
# Sex vs disease
sex_stats = df.groupby('sex')['heart_disease'].agg(['count', 'sum'])
sex_stats['rate_pct'] = (sex_stats['sum'] / sex_stats['count'] * 100).round(1)
parts.append(f"\n--- Sex vs Disease ---\n{sex_stats.to_string()}")
# High cholesterol flag
df_local['high_chol'] = df_local['chol'] >= 240
chol_stats = df_local.groupby('high_chol')['heart_disease'].agg(['count', 'sum'])
chol_stats['rate_pct'] = (chol_stats['sum'] / chol_stats['count'] * 100).round(1)
chol_stats.index = ['chol < 240', 'chol >= 240']
parts.append(f"\n--- High Cholesterol vs Disease ---\n{chol_stats.to_string()}")
# Exercise-induced angina
exang_stats = df.groupby('exang')['heart_disease'].agg(['count', 'sum'])
exang_stats['rate_pct'] = (exang_stats['sum'] / exang_stats['count'] * 100).round(1)
parts.append(f"\n--- Exercise-Induced Angina vs Disease ---\n{exang_stats.to_string()}")
return "\n".join(parts)
data_summary = build_summary(heart_disease_db)
print(data_summary[:600])
Output:
Records: 740 patients
Heart disease present (num > 0): 383 (51.8%)
No heart disease (num = 0): 357 (48.2%)
--- Heart Disease Stage Distribution (num column) ---
patients pct
stage 0 (no disease) 357 48.2
stage 1 204 27.6
stage 2 79 10.7
stage 3 78 10.5
stage 4 22 3.0
--- Sex Distribution ---
sex
Male 566
Female 174
--- Numeric Stats (overall) ---
age trestbps chol thalch oldpeak
count 740.00 740.00 740.00 740.00 740.00
mean 53.10 132.75 22
The build_summary function divides the patient data into eleven blocks. Each block covers a different aspect of the dataset, and together they give Claude both the binary and the staged view of heart disease.
- Overview counts. Total number of patients, how many have heart disease (
num > 0), and how many do not, with percentages for both groups. - Stage distribution. A table built from the raw
numcolumn showing how many patients fall into stage 0, stage 1, stage 2, stage 3, and stage 4, along with the percentage share of each stage. This is the block that lets Claude reason about severity rather than just presence. - Sex distribution. Counts of male and female patients in the dataset.
- Numeric stats overall. The pandas
describe()output for age, resting blood pressure (trestbps), cholesterol (chol), maximum heart rate achieved (thalch), and ST depression (oldpeak). This gives Claude the mean, standard deviation, min, max, and quartiles for every numeric clinical feature. - Averages by binary disease status. The same five numeric features averaged separately for the no-disease group and the disease group, so Claude can quickly point out which features differ the most when disease is present.
- Averages by stage. The same five numeric features averaged across each value of
numfrom 0 to 4. This block is what lets the chatbot describe how cholesterol, maximum heart rate, ST depression, and the rest shift as severity increases. - Chest pain type vs disease. For every chest pain category in the
cpcolumn (typical angina, atypical angina, non-anginal, asymptomatic), the number of patients, the count with heart disease, and the disease rate as a percentage. - Chest pain type vs stage. A table counting how many patients land in each combination of chest pain type and disease stage. This is useful for spotting which chest pain category dominates in the higher stages.
- Age group breakdown. Patients are bucketed into <40, 40-49, 50-59, 60-69, and 70+. For each bucket the function reports the patient count, the disease count, the average stage, the average cholesterol, the average resting blood pressure, the average maximum heart rate, and the disease rate as a percentage.
- Sex vs disease. Disease counts and rates split by male and female patients.
- Cholesterol threshold and exercise-induced angina. Two short tables checking whether having cholesterol at or above 240 mg/dL changes the disease rate, and whether exercise-induced angina does the same. Both appear in the standard heart disease literature as risk markers, so they earn their own blocks in the summary.
These eleven blocks together stay well within Claude’s context window even though they are computed over every patient in the database, which is the whole point of pre-aggregating before sending the data to the model.
Create Chatbot
With the summary in place, we wire up the chatbot. The system prompt embeds the entire summary and tells Claude to back every observation with concrete numbers. The HeartDiseaseChatbot class keeps a running conversation history so follow-up questions naturally build on what was already discussed.
In the script below we use the Claude Sonnet 4.6 model. You can swap in any other Anthropic model if you prefer.
SYSTEM_PROMPT = f"""You are a clinical data analyst. You have records for {len(heart_disease_db)} patients
from the UCI Heart Disease dataset. Each record includes age, sex, chest pain type (cp),
resting blood pressure (trestbps), cholesterol (chol), fasting blood sugar (fbs),
resting ECG (restecg), maximum heart rate achieved (thalch), exercise-induced angina (exang),
and ST depression (oldpeak). The heart_disease column is 1 when disease is present and 0 otherwise.
Always ground your answers in the specific numbers from the summary below. When you give
recommendations, frame them as data-backed observations rather than medical advice, and remind
the user that any clinical decision should be reviewed by a qualified healthcare professional.
DATA:
{data_summary}
"""
class HeartDiseaseChatbot:
def __init__(self):
self.client = anthropic.Anthropic()
self.history = []
def ask(self, question):
self.history.append({"role": "user", "content": question})
response = self.client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
system=SYSTEM_PROMPT,
messages=self.history
)
answer = response.content[0].text
self.history.append({"role": "assistant", "content": answer})
return answer
def reset(self):
self.history = []
print("History cleared.")
chatbot = HeartDiseaseChatbot()
print("Chatbot ready!")
Output:
Chatbot ready!
The chatbot is initialized and ready to answer questions about the patient records.
Ask Questions
Let’s test the chatbot with three questions covering risk factor patterns, age group comparisons, and a follow-up that builds on the previous answer.
Question 1: Most Common Risk Factors Among Heart Disease Patients
print(chatbot.ask("Which risk factors appear most often among patients who have heart disease? Cite specific numbers."))
Output (partial screenshot):
The chatbot walks through the dominant risk patterns. Asymptomatic chest pain stands out as the strongest signal, with disease rates well above the rates seen for typical angina or non-anginal pain. Patients in the disease group also show a noticeably higher average ST depression value and a lower average maximum heart rate during exercise compared to patients without disease. Cholesterol differences are smaller than most people expect, while exercise-induced angina is far more common in the disease group.
Question 2: Age Group Comparison
print(chatbot.ask("Compare heart disease rates across age groups. How do the average cholesterol and resting blood pressure shift with age?"))
Output (partial screenshot):
Claude lays out the age group breakdown, showing how disease rates climb from the youngest cohort through the 60-69 bracket. It also notes that resting blood pressure trends upward with age while maximum achievable heart rate drops, which lines up with what is seen in clinical practice.
Question 3: Best Single Indicator
print(chatbot.ask("Based on what you just told me, which single feature would be the most useful early warning sign for a clinician to focus on?"))
Output (partial screenshot):
Because the chatbot retains conversation history, this follow-up question builds directly on the previous analysis. Claude points to asymptomatic chest pain combined with reduced maximum heart rate during exercise as the most discriminating combination in the dataset, and frames the conclusion as a data observation rather than a clinical instruction.
Execute Code and Generate Charts
Beyond text answers, we can ask Claude to write matplotlib code for visualizations. The generate_and_run_chart function sends a chart description to Claude, takes the returned Python code, and runs it inline so the chart appears right under the request.
client = anthropic.Anthropic()
def generate_and_run_chart(question):
"""
Ask Claude to generate matplotlib code for a chart, then execute it.
The chart displays inline in the notebook.
"""
schema = f"Columns: {list(heart_disease_db.columns)}\nSample:\n{heart_disease_db.head(3).to_csv(index=False)}"
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
messages=[{
"role": "user",
"content": f"""I have a pandas DataFrame `heart_disease_db` with this structure:
{schema}
The heart_disease column is 1 if disease is present and 0 otherwise.
Chest pain type (cp) is a string column with values: 'typical angina', 'atypical angina', 'non-anginal', 'asymptomatic'.
Write Python code using pandas and matplotlib to: {question}
RULES:
- Return ONLY Python code, no markdown fences, no explanation
- heart_disease_db is already loaded, matplotlib.pyplot is imported as plt
- Use plt.figure(figsize=(10, 6)) for good sizing
- Always include plt.tight_layout() and plt.show()
- Add a clear title, axis labels, and a legend where needed"""
}]
)
code = response.content[0].text
code = re.sub(r'^
python\s*’, ”, code, flags=re.MULTILINE)
code = re.sub(r’^\s*$', '', code, flags=re.MULTILINE)
code = code.strip()
print("Generated code:")
print("-" * 40)
print(code)
print("-" * 40)
print("\nExecuting...\n")
exec(code, globals())
We create a module-level `client` at the top of the cell because `generate_and_run_chart` references it directly inside its body. The `HeartDiseaseChatbot` class earlier built its own client as an instance attribute (`self.client`), which is not visible from outside the class, so the chart helper needs its own handle.
The function passes the dataframe schema and a plain English chart description to Claude, which sends back ready-to-run matplotlib code. The `exec(code, globals())` call runs the code in the global scope so it can see `heart_disease_db`, `plt`, and `pd`.
Let's plot a few charts that highlight the patterns we discussed above.
#### Chart 1: Disease Rate by Age Group
python
generate_and_run_chart("Bar chart showing the percentage of patients with heart disease across age groups (<40, 40-49, 50-59, 60-69, 70+). Put the percentage on top of each bar.")
**Output:**
<img src="images\img6-disease-rate-by-age.png">
The chart confirms the steady climb in disease rate from the youngest cohort through middle and older age groups.
#### Chart 2: Disease Rate by Chest Pain Type
python
generate_and_run_chart("Bar chart showing the percentage of patients with heart disease for each chest pain type. Use the labels typical angina, atypical angina, non-anginal, asymptomatic on the x axis.")
**Output:**
<img src="images\img7-disease-rate-by-cp.png">
Asymptomatic chest pain ends up with by far the highest disease rate, which matches what the chatbot pointed out in its first answer.
#### Chart 3: Cholesterol Distribution by Disease Status
python
generate_and_run_chart("Two overlapping histograms of cholesterol values, one for patients with heart disease and one for patients without. Use different colors and add a legend.")
Output:
The histogram shows that while cholesterol distributions for the two groups overlap considerably, the disease group has a slightly heavier right tail.
Conclusion
This article showed how to combine the Anthropic Claude API with GridDB Cloud to build an AI-powered heart disease analysis chatbot. The chatbot pulls patient records out of GridDB, summarizes them on the fly, and lets you ask plain natural language questions about risk factors, age group differences, and individual features. The chart generation step extends it further by producing matplotlib visualizations from natural language descriptions, so you can dig into the data visually without writing plotting code by hand.
You can extend this approach by adding more clinical features such as serum thalassemia type or number of major vessels colored by fluoroscopy, by joining records from multiple cohorts for cross-population comparison, or by hooking the chatbot up to live patient databases for ongoing monitoring. The pairing of a fast structured database and a reasoning model opens up plenty of room for clinical decision support tools, so long as the medical professionals stay firmly in the loop.
You can find the complete code for this blog on the GridDB Blogs GitHub repository. If you have any questions or queries related to GridDB, create a post on Stack Overflow with the griddb tag. Our engineers are more than happy to respond.
Jupyter Format
Installing and Importing Required Libraries¶
!pip install -q python-dotenv
!pip install -q anthropic
import pandas as pd
import matplotlib.pyplot as plt
import base64
import os
import requests
import json
import re
import anthropic
from dotenv import load_dotenv
load_dotenv()
True
Importing the Dataset¶
dataset = pd.read_csv("heart_disease_uci.csv", encoding='utf-8')
keep_cols = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs',
'restecg', 'thalch', 'exang', 'oldpeak', 'num']
dataset = dataset[keep_cols].dropna().reset_index(drop=True)
# Convert the multi-class target to a binary heart disease flag
dataset['heart_disease'] = (dataset['num'] > 0).astype(int)
print(dataset.shape)
dataset.head()
(740, 12)
| age | sex | cp | trestbps | chol | fbs | restecg | thalch | exang | oldpeak | num | heart_disease | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 63 | Male | typical angina | 145.0 | 233.0 | True | lv hypertrophy | 150.0 | False | 2.3 | 0 | 0 |
| 1 | 67 | Male | asymptomatic | 160.0 | 286.0 | False | lv hypertrophy | 108.0 | True | 1.5 | 2 | 1 |
| 2 | 67 | Male | asymptomatic | 120.0 | 229.0 | False | lv hypertrophy | 129.0 | True | 2.6 | 1 | 1 |
| 3 | 37 | Male | non-anginal | 130.0 | 250.0 | False | normal | 187.0 | False | 3.5 | 0 | 0 |
| 4 | 41 | Female | atypical angina | 130.0 | 204.0 | False | lv hypertrophy | 172.0 | False | 1.4 | 0 | 0 |
Inserting Data in GridDB¶
Creating a GridDB Connection¶
username = os.environ.get("username")
password = os.environ.get("password")
base_url = os.environ.get("base_url")
url = f"{base_url}/checkConnection"
credentials = f"{username}:{password}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
headers = {
'Content-Type': 'application/json',
'Authorization': f'Basic {encoded_credentials}',
'User-Agent': 'PostmanRuntime/7.29.0'
}
response = requests.get(url, headers=headers)
print(response.status_code)
200
Creating a GridDB Container for Patient Records¶
dataset.insert(0, "SerialNo", dataset.index + 1)
dataset.columns.name = None
# Mapping pandas dtypes to GridDB types
type_mapping = {
"int64": "LONG",
"float64": "DOUBLE",
"bool": "BOOL",
"datetime64": "TIMESTAMP",
"object": "STRING",
"category": "STRING",
}
# Generate the columns part of the payload dynamically
columns = []
for col, dtype in dataset.dtypes.items():
griddb_type = type_mapping.get(str(dtype), "STRING")
columns.append({
"name": col,
"type": griddb_type
})
print(columns)
[{'name': 'SerialNo', 'type': 'LONG'}, {'name': 'age', 'type': 'LONG'}, {'name': 'sex', 'type': 'STRING'}, {'name': 'cp', 'type': 'STRING'}, {'name': 'trestbps', 'type': 'DOUBLE'}, {'name': 'chol', 'type': 'DOUBLE'}, {'name': 'fbs', 'type': 'STRING'}, {'name': 'restecg', 'type': 'STRING'}, {'name': 'thalch', 'type': 'DOUBLE'}, {'name': 'exang', 'type': 'STRING'}, {'name': 'oldpeak', 'type': 'DOUBLE'}, {'name': 'num', 'type': 'LONG'}, {'name': 'heart_disease', 'type': 'LONG'}]
container_name = "heart_disease_db"
url = f"{base_url}/containers"
payload = json.dumps({
"container_name": container_name,
"container_type": "COLLECTION",
"rowkey": True,
"columns": columns
})
response = requests.post(url, headers=headers, data=payload)
print(f"Status Code: {response.status_code}")
Status Code: 201
Inserting Patient Records into the GridDB Container¶
url = f"{base_url}/containers/{container_name}/rows"
def format_row(row):
formatted = []
for item in row:
if pd.isna(item):
formatted.append(None)
elif isinstance(item, bool):
formatted.append(str(item).lower())
elif isinstance(item, (int, float)):
formatted.append(item)
else:
formatted.append(str(item))
return formatted
rows = [format_row(row) for row in dataset.values.tolist()]
payload = json.dumps(rows)
response = requests.put(url, headers=headers, data=payload)
print(f"Status Code: {response.status_code}")
print(f"Response Text: {response.text}")
Status Code: 200
Response Text: {"count":740}
Using AI to Analyze Patient Records and Get Insights¶
Retrieve Data from GridDB¶
url = f"{base_url}/containers/{container_name}/rows"
payload = json.dumps({
"offset": 0,
"limit": 10000,
"condition": "",
"sort": ""
})
response = requests.post(url, headers=headers, data=payload)
print(f"Status Code: {response.status_code}")
if response.status_code == 200:
try:
data = response.json()
print("Data retrieved successfully!")
rows = data.get("rows", [])
heart_disease_db = pd.DataFrame(rows, columns=[col for col in dataset.columns])
except json.JSONDecodeError:
print("Error: Failed to decode JSON response.")
else:
print(f"Error: Failed to query data from the container. Response: {response.text}")
print(heart_disease_db.shape)
heart_disease_db.head()
Status Code: 200 Data retrieved successfully! (740, 13)
| SerialNo | age | sex | cp | trestbps | chol | fbs | restecg | thalch | exang | oldpeak | num | heart_disease | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 63 | Male | typical angina | 145.0 | 233.0 | true | lv hypertrophy | 150.0 | false | 2.3 | 0 | 0 |
| 1 | 2 | 67 | Male | asymptomatic | 160.0 | 286.0 | false | lv hypertrophy | 108.0 | true | 1.5 | 2 | 1 |
| 2 | 3 | 67 | Male | asymptomatic | 120.0 | 229.0 | false | lv hypertrophy | 129.0 | true | 2.6 | 1 | 1 |
| 3 | 4 | 37 | Male | non-anginal | 130.0 | 250.0 | false | normal | 187.0 | false | 3.5 | 0 | 0 |
| 4 | 5 | 41 | Female | atypical angina | 130.0 | 204.0 | false | lv hypertrophy | 172.0 | false | 1.4 | 0 | 0 |
Build Dataset Summary¶
NUMERIC_COLS = ['age', 'trestbps', 'chol', 'thalch', 'oldpeak']
STAGE_LABELS = {
0: 'stage 0 (no disease)',
1: 'stage 1',
2: 'stage 2',
3: 'stage 3',
4: 'stage 4'
}
def build_summary(df):
parts = []
# Overview
total = len(df)
diseased = int(df['heart_disease'].sum())
healthy = total - diseased
parts.append(f"Records: {total} patients")
parts.append(f"Heart disease present (num > 0): {diseased} ({diseased/total*100:.1f}%)")
parts.append(f"No heart disease (num = 0): {healthy} ({healthy/total*100:.1f}%)")
# Stage breakdown using the original num column (0 to 4)
stage_counts = df['num'].value_counts().sort_index()
stage_table = pd.DataFrame({
'patients': stage_counts,
'pct': (stage_counts / total * 100).round(1)
})
stage_table.index = [STAGE_LABELS.get(int(i), str(i)) for i in stage_table.index]
parts.append(f"\n--- Heart Disease Stage Distribution (num column) ---\n{stage_table.to_string()}")
# Sex distribution
sex_counts = df['sex'].value_counts()
parts.append(f"\n--- Sex Distribution ---\n{sex_counts.to_string()}")
# Numeric stats overall
parts.append(f"\n--- Numeric Stats (overall) ---\n{df[NUMERIC_COLS].describe().round(2).to_string()}")
# Numeric stats split by heart disease status
grouped = df.groupby('heart_disease')[NUMERIC_COLS].mean().round(2)
grouped.index = ['no disease', 'disease']
parts.append(f"\n--- Avg by Heart Disease Status ---\n{grouped.to_string()}")
# Numeric stats split by stage (0 to 4)
stage_grouped = df.groupby('num')[NUMERIC_COLS].mean().round(2)
stage_grouped.index = [STAGE_LABELS.get(int(i), str(i)) for i in stage_grouped.index]
parts.append(f"\n--- Avg by Stage ---\n{stage_grouped.to_string()}")
# Chest pain type vs disease (cp is already a string in the Kaggle file:
# typical angina, atypical angina, non-anginal, asymptomatic)
cp_counts = df.groupby('cp')['heart_disease'].agg(['count', 'sum'])
cp_counts['rate_pct'] = (cp_counts['sum'] / cp_counts['count'] * 100).round(1)
parts.append(f"\n--- Chest Pain Type vs Disease ---\n{cp_counts.to_string()}")
# Chest pain type vs stage (cross tab)
stage_named = df['num'].map(STAGE_LABELS)
cp_stage = pd.crosstab(df['cp'], stage_named)
parts.append(f"\n--- Chest Pain Type vs Stage (counts) ---\n{cp_stage.to_string()}")
# Age groups
bins = [0, 40, 50, 60, 70, 100]
labels = ['<40', '40-49', '50-59', '60-69', '70+']
df_local = df.copy()
df_local['age_group'] = pd.cut(df_local['age'], bins=bins, labels=labels, right=False)
age_stats = df_local.groupby('age_group').agg(
patients=('age', 'count'),
disease_count=('heart_disease', 'sum'),
avg_stage=('num', 'mean'),
avg_chol=('chol', 'mean'),
avg_bp=('trestbps', 'mean'),
avg_max_hr=('thalch', 'mean')
).round(2)
age_stats['disease_rate_pct'] = (age_stats['disease_count'] / age_stats['patients'] * 100).round(1)
parts.append(f"\n--- Age Group Breakdown ---\n{age_stats.to_string()}")
# Sex vs disease
sex_stats = df.groupby('sex')['heart_disease'].agg(['count', 'sum'])
sex_stats['rate_pct'] = (sex_stats['sum'] / sex_stats['count'] * 100).round(1)
parts.append(f"\n--- Sex vs Disease ---\n{sex_stats.to_string()}")
# High cholesterol flag
df_local['high_chol'] = df_local['chol'] >= 240
chol_stats = df_local.groupby('high_chol')['heart_disease'].agg(['count', 'sum'])
chol_stats['rate_pct'] = (chol_stats['sum'] / chol_stats['count'] * 100).round(1)
chol_stats.index = ['chol < 240', 'chol >= 240']
parts.append(f"\n--- High Cholesterol vs Disease ---\n{chol_stats.to_string()}")
# Exercise-induced angina
exang_stats = df.groupby('exang')['heart_disease'].agg(['count', 'sum'])
exang_stats['rate_pct'] = (exang_stats['sum'] / exang_stats['count'] * 100).round(1)
parts.append(f"\n--- Exercise-Induced Angina vs Disease ---\n{exang_stats.to_string()}")
return "\n".join(parts)
data_summary = build_summary(heart_disease_db)
print(data_summary[:600])
Records: 740 patients
Heart disease present (num > 0): 383 (51.8%)
No heart disease (num = 0): 357 (48.2%)
--- Heart Disease Stage Distribution (num column) ---
patients pct
stage 0 (no disease) 357 48.2
stage 1 204 27.6
stage 2 79 10.7
stage 3 78 10.5
stage 4 22 3.0
--- Sex Distribution ---
sex
Male 566
Female 174
--- Numeric Stats (overall) ---
age trestbps chol thalch oldpeak
count 740.00 740.00 740.00 740.00 740.00
mean 53.10 132.75 22
/tmp/ipykernel_17137/2023547795.py:64: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning.
age_stats = df_local.groupby('age_group').agg(
Creating Chatbot¶
SYSTEM_PROMPT = f"""You are a clinical data analyst. You have records for {len(heart_disease_db)} patients
from the UCI Heart Disease dataset. Each record includes age, sex, chest pain type (cp),
resting blood pressure (trestbps), cholesterol (chol), fasting blood sugar (fbs),
resting ECG (restecg), maximum heart rate achieved (thalch), exercise-induced angina (exang),
and ST depression (oldpeak). The heart_disease column is 1 when disease is present and 0 otherwise.
Always ground your answers in the specific numbers from the summary below. When you give
recommendations, frame them as data-backed observations rather than medical advice, and remind
the user that any clinical decision should be reviewed by a qualified healthcare professional.
DATA:
{data_summary}
"""
class HeartDiseaseChatbot:
def __init__(self):
self.client = anthropic.Anthropic()
self.history = []
def ask(self, question):
self.history.append({"role": "user", "content": question})
response = self.client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
system=SYSTEM_PROMPT,
messages=self.history
)
answer = response.content[0].text
self.history.append({"role": "assistant", "content": answer})
return answer
def reset(self):
self.history = []
print("History cleared.")
chatbot = HeartDiseaseChatbot()
print("Chatbot ready!")
Chatbot ready!
Ask Questions¶
# Q1: Most common risk factors among heart disease patients
print(chatbot.ask("Which risk factors appear most often among patients who have heart disease? Cite specific numbers."))
# Key Risk Factors Associated with Heart Disease in This Dataset Here is a breakdown of the factors most strongly associated with heart disease presence across the 383 affected patients (51.8% of the 740 total). All figures come directly from the data summary. --- ## 1. 🫀 Exercise-Induced Angina — Strongest Single Predictor - Patients **with** exercise-induced angina had a disease rate of **81.8%** (242 of 296 patients) - Patients **without** it had a rate of only **31.8%** (141 of 444) - That is a **50 percentage-point gap**, making this the sharpest dividing factor in the dataset --- ## 2. 💔 Chest Pain Type (Asymptomatic = High Risk) - **Asymptomatic** chest pain had by far the highest disease rate: **76.0%** (298 of 392 patients) - Compare that to **atypical angina** at only **14.7%** (22 of 150) and **non-anginal pain** at **30.4%** (49 of 161) - Counterintuitively, the *absence* of classic symptoms was most strongly linked to disease presence --- ## 3. 👴 Age — Clear Gradient Across Groups | Age Group | Disease Rate | |-----------|-------------| | Under 40 | 27.3% | | 40–49 | 39.6% | | 50–59 | 53.0% | | 60–69 | **70.3%** | | 70+ | **69.6%** | - Disease rates more than **doubled** from the youngest to oldest groups - Average age for disease patients was **55.7** vs. **50.3** for those without --- ## 4. 🚹 Sex — Large Disparity - **Male** patients had a disease rate of **60.1%** (340 of 566) - **Female** patients had a rate of only **24.7%** (43 of 174) - Males represent **88.8%** of all disease cases (340 of 383) in this dataset --- ## 5. 📉 Maximum Heart Rate (thalch) — Lower Is Riskier - Disease patients averaged a max heart rate of **128.91 bpm** - Non-disease patients averaged **149.29 bpm** — a difference of **~20 beats per minute** - This gap widens at higher stages: Stage 4 patients averaged only **130.55 bpm** --- ## 6. 📈 ST Depression (oldpeak) — Rises With Severity - Disease patients averaged an oldpeak of **1.33** vs. **0.43** for non-disease patients — **3× higher** - The value climbs steadily by stage: 0.43 → 1.09 → 1.39 → 1.60 → **2.36** at Stage 4 --- ## 7. 🩸 Resting Blood Pressure — Modest But Consistent Elevation - Disease patients averaged **135.44 mmHg** vs. **129.87 mmHg** — a modest **~5.6 mmHg** difference - Resting BP also rises across stages, reaching **142.23 mmHg** at Stage 4 --- ## ⚠️ Notable Finding on Cholesterol - Cholesterol tells a **surprising story**: disease patients actually had *lower* average cholesterol (**207.83**) than non-disease patients (**233.34**) - The high vs. low cholesterol split showed nearly identical disease rates (~51–53%), suggesting **cholesterol alone is not a strong discriminator** in this dataset --- > **Important note:** These are observational associations from a specific dataset of 740 patients. They should not be interpreted as diagnostic criteria. Any clinical decisions must be reviewed by a qualified healthcare professional.
# Q2: Age group comparison
print(chatbot.ask("Compare heart disease rates across age groups. How do the average cholesterol and resting blood pressure shift with age?"))
# Heart Disease, Cholesterol & Blood Pressure Across Age Groups Here is a detailed breakdown using the exact figures from the dataset of 740 patients. --- ## 📊 Heart Disease Rate by Age Group — A Clear Escalation | Age Group | Patients | Disease Cases | Disease Rate | Avg Stage | |-----------|----------|---------------|--------------|-----------| | Under 40 | 66 | 18 | 27.3% | 0.35 | | 40–49 | 182 | 72 | 39.6% | 0.54 | | 50–59 | 304 | 161 | 53.0% | 0.91 | | 60–69 | 165 | 116 | 70.3% | 1.50 | | 70+ | 23 | 16 | 69.6% | 1.65 | ### Key Observations: - Disease rate **more than doubles** from the under-40 group (27.3%) to the 60–69 group (70.3%) - The steepest single jump occurs between **50–59 (53.0%) and 60–69 (70.3%)** — a **17.3 percentage point** leap - The **70+ group** (69.6%) is slightly lower than 60–69, but this group has only **23 patients**, making it the smallest and least statistically robust cohort - Average disease stage also rises consistently, from **0.35** in the youngest group to **1.65** in the oldest — reflecting not just more disease, but **more severe disease** with age - The 50–59 bracket is the **largest group at 304 patients (41% of the dataset)**, crossing the majority threshold for disease presence at 53.0% --- ## 🩸 Resting Blood Pressure by Age Group — Steady Climb | Age Group | Avg Resting BP | |-----------|---------------| | Under 40 | 124.82 mmHg | | 40–49 | 127.94 mmHg | | 50–59 | 133.95 mmHg | | 60–69 | 137.98 mmHg | | 70+ | 140.35 mmHg | ### Key Observations: - Blood pressure rises **monotonically** across every age group without exception - From the youngest to oldest group, average BP increases by **15.53 mmHg** (124.82 → 140.35) - The largest single-group jump is between **40–49 and 50–59**, where BP rises by **6.01 mmHg** - The 70+ group at **140.35 mmHg** sits above the commonly referenced 130 mmHg threshold for elevated BP - This consistent upward trend aligns with the simultaneous rise in disease rates, though correlation does not establish causation --- ## 🧪 Cholesterol by Age Group — A More Complex Pattern | Age Group | Avg Cholesterol | |-----------|----------------| | Under 40 | 226.26 mg/dL | | 40–49 | 228.90 mg/dL | | 50–59 | 221.52 mg/dL | | 60–69 | 206.85 mg/dL | | 70+ | 210.30 mg/dL | ### Key Observations: - Unlike blood pressure, cholesterol does **not rise steadily with age** — it actually **peaks in the 40–49 group (228.90)** and **declines in older groups** - The 60–69 group has the **lowest average cholesterol at 206.85 mg/dL**, despite having the highest disease rate (70.3%) - This mirrors the overall dataset finding that disease patients had *lower* average cholesterol (207.83) than non-disease patients (233.34) - One possible data-backed explanation: higher-risk, older patients may have lower recorded cholesterol due to treatment, survivorship effects, or other clinical factors — but this interpretation requires professional clinical judgment --- ## 🔍 Putting It All Together | Age Group | Disease Rate | Avg Chol | Avg BP | Avg Max HR | |-----------|-------------|----------|--------|------------| | Under 40 | 27.3% | 226.26 | 124.82 | 159.91 | | 40–49 | 39.6% | 228.90 | 127.94 | 146.42 | | 50–59 | 53.0% | 221.52 | 133.95 | 135.71 | | 60–69 | 70.3% | 206.85 | 137.98 | 129.78 | | 70+ | 69.6% | 210.30 | 140.35 | 121.70 | - **Blood pressure and disease rate move in the same direction** across all age groups - **Maximum heart rate declines steadily** with age (159.91 → 121.70), and as noted earlier, lower max HR is strongly associated with disease - **Cholesterol moves inversely** to disease rate across age groups — a counterintuitive finding that underscores why no single biomarker should be assessed in isolation --- > **Important reminder:** These are descriptive patterns from 740 patient records and should not be used as a basis for individual clinical decisions. Please consult a qualified healthcare professional for any diagnostic or treatment considerations.
# Q3: Follow-up
print(chatbot.ask("Based on what you just told me, which single feature would be the most useful early warning sign for a clinician to focus on?"))
# Most Useful Single Early Warning Feature: A Data-Driven Assessment This is an important question, and the data offers a reasonably clear answer — though with important nuances worth unpacking. --- ## 🏆 The Strongest Single Indicator: Exercise-Induced Angina Based purely on the numbers in this dataset, **exercise-induced angina (exang)** produces the sharpest, cleanest separation between disease and non-disease patients: - Patients **with** exercise-induced angina: **81.8% disease rate** (242 of 296) - Patients **without** it: **31.8% disease rate** (141 of 444) - That is a **50 percentage-point gap** — larger than any other single binary factor in the dataset No other individual feature creates this magnitude of split. --- ## 📊 How Other Strong Candidates Compare | Feature | Key Finding | Limitation | |--------|-------------|------------| | **Exercise-induced angina** | 81.8% vs 31.8% disease rate | Requires an exercise test to measure | | **Asymptomatic chest pain** | 76.0% disease rate | Paradoxically silent — patient may not volunteer it | | **Age 60–69** | 70.3% disease rate | Not modifiable or actionable on its own | | **Max heart rate (thalch)** | 128.91 vs 149.29 avg | Also requires exercise testing | | **ST depression (oldpeak)** | 1.33 vs 0.43 avg; 3× higher in disease patients | Also requires exercise testing | | **Sex (Male)** | 60.1% vs 24.7% | Demographic, not a symptom or measurement | | **Resting BP** | 135.44 vs 129.87 avg | Only ~5.6 mmHg difference — modest gap | | **Cholesterol** | Moves *inversely* to disease in this data | Weak and counterintuitive signal here | --- ## ⚖️ A Critical Nuance: "Early Warning" Changes the Answer If the goal is specifically **early warning** — meaning detection *before* a stress test is ordered — then the picture shifts somewhat: ### Most Accessible Without Specialized Testing: | Feature | Why It Matters | Disease Rate Differential | |---------|---------------|--------------------------| | **Age** | Immediately known | Rate jumps from 27.3% to 70.3% across groups | | **Sex** | Immediately known | 60.1% (male) vs 24.7% (female) | | **Resting BP** | Routine clinical measurement | Rises consistently across all age groups and stages | | **Chest pain type** | Reported by patient | Asymptomatic type = 76.0% disease rate | ### The Standout for Early, Accessible Warning: **Asymptomatic chest pain pattern** combined with **age over 50** may be the most *clinically actionable* early signal without requiring exercise testing: - Asymptomatic chest pain alone carries a **76.0% disease rate** - Disease rate crosses 50% at age **50–59** and hits **70.3%** by 60–69 - These are observations a clinician can gather from a **basic patient interview and vital signs** --- ## 🔑 Bottom Line From the Data | Context | Best Single Feature | |---------|-------------------| | Pure statistical separation | **Exercise-induced angina** (50-point gap) | | No exercise test available | **Chest pain type (asymptomatic)** (76.0% disease rate) | | Routine screening context | **Age + resting BP together** (both rise monotonically with disease) | | Lowest-effort first filter | **Sex + Age** (male, over 50 → meaningful elevated baseline risk) | The data most strongly supports **exercise-induced angina** as the single most discriminating feature numerically. However, since it requires a stress test, **asymptomatic chest pain presentation** may serve as the most practically accessible early warning flag in a routine clinical encounter. --- > ⚠️ **Important disclaimer:** This analysis reflects statistical patterns in 740 historical patient records only. It is not a clinical decision-making tool, diagnostic algorithm, or substitute for professional medical judgment. Any decisions about patient screening, testing, or treatment must be made by a qualified healthcare professional with full access to the patient's clinical context.
Execute Code and Generate Charts¶
client = anthropic.Anthropic()
def generate_and_run_chart(question):
"""
Ask Claude to generate matplotlib code for a chart, then execute it.
The chart displays inline in the notebook.
"""
schema = f"Columns: {list(heart_disease_db.columns)}\nSample:\n{heart_disease_db.head(3).to_csv(index=False)}"
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
messages=[{
"role": "user",
"content": f"""I have a pandas DataFrame `heart_disease_db` with this structure:
{schema}
The heart_disease column is 1 if disease is present and 0 otherwise.
Chest pain type (cp) is a string column with values: 'typical angina', 'atypical angina', 'non-anginal', 'asymptomatic'.
Write Python code using pandas and matplotlib to: {question}
RULES:
- Return ONLY Python code, no markdown fences, no explanation
- heart_disease_db is already loaded, matplotlib.pyplot is imported as plt
- Use plt.figure(figsize=(10, 6)) for good sizing
- Always include plt.tight_layout() and plt.show()
- Add a clear title, axis labels, and a legend where needed"""
}]
)
code = response.content[0].text
code = re.sub(r'^```python\s*', '', code, flags=re.MULTILINE)
code = re.sub(r'^```\s*$', '', code, flags=re.MULTILINE)
code = code.strip()
print("Generated code:")
print("-" * 40)
print(code)
print("-" * 40)
print("\nExecuting...\n")
exec(code, globals())
# Chart 1: Disease rate by age group
generate_and_run_chart("Bar chart showing the percentage of patients with heart disease across age groups (<40, 40-49, 50-59, 60-69, 70+). Put the percentage on top of each bar.")
Generated code:
----------------------------------------
age_bins = [0, 39, 49, 59, 69, float('inf')]
age_labels = ['<40', '40-49', '50-59', '60-69', '70+']
heart_disease_db['age_group'] = pd.cut(heart_disease_db['age'], bins=age_bins, labels=age_labels, right=True)
age_group_stats = heart_disease_db.groupby('age_group', observed=True)['heart_disease'].agg(['sum', 'count']).reset_index()
age_group_stats.columns = ['age_group', 'disease_count', 'total_count']
age_group_stats['percentage'] = (age_group_stats['disease_count'] / age_group_stats['total_count']) * 100
plt.figure(figsize=(10, 6))
bars = plt.bar(
age_group_stats['age_group'],
age_group_stats['percentage'],
color='steelblue',
edgecolor='black',
width=0.6
)
for bar, pct in zip(bars, age_group_stats['percentage']):
plt.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.8,
f'{pct:.1f}%',
ha='center',
va='bottom',
fontsize=11,
fontweight='bold'
)
plt.title('Percentage of Patients with Heart Disease by Age Group', fontsize=14, fontweight='bold')
plt.xlabel('Age Group', fontsize=12)
plt.ylabel('Percentage with Heart Disease (%)', fontsize=12)
plt.ylim(0, max(age_group_stats['percentage']) * 1.15)
plt.xticks(fontsize=11)
plt.yticks(fontsize=11)
plt.legend(['Heart Disease Prevalence (%)'], loc='upper left', fontsize=10)
plt.tight_layout()
plt.show()
----------------------------------------
Executing...
# Chart 2: Disease rate by chest pain type
generate_and_run_chart("Bar chart showing the percentage of patients with heart disease for each chest pain type. Use the labels typical angina, atypical angina, non-anginal, asymptomatic on the x axis.")
Generated code:
----------------------------------------
cp_order = ['typical angina', 'atypical angina', 'non-anginal pain', 'asymptomatic']
cp_disease = heart_disease_db.groupby('cp')['heart_disease'].agg(['sum', 'count'])
cp_disease['percentage'] = (cp_disease['sum'] / cp_disease['count']) * 100
cp_disease = cp_disease.reindex(cp_order)
plt.figure(figsize=(10, 6))
bars = plt.bar(cp_order, cp_disease['percentage'], color=['steelblue', 'darkorange', 'green', 'red'], edgecolor='black', width=0.6)
for bar, pct in zip(bars, cp_disease['percentage']):
plt.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 1, f'{pct:.1f}%', ha='center', va='bottom', fontsize=11, fontweight='bold')
plt.title('Percentage of Patients with Heart Disease by Chest Pain Type', fontsize=14, fontweight='bold')
plt.xlabel('Chest Pain Type', fontsize=12)
plt.ylabel('Percentage with Heart Disease (%)', fontsize=12)
plt.xticks(fontsize=11)
plt.yticks(fontsize=11)
plt.ylim(0, 100)
plt.legend(handles=bars, labels=cp_order, title='Chest Pain Type', fontsize=10, title_fontsize=11)
plt.tight_layout()
plt.show()
----------------------------------------
Executing...
# Chart 3: Cholesterol distribution by disease status
generate_and_run_chart("Two overlapping histograms of cholesterol values, one for patients with heart disease and one for patients without. Use different colors and add a legend.")
Generated code:
----------------------------------------
plt.figure(figsize=(10, 6))
chol_disease = heart_disease_db[heart_disease_db['heart_disease'] == 1]['chol'].dropna()
chol_no_disease = heart_disease_db[heart_disease_db['heart_disease'] == 0]['chol'].dropna()
plt.hist(chol_no_disease, bins=30, color='steelblue', alpha=0.6, label='No Heart Disease')
plt.hist(chol_disease, bins=30, color='tomato', alpha=0.6, label='Heart Disease')
plt.title('Cholesterol Distribution by Heart Disease Status')
plt.xlabel('Cholesterol (mg/dl)')
plt.ylabel('Number of Patients')
plt.legend()
plt.tight_layout()
plt.show()
----------------------------------------
Executing...






