This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```# Load necessary libraries library(sf) library(shiny) library(shinydashboard) library(ggplot2) library(plotly) library(leaflet) library(tidyverse) library(rsconnect) geojson_data <- st_read(“countries.geojson”) afford_data <- read_csv(“affordability-cigarettes.csv”) afford_data <- afford_data %>% filter(Year == ‘2012’) merged_data <- right_join(geojson_data, afford_data, by = c(“ADMIN” = “Country”)) # Define UI ui <- dashboardPage( dashboardHeader(title = “Data Visualizations”), dashboardSidebar( sidebarMenu( menuItem(“Cigarette Statistics”, tabName = “cigarette_stats”, icon = icon(“chart-bar”)), menuItem(“Death Rate from Smoking”, tabName = “death_rate”, icon = icon(“chart-line”)), menuItem(“Age Analysis”, tabName = “age_analysis”, icon = icon(“chart-pie”)) ) ), dashboardBody( tabItems( # First Tab: Cigarette Statistics # First Tab: Cigarette Statistics tabItem( tabName = “cigarette_stats”, fluidRow( column(width=12, leafletOutput(“choroplethMap”)) ), fluidRow( box( title = “Affordability of Cigarettes (2012)”, status = “primary”, solidHeader = TRUE, plotlyOutput(“percentage_chart”), helpText( “Cigarette affordability varies globally. Low- and middle-income countries have cheaper cigarettes due to lower incomes, lower taxes, and weaker regulations. Russia is one of the country which offers the most affordable cigarettes (0.93% of average income), Australia has the highest cigarette prices (2% of average income), with the USA also relatively expensive. Affordability impacts smoking rates; cheaper cigarettes lead to higher consumption. Governments should raise taxes and restrict cheap sales to combat this public health issue.”) ),
box(
title = "Daily Cigarette Consumption (2012)",
status = "primary",
solidHeader = TRUE,
plotlyOutput("daily_consumption_chart"),
helpText("Cigarette consumption worldwide reveals stark global disparities. Predominantly, low- and middle-income nations exhibit higher smoking rates, linked to lower socioeconomic status and limited healthcare access. This trend stems from both the affordability of cigarettes and targeted marketing by tobacco corporations. Additionally, regional variations in consumption suggest influences from cultural norms, governmental policies, and healthcare accessibility. The alarming prevalence of smoking in these countries necessitates urgent public health action. Implementing strategies like raising tobacco taxes, prohibiting advertising, and offering cessation programs are vital steps toward reducing smoking-related mortality rates, addressing a pressing global health challenge.")
)
)
),
# Second Tab: Death Rate from Smoking
tabItem(
tabName = "death_rate",
fluidRow(
box(
title = "Death Rate from Smoking per 100,000 people, 2012",
status = "primary",
solidHeader = TRUE,
plotlyOutput("bar_plot"),
helpText("The global impact of smoking-related diseases reveals a glaring inequality, with low- and middle-income countries, such as India, Russia, and the USA, shouldering the heaviest burden. These nations, alongside China and Indonesia, constitute over 70% of worldwide smoking-related fatalities. In stark contrast, affluent countries like Australia experience a lower toll. This gap stems from a blend of factors, including the affordability of cigarettes and easier access of tobacco conglomerates. Confronting this public health challenge is paramount. Governments should explore avenues like increased tobacco taxes, advertising prohibitions, and the facilitation of smoking cessation programs. Beyond public health, smoking inflicts a significant economic cost, amounting to trillions in lost productivity and healthcare expenses annually, underscoring the shared concern of governments and businesses in curbing smoking rates.")
),
box(
title = "Death Rate from Passive Smoking per 100,000 people, 2012",
status = "primary",
solidHeader = TRUE,
plotlyOutput("scatter_plot"),
helpText("The global map of secondhand smoke-related deaths underscores a global imbalance. Individuals in low- and middle-income nations face a higher likelihood of exposure, leading to increased fatalities. This is attributed to several factors, including elevated smoking prevalence in these regions, limited implementation of smoke-free policies, and higher poverty rates, which amplify exposure risks. The substantial mortality rates in these countries demand urgent attention from governments. They must enact stringent smoke-free laws, offer accessible smoking cessation initiatives, and intensify public awareness campaigns to combat the hazards of secondhand smoke.")
)
)
),
# Third Tab: Age Analysis
tabItem(
tabName = "age_analysis",
fluidRow(width=12,
title = "Age Analysis",
status = "primary",
selectInput("age_group", label = "Select Age Group",
choices = c("15-49 years", "50-69 years", "70+ years"),
selected = "15-49 years")),
fluidRow(width=6,
box(
plotlyOutput("bar_plot_overall"),
helpText("The global map depicting smoking-related deaths across age groups underscores the profound impact of tobacco-related diseases. Over a million preventable deaths annually, smoking stands as the leading cause of mortality worldwide. While the 70+ age group bears the highest percentage of these fatalities, it's crucial to recognize that smoking claims lives across all age brackets. Regional disparities in smoking-related deaths can be attributed to various factors including historical smoking prevalence, differing tobacco regulations, and varying healthcare accessibility. It's worth noting that while percentages may vary, countries with larger populations may still witness higher total death tolls from smoking.")
),
box(
plotlyOutput("bar_plot_smoke"),
helpText("The age-specific graph of secondhand smoke-related deaths highlights the cumulative impact of prolonged exposure. Those subjected to secondhand smoke over their lifetimes face elevated risks of diseases like heart conditions, strokes, and lung cancer. The degree of exposure directly correlates with the heightened risk of these ailments. It can be seen that these deaths are more common in countries which are having poor air conditions. The countries with better air quality have fewer deaths due to secondhand smoke compared to poor air quality ones.") )
)
)
)
) )
server <- function(input, output) { # Percentage Comparison data data_percentage <- data.frame( Country = c( “India”, “Russia”, “Australia”, “USA”, “Morocco”), Percentage = c( 12.47, 0.93, 2.06, 1.18, 6.81) )
# Daily Cigarette Consumption data data_daily_consumption <- data.frame( Country = c( “India”, “Russia”, “Australia”, “USA”, “Morocco”), Consumption = c(8.2, 24.4, 20.1, 22.5, 14) )
output\(choroplethMap <- renderLeaflet({ # Create the Leaflet Map m <- leaflet(merged_data) %>% addProviderTiles(providers\)OpenStreetMap) %>% setView(lng = -98.5795, lat = 39.8283, zoom = 4)
# Define Color Palette (for continuous scale)
pal <- colorNumeric(
palette = "YlOrBr",
domain = merged_data$Affordability
)
# Create Labels
labels <- sprintf(
"<strong>%s</strong><br/>%s",
merged_data$ADMIN, merged_data$Affordability
) %>% lapply(htmltools::HTML)
# Add Polygons with Fill Color Based on Affordability
m <- m %>% addPolygons(
fillColor = ~pal(Affordability),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 5,
color = "lightblue",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto"))
# Add a Color Legend (for continuous scale)
m <- m %>% addLegend(pal = pal, values = ~Affordability, opacity = 0.7,
title = "Affordability", position = "bottomright")
# Display the Map
m
})
# Render plots for the Cigarette Statistics tab output$percentage_chart <- renderPlotly({ f <- ggplot(data_percentage, aes(x = Country, y = Percentage, fill = Country)) + geom_bar(stat = “identity”, color = “white”) + geom_text(aes(label = format(Percentage, big.mark = “,”)), vjust = -0.5, size = 3, position = position_dodge(width = 0.9), fontface = “bold”) + labs(title = “Affordability based on GDP Share for 100 packs”, x = “Country”, y = “Percentage (%)”) + ylim(0, 30) + scale_fill_brewer(palette = “Set2”)+ # Soft light and visually appealing colors theme_minimal() ggplotly (f) })
output$daily_consumption_chart <- renderPlotly({ e <- ggplot(data_daily_consumption, aes(x = Country, y = Consumption, fill = Country)) + geom_bar(stat = “identity”, color = “white”) + geom_text(aes(label = format(Consumption, big.mark = “,”)), vjust = -0.5, size = 3, position = position_dodge(width = 0.9), fontface = “bold”) + labs(title = “Daily Cigarette Consumption per Smoker (2012)”, x = “Country”, y = “Consumption”) + ylim(0, 25) + scale_fill_brewer(palette = “Set2”) + # Soft light and visually appealing colors theme_minimal() ggplotly(e) })
# Death rate from smoking data countries_death_rate <- c(“Australia”, “India”, “Morocco”, “Russia”, “USA”) values_death_rate <- c(50.3, 110.4, 70.5, 145.9, 99.7) data_death_rate <- data.frame(Country = countries_death_rate, Value = values_death_rate)
# Scatter Plot data countries_scatter <- c(“Australia”, “India”, “Morocco”, “Russia”, “USA”) values_scatter <- c(1443, 198740, 5628, 39475, 31344) data_scatter <- data.frame(Country = countries_scatter, Value = values_scatter)
# Render plots for the Death Rate from Smoking tab output$bar_plot <- renderPlotly({ r <- ggplot(data_death_rate, aes(x = Country, y = Value, fill = Country)) + geom_bar(stat = “identity”, color = “white”, position = “dodge”) + geom_text(aes(label = format(Value, big.mark = “,”)), vjust = -0.5, size = 3, position = position_dodge(width = 0.9), fontface = “bold”) + labs(title = “Deaths because of smoking per 100,000 people”, x = “Country”, y = “Value”) + ylim(0, 200) + scale_fill_brewer(palette = “Set2”) + theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0.5))+ theme_minimal() ggplotly() })
output$scatter_plot <- renderPlotly({ s <- ggplot(data_scatter, aes(x = Country, y = Value, color = Country)) + geom_point(size = 5, shape = 16, alpha = 0.8) + geom_text(aes(label = Value), vjust = -1.0, size = 3, fontface = “bold”, color = “black”) + labs(title = “Annual number of deaths due to Passive smoking”, x = “Country”, y = “Value”, color = “Country”) + ylim(0, max(values_scatter) + 10000) + theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0.5)) + theme_minimal() + scale_color_discrete(name = “Country”) ggplotly(s) })
# Define data for the Age Analysis countries_age <- c(“Australia”, “India”, “Morocco”, “Russia”, “USA”) deaths_15to49 <- c(786, 6140, 10804, 97041, 407539, 392527) deaths_50to69 <- c(2178, 9019, 6361) deaths_70plus <- c(33459, 157416, 121900, 19773, 176311, 285102) deaths_15to49_smoke <- c(102, 453, 884, 20614, 70672, 84414) deaths_50to69_smoke <- c(715, 2298, 2360) deaths_70plus_smoke <- c(3921, 15943, 19106, 2513, 12674, 16065)
data_age <- data.frame( Country = rep(countries_age, each = 3), AgeGroup = rep(c(“15-49 years”, “50-69 years”, “70+ years”), times = 5), Deaths = c(deaths_15to49, deaths_50to69, deaths_70plus), DeathsSmoke = c(deaths_15to49_smoke, deaths_50to69_smoke, deaths_70plus_smoke) )
# Define a reactive expression to filter data based on selected age group filtered_data <- reactive({ age_group <- input\(age_group filtered <- data_age[data_age\)AgeGroup == age_group, ] return(filtered) })
# Render plots for the Age Analysis tab #output$bar_plot_overall <- renderPlot({ # filtered <- filtered_data()
# Define y-axis limits based on age group # y_limits <- if (input\(age_group == "50-69 years") c(0, 420000) # else if (input\)age_group == “70+ years”) c(0, 400000) # else c(0, max(filtered\(Deaths)) # # ggplot(filtered, aes(x = Country, y = Deaths, fill = Country)) + # geom_bar(stat = "identity") + # geom_text(aes(label = format(Deaths, big.mark = ",")), vjust = -0.5, size = 4, position = position_dodge(width = 0.9), fontface = "bold") + # labs(title = paste("Death Rate by Age Group (Overall -", input\)age_group, “)”, sep = ““), # x =”Country”, # y = “Number of Deaths”) + # scale_fill_brewer(palette = “Set3”) + # scale_y_continuous(limits = y_limits, labels = scales::comma_format(scale = 1e-3, accuracy = 1, suffix = “K”)) + # theme(axis.title.x = element_text(size = 14, face = “bold”), # axis.title.y = element_text(size = 14, face = “bold”), # }) output$bar_plot_overall <- renderPlotly({ filtered <- filtered_data()
# Define y-axis limits based on age group
y_limits <- if (input$age_group == "50-69 years") c(0, 420000)
else if (input$age_group == "70+ years") c(0, 400000)
else c(0, max(filtered$Deaths))
p <- ggplot(filtered, aes(x = Country, y = Deaths, fill = Country)) +
geom_bar(stat = "identity") +
geom_text(aes(label = format(Deaths, big.mark = ",")), vjust = -0.5, size = 3, position = position_dodge(width = 0.9), fontface = "bold") +
labs(title = paste("Death Rate by Age Group (Overall -", input$age_group, ")", sep = ""),
x = "Country",
y = "Number of Deaths") +
scale_fill_brewer(palette = "Set3") +
scale_y_continuous(limits = y_limits, labels = scales::comma_format(scale = 1e-3, accuracy = 1, suffix = "K")) +
theme(
axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1), # Adjust angle and alignment
axis.title.x = element_blank() # Hide x-axis title
) +
theme_minimal()
ggplotly(p)
})
output$bar_plot_smoke <- renderPlotly({ filtered <- filtered_data()
q <- ggplot(filtered, aes(x = Country, y = DeathsSmoke, fill = Country)) +
geom_bar(stat = "identity") +
geom_text(aes(label = format(DeathsSmoke, big.mark = ",")), vjust = -0.5, size = 3, position = position_dodge(width = 0.9), fontface = "bold") +
labs(title = paste("Death Rate by Age Group for Passive Smoke (", input$age_group, ")", sep = ""),
x = "Country",
y = "Number of Deaths") +
scale_fill_brewer(palette = "Set3") +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0.5)) +
theme_minimal()
ggplotly(q)
}) }
shinyApp(ui, server)
```
You can also embed plots, for example:
Note that the echo = FALSE parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.