# Required packages for our course. Do not delete.
library(mosaic)
library(tidyverse)
library(ggplot2)
library(viridis)
library(reshape2)
library(ggthemes)
library(ggplot2)
library(plotly)
library(dplyr)

Big-picture

Research Question

What is the question you hope to answer with your infographic?

The primary objective of the Project is to examine the relationships between the target variable (indicating the presence or absence of heart disease) and other columns, including both continuous and categorical attributes. By understanding these relationships, I aim to gain insights into the factors that contribute to the risk of heart disease.

Data

Description of data

The data I am using in this project is derived from the Heart Disease dataset. The initial dataset comprising various features from patients was distilled to 14 relevant features, as identified in published studies. These features include demographic and clinical parameters such as age, sex, chest pain type, blood pressure, cholesterol levels, fasting blood sugar, resting ECG results, ST depression induced by exercise, etc. There is also a target variable that indicates if an individual is suffering from heart disease or not.

Load data into R

Include the code to load your data here. Using the head() function, show the first 10 rows of data.

# heart_data <- read_delim("/Users/siddharthbanyal/Downloads/Heart_csv.txt", delim = "\t", escape_double = FALSE,  trim_ws = TRUE)
df = read_csv('https://raw.githubusercontent.com/SidBanyal/Data_Wrangling/main/heart_dataset_raw.csv')
attach(df)
head(df,10)
## # A tibble: 10 × 18
##    HeartDisease   BMI Smoking AlcoholDrinking Stroke PhysicalHealth MentalHealth
##    <chr>        <dbl> <chr>   <chr>           <chr>           <dbl>        <dbl>
##  1 No            16.6 Yes     No              No                  3           30
##  2 No            20.3 No      No              Yes                 0            0
##  3 No            26.6 Yes     No              No                 20           30
##  4 No            24.2 No      No              No                  0            0
##  5 No            23.7 No      No              No                 28            0
##  6 Yes           28.9 Yes     No              No                  6            0
##  7 No            21.6 No      No              No                 15            0
##  8 No            31.6 Yes     No              No                  5            0
##  9 No            26.4 No      No              No                  0            0
## 10 No            40.7 No      No              No                  0            0
## # ℹ 11 more variables: DiffWalking <chr>, Sex <chr>, AgeCategory <chr>,
## #   Race <chr>, Diabetic <chr>, PhysicalActivity <chr>, GenHealth <chr>,
## #   SleepTime <dbl>, Asthma <chr>, KidneyDisease <chr>, SkinCancer <chr>

Variables

names(df)
##  [1] "HeartDisease"     "BMI"              "Smoking"          "AlcoholDrinking" 
##  [5] "Stroke"           "PhysicalHealth"   "MentalHealth"     "DiffWalking"     
##  [9] "Sex"              "AgeCategory"      "Race"             "Diabetic"        
## [13] "PhysicalActivity" "GenHealth"        "SleepTime"        "Asthma"          
## [17] "KidneyDisease"    "SkinCancer"

The variables I usedin my infographic design are:

  1. Age
  2. Sex
  3. SleepTime
  4. BMI
  5. HeartDisease
  6. AlcoholDrinking
  7. Smoking

Data Analysis

Summary Statistics

summary_stats <- lapply(df[, sapply(df, is.numeric)], favstats)
print(summary_stats)
## $BMI
##    min    Q1 median    Q3   max    mean     sd      n missing
##  12.02 24.03  27.34 31.42 94.85 28.3254 6.3561 319795       0
## 
## $PhysicalHealth
##  min Q1 median Q3 max    mean      sd      n missing
##    0  0      0  2  30 3.37171 7.95085 319795       0
## 
## $MentalHealth
##  min Q1 median Q3 max     mean       sd      n missing
##    0  0      0  3  30 3.898366 7.955235 319795       0
## 
## $SleepTime
##  min Q1 median Q3 max     mean       sd      n missing
##    1  6      7  8  24 7.097075 1.436007 319795       0

Section 1: Demographic Analysis 1/2 Sankey Chart

What is the information flow across demographics?

df1 <- df %>%
  group_by(AgeCategory, Sex) %>%
  summarise(value = n()) %>%
  ungroup() %>%
  rename(source = AgeCategory, target = Sex)

df3 <- df %>%
  group_by(Sex, HeartDisease) %>%
  summarise(value = n()) %>%
  ungroup() %>%
  rename(source = Sex, target = HeartDisease)


df_concat <- bind_rows(df1, df3)


source_target <- unique(c(df_concat$source, df_concat$target))


mapping_dict <- setNames(0:(length(source_target) - 1), source_target)

mapping_dict
##       18-24       25-29       30-34       35-39       40-44       45-49 
##           0           1           2           3           4           5 
##       50-54       55-59       60-64       65-69       70-74       75-79 
##           6           7           8           9          10          11 
## 80 or older      Female        Male          No         Yes 
##          12          13          14          15          16
df_concat$source <- mapping_dict[df_concat$source]
df_concat$target <- mapping_dict[df_concat$target]

links_dict <- list(
  source = df_concat$source,
  target = df_concat$target,
  value = df_concat$value
)

fig <- plot_ly(
  type = "sankey",
  node = list(
    pad = 15,
    thickness = 20,
    line = list(color = "green", width = 0.7),
    label = source_target,
    color = "lightseagreen"
  ),
  link = list(
    source = links_dict$source,
    target = links_dict$target,
    value = links_dict$value
  )
)

# Show the plot
fig

In the Sankey diagram, it is evident that males are more prone to heart attacks than females. Additionally, the visualization highlights a relatively lower number of records for individuals suffering from heart diseases in the dataset. Given the class imbalance and to address potential issues during machine learning modeling, it would be advisable to consider data preprocessing techniques. One effective approach is upsampling the minority class using methods like SMOTE (Synthetic Minority Over-sampling Technique) to create a more balanced dataset.

Demographic Analysis 2/2 Bar Graph

Is there a gender-specific correlation between age and heart disease?

df_Heart_Disease <- df[df$HeartDisease == 'Yes', ]

age_sex_groups <- df_Heart_Disease %>%
  group_by(AgeCategory, Sex) %>%
  summarise(HeartDisease = n()) %>%
  ungroup()

fig <- plot_ly(
  age_sex_groups,
  x = ~AgeCategory,
  y = ~HeartDisease,
  color = ~Sex,
  type = "bar",
  barmode = "group"
) %>%
  layout(
    title = "Heart Disease by Age Category and Sex",
    xaxis = list(title = "Age Category"),
    yaxis = list(title = "Heart Disease"),
    legend = list(title = "Sex")
  )

# Show the plot
fig

Insight: The people who are older are more prone to heart disease. Also, males are more prone to heart disease

Section 2: Metabolic Health Analysis 1/2

How do BMI levels align for individuals suffering from heart disease?

df_chart_sorted <- df_Heart_Disease[order(df_Heart_Disease$AgeCategory), ]

fig <- plot_ly(df_chart_sorted, 
               x = ~AgeCategory, 
               y = ~BMI, 
               type = 'violin', 
               box = list(visible = TRUE),
               points = 'all',
               color = ~AgeCategory)

fig <- fig %>% layout(title = 'BMI by Age Category',
                      xaxis = list(title = 'Age Category'),
                      yaxis = list(title = 'BMI'))
fig

Insight: As per CDC: If your BMI is less than 18.5, it falls within the underweight range. If your BMI is 18.5 to 24.9, it falls within the Healthy Weight range. If your BMI is 25.0 to 29.9, it falls within the overweight range. If your BMI is 30.0 or higher, it falls within the obese range. So in this graph we clearly see that there is a lot of variation and the BMI of people who are suffering from heart disease falls in unhealthy ranges.

Metabolic Health Analysis 2/2

How do cholesterol levels align for individuals suffering from heart disease?

heart_data <- read_delim("/Users/siddharthbanyal/Downloads/Heart_csv.txt", delim = "\t", escape_double = FALSE,  trim_ws = TRUE)

ggplot(data=heart_data, aes(x=age, y=chol, group=sex, color=factor(sex))) +
  geom_line() +
  geom_point() +
  scale_color_manual(values = c("#1f78b4", "#e41a1c"), labels = c("Male", "Female"))

Insight: The cholesterol levels observed here significantly exceed the healthy range, particularly with higher levels in males.

Section 3: Lifestyle Health Analysis 1/2

Is there a correlation between the occurrence of heart disease and the habits of smoking and alcohol consumption?

heart_disease_subset <- df[df$HeartDisease == "Yes", ]

heart_disease_subset$SmokingDrinking <- ifelse(heart_disease_subset$Smoking == "Yes" & heart_disease_subset$AlcoholDrinking == "Yes", "Smoking + Drinking",
                                               ifelse(heart_disease_subset$Smoking == "Yes", "Smoking Only",
                                                      ifelse(heart_disease_subset$AlcoholDrinking == "Yes", "Drinking Only", "Neither")))

combined_habits_plot <- plot_ly() %>%
  add_trace(type = 'bar', x = unique(heart_disease_subset$SmokingDrinking), 
            y = table(heart_disease_subset$SmokingDrinking),
            marker = list(color = 'rgba(255, 0, 0, 0.6)')) %>%
  layout(title = 'Comparison of Smoking and Drinking Habits among People with Heart Disease',
         xaxis = list(title = 'Habits'),
         yaxis = list(title = 'Count', range = c(0, 16000)))

combined_habits_plot

Insight: Individuals who engage in both smoking and drinking exhibit higher chances of experiencing heart disease, underlining the significance of addressing these risk factors for cardiovascular health.

Lifestyle Health Analysis 2/2

Is there a relationship between heart Disease and sleep?

heart_disease_subset <- df[df$HeartDisease == "Yes", ]


less_than_7_hours_count <- sum(heart_disease_subset$SleepTime < 7)
more_than_7_hours_count <- nrow(heart_disease_subset) - less_than_7_hours_count


red_and_blue_colors <- c('rgba(255, 0, 0, 0.6)', 'rgba(0, 0, 255, 0.6)')


heart_disease_sleep_comparison_pie <- plot_ly(labels = c("Less than 7 hours", "7 hours or more"),
                                              values = c(less_than_7_hours_count, more_than_7_hours_count),
                                              type = 'pie',
                                              marker = list(colors = red_and_blue_colors)) %>%
  layout(title = 'Proportion of Heart Disease based on Sleep Time')


heart_disease_sleep_comparison_pie

Yes, With a 1/3 chance, prioritizing quality sleep becomes crucial to mitigate the associated risk of heart attacks.

Option 1:

Made with Visme Infographic Maker

Presentation on Canva with graphics Option 2:

Heart by Siddharth Banyal

Brief description of my data visualization process:

The visualization process for uncovering heart diseases involves three key sections: Demographics Analysis, Metabolic Health Analysis, and Lifestyle Analysis. The journey begins with two doctors and a Data Scientist discovering the project. As they delve into the data, the visualization unfolds across these three sections, each revealing critical insights. Demographics Analysis: The first section focuses on demographics, exploring factors such as age, gender, and geographical location. Interactive graphs illustrate the distribution of heart diseases across different demographic groups. This part of the story introduces the doctors and the Data Scientist to the diverse aspects of the population under study. Metabolic Health Analysis: Moving on to the second section, the team delves into metabolic health factors, examining variables like cholesterol levels, blood pressure, and body mass index (BMI). The interactive graphs dynamically display correlations and trends, aiding the discovery of patterns that contribute to heart diseases. As the story progresses, the doctors and the Data Scientist gain deeper insights into the metabolic aspects influencing heart health. Lifestyle Analysis: In the final section, lifestyle factors such as diet, physical activity, and stress levels are explored. Engaging visualizations showcase the impact of various lifestyle choices on heart health. The interactive nature of the graphs allows the team to interact with the data, facilitating a comprehensive understanding of how lifestyle elements contribute to or mitigate the risk of heart diseases. Throughout the analysis journey, my characters the doctors and the Data Scientist collaboratively interpret the findings, leveraging the power of visualizations to make informed decisions. As the story concludes, the transformation of one of the doctors into a Data Scientist symbolizes the evolving role of healthcare professionals, blending medical expertise with data-driven insights for more effective disease prevention and management. The visualization process not only uncovers critical aspects of heart diseases but also highlights the potential for interdisciplinary collaboration in the evolving landscape of healthcare


References

Include any references that you might have used to construct your graphic. This may include, but is not limited to citations for: graphics used, coding techniques, data collection, R-Markdown/RStudio documentation, etc. Delete this when complete.

  1. https://www.cdc.gov/sleep/about_sleep/how_much_sleep.html
  2. https://archive.ics.uci.edu/datasets
  3. https://advance.org/meet-dr-martin-seneviratne-a-doctor-turned-data-scientist-bridging-the-divide-between-technology-and-healthcare/
  4. https://my.clevelandclinic.org/health/articles/11920-cholesterol-numbers-what-do-they-mean#:~:text=Your%20HDL%20(%E2%80%9Cgood%E2%80%9D%20cholesterol,how%20to%20manage%20your%20cholesterol.
  5. https://www.google.com/search?q=bmi+healthy+range&rlz=1C5CHFA_enIN851IN851&oq=bmi+healt&gs_lcrp=EgZjaHJvbWUqCggAEAAYsQMYgAQyCggAEAAYsQMYgAQyBwgBEAAYgAQyDQgCEC4YxwEY0QMYgAQyBwgDEAAYgAQyBggEEEUYOTIHCAUQABiABDIHCAYQABiABDIHCAcQABiABDIHCAgQABiABDIHCAkQABiABKgCALACAA&sourceid=chrome&ie=UTF-8 * * *

All done!