library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(janitor)
## 
## Attaching package: 'janitor'
## 
## The following objects are masked from 'package:stats':
## 
##     chisq.test, fisher.test
library(ggfortify)
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(reshape2)
## 
## Attaching package: 'reshape2'
## 
## The following object is masked from 'package:tidyr':
## 
##     smiths
library(gridExtra)
## 
## Attaching package: 'gridExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
library(highcharter)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo 
## Highcharts (www.highcharts.com) is a Highsoft software product which is
## not free for commercial and Governmental use
#library(shiny)
#library(shinyjs)
setwd("C:/Users/eyong/Downloads/heart_2022_no_nans.csv")
gf<- read_csv("heart_2022_no_nans.csv")
## Rows: 246022 Columns: 40
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (34): State, Sex, GeneralHealth, LastCheckupTime, PhysicalActivities, Re...
## dbl  (6): PhysicalHealthDays, MentalHealthDays, SleepHours, HeightInMeters, ...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
gf<-janitor::clean_names(gf)

# Select relevant columns from your dataframe
ha <- gf %>% select(state, sex, race_ethnicity_category, age_category, weight_in_kilograms, bmi, had_heart_attack,sleep_hours,height_in_meters,physical_health_days,mental_health_days)

race_p_summary <- ha %>%
  group_by(race_ethnicity_category, had_heart_attack) %>%
  summarise(count = n(), .groups = "drop")

# Create a highcharter stacked bar chart with tooltip showing the count
hchart(race_p_summary, "column", hcaes(x = race_ethnicity_category, y = log(count), group = had_heart_attack)) %>%
  hc_title(text = "Heart Attack by Race/Ethnicity") %>%
  hc_xAxis(title = list(text = "Race/Ethnicity")) %>%
  hc_yAxis(title = list(text = "Log of the Frequency")) %>%
  hc_plotOptions(column = list(stacking = "normal")) %>%
  hc_tooltip(
    pointFormat = "<b>Count:</b> {point.count}<br><b>Race/Ethnicity:</b> {point.race_ethnicity_category}<br><b>Heart Attack:</b> {point.had_heart_attack}"
  ) ## refrence for the  tooltip was chart gbt

ha$had_heart_attack <- factor(ha$had_heart_attack, levels = c("Yes", "No"))

# Aggregate data to count occurrences by state, sex, race_ethnicity_category, and had_heart_attack
agg_data <- ha %>%
  group_by(state, sex, race_ethnicity_category, had_heart_attack) %>%
  summarise(count = n(), .groups = 'drop')

# Create the Plotly bar graph
p <- agg_data %>%
  plot_ly(x = ~state, y = ~count, color = ~had_heart_attack, type = 'bar', 
          hoverinfo = 'text', 
          text = ~paste('State: ', state, '<br>Heart Attack: ', had_heart_attack, '<br>Count: ', count)) %>%
  layout(title = "Number of Heart Attacks per State by Sex and Ethnicity",
         xaxis = list(title = "State"),
         yaxis = list(title = "Number of Heart Attacks"),
         barmode = 'dodge', # Bars side-by-side for Yes and No
         facet = list(rows = 1, columns = 2, 
                      categoryorder = 'total ascending'))  # Facet by sex and race_ethnicity_category

# Show plot
p
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning: 'layout' objects don't have these attributes: 'facet'
## Valid attributes include:
## '_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'
# Loading necessary libraries
library(dplyr)
library(plotly)

# Assuming gf is the dataset and has the required columns
ha <- gf %>%
  select(sex, had_heart_attack) %>%
  group_by(sex, had_heart_attack) %>%
  summarise(count = n()) %>%
  ungroup()
## `summarise()` has grouped output by 'sex'. You can override using the `.groups`
## argument.
# Create an interactive plot with plotly
interactive_plot <- plot_ly(ha, 
                            x = ~sex, 
                            y = ~count, 
                            color = ~had_heart_attack, 
                            type = 'bar', 
                            barmode = 'dodge',
                            text = ~paste('Count:', count),
                            hoverinfo = 'text') %>%
  layout(title = 'Count of Males and Females with Heart Attack Status',
         xaxis = list(title = 'Sex'),
         yaxis = list(title = 'Count'),
         barmode = 'dodge')

# Display the plot
interactive_plot
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning: 'bar' objects don't have these attributes: 'barmode'
## Valid attributes include:
## '_deprecated', 'alignmentgroup', 'base', 'basesrc', 'cliponaxis', 'constraintext', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'insidetextanchor', 'insidetextfont', 'legendgroup', 'legendgrouptitle', 'legendrank', 'marker', 'meta', 'metasrc', 'name', 'offset', 'offsetgroup', 'offsetsrc', 'opacity', 'orientation', 'outsidetextfont', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textangle', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'width', 'widthsrc', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
## Warning: 'bar' objects don't have these attributes: 'barmode'
## Valid attributes include:
## '_deprecated', 'alignmentgroup', 'base', 'basesrc', 'cliponaxis', 'constraintext', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'insidetextanchor', 'insidetextfont', 'legendgroup', 'legendgrouptitle', 'legendrank', 'marker', 'meta', 'metasrc', 'name', 'offset', 'offsetgroup', 'offsetsrc', 'opacity', 'orientation', 'outsidetextfont', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textangle', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'width', 'widthsrc', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
ha$had_heart_attack <- factor(ha$had_heart_attack, levels = c("Yes", "No"))

# Aggregate data to count occurrences by state, sex, race_ethnicity_category, and had_heart_attack
agg_data <- gf %>%
  group_by(state, sex, race_ethnicity_category, had_heart_attack) %>%
  summarise(count = n(), .groups = 'drop')

# Create the Plotly bar graph
p <- agg_data %>%
  plot_ly(x = ~state, y = ~count, color = ~race_ethnicity_category, type = 'bar', 
          hoverinfo = 'text', 
          text = ~paste('State: ', state, '<br>Heart Attack: ', had_heart_attack, '<br>Count: ', count)) %>%
  layout(title = "Number of Heart Attacks per State by Sex and Ethnicity",
         xaxis = list(title = "State"),
         yaxis = list(title = "Number of Heart Attacks"),
         barmode = 'dodge', # Bars side-by-side for Yes and No
         facet = list(rows = 1, columns = 2, 
                      categoryorder = 'total ascending'))  # Facet by sex and race_ethnicity_category

# Show plot
p
## Warning: 'layout' objects don't have these attributes: 'facet'
## Valid attributes include:
## '_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'
ha$had_heart_attack <- factor(ha$had_heart_attack, levels = c("Yes", "No"))

# Aggregate data to count occurrences by state, sex, race_ethnicity_category, and had_heart_attack
agg_data <- gf %>%
  group_by(state, sex, race_ethnicity_category, had_heart_attack) %>%
  summarise(count = n(), .groups = 'drop')

# Create the Plotly bar graph
p <- agg_data %>%
  plot_ly(x = ~state, y = ~count, color = ~race_ethnicity_category, 
          type = 'bar', 
          hoverinfo = 'text', 
          text = ~paste('State: ', state, '<br>Heart Attack: ', had_heart_attack, '<br>Count: ', count), 
          split = ~had_heart_attack) %>% # Split by 'had_heart_attack' to separate bars for Yes/No
  layout(title = "Number of Heart Attacks per State by Sex and Ethnicity",
         xaxis = list(title = "State"),
         yaxis = list(title = "Number of Heart Attacks"),
         barmode = 'dodge', # Bars side-by-side for Yes and No
         facet = list(rows = 1, columns = 2, 
                      categoryorder = 'total ascending'),
         legend = list(title = list(text = "Heart Attack Status"), 
                       x = 1, y = 1))  # Position and title for the legend

# Show plot
p
## Warning: 'layout' objects don't have these attributes: 'facet'
## Valid attributes include:
## '_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'