Purpose of the project

With a background in commercial music and as a graduate student pursuing a master’s degree in Media and Communication, I have developed an interest in the intersection of music, technology, and media. As artificial intelligence (AI) becomes increasingly integrated into the music industry, conversations surrounding its implications have become particularly relevant to both my professional and academic interests.

This project was initially developed as a preliminary exploration of my thesis research, which examines how artificial intelligence is framed in media coverage of the music industry. My original approach was to conduct a sentiment analysis comparing AI-related headlines published by Billboard and Rolling Stone to determine whether either publication demonstrated a more positive or negative sentiment toward AI.

However, after reviewing the initial results and receiving feedback, I realized that sentiment alone did not necessarily capture the complexities of these conversations. Rather than focusing on whether AI was represented positively or negatively, I became more interested in understanding which aspects of AI were receiving attention and how these conversations differed between publications.

This led me to shift the focus of the project from sentiment analysis to media framing and expand its analytical scope to include developments across the creative industries.

The resulting project developed R code aimed at examining the volume of AI-related media coverage over time, identifying recurring media frames, comparing framing across publications, and exploring changes in coverage surrounding significant industry developments.

Data source

The data used in this project were retrieved from MediaCloud, an open-source platform that collects and indexes online news coverage, allowing researchers to examine media content across different publications and periods of time.

I chose Billboard and Rolling Stone because of their established presence within the music and entertainment industries. While Billboard is more industry-oriented, Rolling Stone covers music alongside broader conversations surrounding entertainment, culture, and society. I was interested in exploring whether these differences were also reflected in their coverage of artificial intelligence.

The original dataset was retrieved through MediaCloud’s Application Programming Interface (API) using R. Since the initial project focused specifically on the music industry, I used the following search query:

("artificial intelligence" OR "generative AI" OR "AI-generated") AND music

The search covered January 1, 2025, through June 30, 2026, and resulted in a dataset of 522 English-language headlines, of which 406 were published by Billboard and 116 by Rolling Stone. The dataset included unique story identifiers, publication names, publication dates, headlines, and article URLs, among other variables.

Preparing the dataset for analysis

When I shifted the focus of the project from sentiment analysis to media framing, I recognized that not all headlines retrieved through the original search were necessarily relevant to the revised research objectives. At the same time, some of the headlines addressed developments involving AI beyond the music industry, which presented an opportunity to expand the analytical scope of the project.

Using R, I exported the headlines into a CSV file and developed a classification system with the assistance of ChatGPT. Each headline was evaluated for its relevance to the project, the creative sector it represented, and the presence of six media frames.

The creative sector classifications included music, film and television, digital media, publishing, visual arts, cross-industry developments, and other creative industries.

The six media frames used in the analysis were:

  • Legal and Copyright: Conversations surrounding intellectual property, copyright infringement, licensing, and legal disputes.

  • Economic Impact: Conversations surrounding revenue, employment, compensation, and the financial implications of AI.

  • Creative Innovation: The use of AI to introduce new creative possibilities, tools, and processes.

  • Artistic Authenticity: Conversations surrounding human creativity, artistic identity, originality, and the authenticity of creative works.

  • Ethics and Governance: Concerns surrounding the responsible use of AI, transparency, consent, regulation, and accountability.

  • Industry Adoption: The integration of AI into industry practices, business operations, platforms, and partnerships.

Each media frame was treated as a binary variable, with a value of 1 indicating the presence of a frame and 0 indicating its absence. Since a headline could address multiple aspects of AI simultaneously, headlines were not limited to a single media frame.

ChatGPT assisted with the initial relevance screening and classification of the headlines. Of the 522 headlines, 56 were flagged for further review. I manually evaluated these headlines to determine whether they were relevant to the project, ultimately retaining 43 and excluding 13 of the flagged headlines.

Following the screening and review process, 280 headlines were retained for the final analysis, consisting of 226 headlines from Billboard and 54 from Rolling Stone.

Accessing the data

The current script requires two data files to be stored in the same R project folder:

  • music_ai_headlines_2025_2026.rds — the original dataset retrieved from MediaCloud.

  • ai_creative_industries_coded_final.csv — the final researcher-reviewed coding dataset containing headline relevance, creative sector classifications, and media frame classifications.

By working with these previously saved files, the analysis can be reproduced without making additional requests to the MediaCloud API or requiring an API key.

It is important to acknowledge that although the analytical scope of the project expanded to include the creative industries, the original search remained music-oriented. As a result, the dataset primarily reflects music-related coverage and should not be interpreted as a comprehensive representation of AI-related media coverage across all creative industries.

Output

The script produces a series of visualizations examining different aspects of AI-related media coverage in the creative industries. Of the visualizations developed throughout the project, I ultimately chose to feature five interactive visualizations in the final presentation.

The first visualization examines the monthly volume of AI-related headlines published by Billboard and Rolling Stone between January 2025 and June 2026. I chose a line chart because I wanted to identify periods of heightened media coverage and observe how coverage fluctuated over time. Three numbered markers were also incorporated into the visualization to identify significant industry developments that would be explored further in the project.

The second visualization compares the representation of different creative sectors within each publication’s AI-related coverage. Given the considerable difference in the number of headlines published by Billboard and Rolling Stone, I chose to represent the data using percentages rather than raw counts. This allows viewers to compare the relative attention each publication dedicated to different creative sectors.

The third visualization examines the prevalence of the six media frames across the two publications. Similar to the previous visualization, percentages are used to account for differences in coverage volume. Rather than determining whether a publication’s coverage of AI was predominantly positive or negative, this visualization allows viewers to identify which aspects of AI received greater emphasis within each publication.

The fourth visualization examines how the volume of headlines containing each media frame fluctuated throughout the study period. I chose to separate the six media frames into individual panels rather than display them within a single line chart. This makes it easier for viewers to compare the two publications while also identifying periods in which particular media frames received greater attention.

The fifth and final visualization is an interactive dashboard examining changes in media framing surrounding three significant industry developments:

The dashboard compares media framing during the 30 days before and after each event, excluding the day of the event itself. Viewers can use a dropdown menu to select an event and explore changes in either frame volume, represented by the number of headlines containing a particular frame, or frame prevalence, represented by the percentage of headlines containing that frame.

Initially, I developed six separate visualizations for this portion of the project, with two visualizations for each event. However, I felt that displaying all six charts would make the final presentation unnecessarily lengthy and repetitive. I ultimately decided to consolidate them into a single interactive dashboard that would allow viewers to navigate between events and metrics. The original visualizations remain in the script but are not featured in the final presentation.

Throughout the project, I used both the ggplot2 and plotly packages to develop the visualizations. Several of the charts were initially developed using ggplot2 and later converted into interactive graphics using plotly. The annotated timeline and final event analysis dashboard were developed directly using plotly.

Since the final project was intended for online viewing, I wanted to take advantage of the interactive capabilities that plotly offers. Viewers can hover over individual data points and bars to access additional information, interact with chart legends, and explore different aspects of the data at their own pace.

I also established a consistent visual identity across the graphics by assigning distinct colors to each publication and maintaining consistent typography and formatting. My intention was to create a cohesive presentation that would be accessible to both academic audiences and creative industry professionals.

My role in developing the script

ChatGPT produced the script’s R Code, but as the project’s designer, I:

Defined the research problem. I wanted to develop a project that would be relevant to both my academic research and my professional interests in the music industry. Since my thesis examines how artificial intelligence is framed in media coverage of the music industry, I saw this project as an opportunity to conduct a preliminary exploration of the topic while developing my skills in data analysis using R.

Identified the publications for comparison. I selected Billboard and Rolling Stone because of their established presence within the music and entertainment industries. I was particularly interested in whether their differences in editorial focus would be reflected in how they covered artificial intelligence.

Established the initial search parameters. I determined the period of coverage, the publications to be examined, and the focus of the original search. With the assistance of ChatGPT, I developed the search query and R code necessary to retrieve the data through the MediaCloud API.

Reevaluated the original analytical approach. The project initially focused on sentiment analysis. However, after examining the preliminary results and receiving feedback from Dr. Blake, I recognized that categorizing headlines according to positive or negative sentiment did not necessarily provide the insight I was looking for. I decided to shift the focus toward media framing to better understand which aspects of artificial intelligence were receiving attention within each publication.

Expanded the analytical scope of the project. While reviewing the original dataset, I recognized that some headlines addressed relevant developments involving artificial intelligence beyond the music industry. Rather than immediately excluding these headlines, I decided to expand the scope of the analysis to include other creative industries while acknowledging the limitations of the original music-oriented search.

Developed a classification strategy. Working with ChatGPT, I established criteria for determining headline relevance, identifying creative sectors, and classifying media frames. I wanted the classifications to reflect the different conversations taking place surrounding artificial intelligence, rather than reducing them to a single positive or negative interpretation. I also decided that headlines should be able to contain multiple media frames, given that conversations surrounding AI often involve overlapping issues.

Reviewed headline classifications. Although ChatGPT assisted with the initial screening and classification of the headlines, I manually reviewed the 56 headlines identified as requiring further evaluation. This involved examining whether each headline was sufficiently relevant to artificial intelligence and the creative industries to be included in the analysis. Of these headlines, I retained 43 and excluded 13.

Recognized the importance of proportional comparisons. After examining the distribution of headlines across the two publications, I recognized that comparing raw counts alone could be misleading. Billboard accounted for a considerably larger portion of the dataset than Rolling Stone. I therefore incorporated percentages into the analysis to provide a more meaningful comparison of the relative attention each publication dedicated to particular creative sectors and media frames.

Incorporated a temporal dimension into the analysis. Following feedback from Dr. Blake, I expanded the analysis beyond the overall prevalence of media frames to examine how their volume fluctuated over time. This provided an opportunity to identify periods of heightened coverage and explore the industry developments taking place during those periods.

Established the approach to examining significant industry developments. With the assistance of ChatGPT, I examined headlines published during periods of heightened coverage and identified several significant AI-related developments. Three events were ultimately selected for further analysis. The 30-day periods before and after each event provided a consistent timeframe for examining changes in media framing.

Recognized the value of examining both frame volume and prevalence. While developing the event analysis, I wanted to distinguish between changes in the number of headlines containing a particular frame and changes in the proportion of coverage containing that frame. An increase in the volume of a particular media frame does not necessarily mean that the frame received greater relative emphasis. Incorporating both measures allowed for a more comprehensive examination of changes in coverage.

Refined the interactive dashboard. The initial approach to presenting the event analysis involved six separate visualizations. After reviewing these graphics, I felt that a single interactive dashboard would provide a more effective viewing experience. Working with ChatGPT, I refined the dashboard’s layout, dropdown menu, publication panels, labels, and hover information through several iterations.

Established a consistent visual identity. I wanted the visualizations to feel like components of a single project rather than a collection of unrelated graphics. I worked with ChatGPT to establish a consistent color palette, typography, and formatting. Particular attention was given to maintaining distinct publication colors and ensuring that the visualizations remained readable and accessible.

Tested and refined the script throughout its development. Rather than generating the entire script at once, I worked through the project in individual steps. I ran the code in RStudio, examined the resulting data and visualizations, identified errors or inconsistencies, and communicated the necessary revisions to ChatGPT. This allowed me to better understand what each portion of the script accomplished before proceeding to the next stage of the analysis.

Developed the final presentation. Once the analysis was complete, I determined how the findings should be organized and communicated through an R Markdown document. Given the intended audience of academic researchers and creative industry professionals, I wanted the presentation to be informative without requiring viewers to have an extensive understanding of R or data analysis. I organized the visualizations around questions that guided viewers through the findings and included key observations to provide additional context.

Things I learned while developing the project

One of the most significant things I learned throughout this project was the importance of being willing to reconsider my approach to a research question. I initially believed that sentiment analysis would provide meaningful insight into how artificial intelligence was being represented in the music industry. However, after examining the preliminary results, I realized that determining whether a headline was positive or negative did not necessarily tell me much about the conversation taking place. Shifting the focus toward media framing allowed me to explore these conversations in greater depth. This was particularly valuable to me given the relevance of this project to my thesis research.

I also developed a greater appreciation for how decisions made during the data collection process can influence the direction and limitations of a research project. Although I was able to expand the analytical scope to include other creative industries, the original search query remained music-oriented. This reinforced the importance of establishing search parameters that align with the research objectives and considering how those parameters influence the conclusions that can reasonably be drawn from the data.

Another thing I learned was the importance of providing context when comparing data. Given the difference in coverage volume between Billboard and Rolling Stone, comparing raw headline counts alone would not necessarily provide a meaningful representation of how each publication framed AI. Incorporating percentages allowed me to distinguish between the amount of coverage and the relative emphasis placed on particular topics. This distinction became especially apparent when examining changes in media framing before and after significant industry developments.

The project also expanded my understanding of data visualization. While developing the graphics, I found myself considering not only what information I wanted to communicate but also how I wanted viewers to engage with it. The interactive dashboard was particularly rewarding to develop because it allowed me to consolidate a considerable amount of information into a single visualization without sacrificing the ability to explore the data in greater detail. I learned that interactivity is most valuable when it serves a purpose rather than simply making a visualization more visually appealing.

Given the subject matter of this project, I also found it interesting that I was using artificial intelligence to examine media coverage of artificial intelligence. While ChatGPT was useful in generating code, assisting with headline classifications, and suggesting analytical approaches, the process reinforced the importance of human judgment. I still needed to evaluate whether its suggestions aligned with my research objectives, review uncertain

How the Script Works

The following is a summary, developed with the assistance of ChatGPT and reviewed by me, of what each step in the R script accomplishes.

  1. Loads the R packages required for data processing, text analysis, date manipulation, and interactive visualizations. Imports the previously retrieved MediaCloud dataset from an RDS file (Step 1).

  2. Establishes a consistent visualization theme, including publication-specific colors, before-and-after comparison colors, typography, and chart formatting (Step 1A).

  3. Verifies the original dataset by examining the number of headlines, publication distribution, publication date range, language, duplicate story identifiers, and missing values (Step 2).

  4. Extracts the story identifiers, publication dates, publication names, and headlines from the original dataset and exports them into a CSV file to support the development of the media framing classification system (Step 3).

  5. Conducts a preliminary relevance screening by identifying headlines containing AI-related keywords, terminology, and company names. Creates a variable indicating whether each headline contains one or more of these terms (Step 4).

  6. Prepares the preliminary screening results for further inspection and exports the headlines and their AI indicators into a CSV file (Step 5).

  7. Creates a coding sheet containing the original headline information and additional variables for relevance, creative sector classifications, the six media frames, and classification notes. Exports the coding sheet for AI-assisted classification and researcher review (Step 6).

  8. Imports the completed, researcher-reviewed coding dataset and examines the distribution of included and excluded headlines across publications and creative sectors (Step 7).

  9. Creates the final analytical dataset by retaining only headlines classified as relevant to the project. Verifies the number of included headlines, their distribution across publications, and whether any media frame classifications are missing. Saves the resulting dataset as an RDS file (Step 8).

  10. Calculates the monthly volume of AI-related headlines published by Billboard and Rolling Stone throughout the study period. Accounts for months in which a publication had no relevant headlines by assigning a value of zero (Step 9).

  11. Creates a line chart comparing monthly AI-related coverage volume across the two publications (Step 9A).

  12. Identifies the five months with the highest volume of AI-related coverage for each publication (Step 9B).

  13. Calculates the number and percentage of headlines associated with each creative sector within each publication (Step 10).

  14. Creates a comparative horizontal bar chart visualizing the percentage of headlines associated with each creative sector (Step 10A).

  15. Restructures the media frame classifications into a format suitable for analysis. Calculates the volume and prevalence of each of the six media frames across both publications (Step 11).

  16. Validates that all media frame variables contain binary values of either 0 or 1. Examines the number of media frames assigned to each headline, including headlines that do not contain any of the six identified frames (Step 11A).

  17. Creates a comparative horizontal bar chart visualizing the prevalence of each media frame across the two publications (Step 11B).

  18. Calculates the monthly volume of headlines containing each media frame for both publications throughout the study period (Step 12).

  19. Creates a series of six line charts, organized into individual panels, visualizing how the volume of each media frame fluctuated over time (Step 12A).

  20. Identifies the three months with the highest volume of headlines containing each media frame for each publication (Step 12B).

  21. Extracts headlines published during selected periods of heightened media coverage and exports them into a CSV file for further examination and identification of significant industry developments (Step 13).

  22. Creates a dataset containing seven significant AI-related industry developments, including their dates, names, creative sectors, and source URLs. Identifies three of these events for further analysis (Step 13A).

  23. Creates an interactive version of the monthly coverage line chart using plotly. Incorporates numbered markers and vertical reference lines identifying the dates of the three selected industry developments (Step 13B).

  24. Examines media framing during the 30 days before and after each selected event, excluding the day of the event itself. Calculates the volume and prevalence of each media frame for both publications within each period (Step 14).

  25. Calculates changes in media frame volume and prevalence between the before-and-after periods for each event. Exports the results into a CSV file for further examination (Step 14A).

  26. Establishes consistent design elements for the event analysis visualizations, including media frame ordering, display labels, comparison colors, and axis scaling (Step 15).

  27. Develops a reusable visualization function that creates comparative horizontal bar charts for individual events. The function allows the charts to display either media frame volume or prevalence and incorporates publication-specific panels, sample sizes, and interactive hover information (Step 15A).

  28. Generates six individual event analysis visualizations, consisting of three frame prevalence charts and three frame volume charts (Step 15B).

  29. Consolidates the individual event comparisons into a single interactive dashboard. Develops a dropdown menu that allows viewers to navigate between the three selected events and two analytical measures while maintaining a consistent visualization layout (Step 15C).

  30. Identifies the three largest changes in media frame prevalence for each publication surrounding each selected event, based on the absolute magnitude of the percentage-point changes (Step 16).

In short, the script takes a previously retrieved MediaCloud dataset and its associated researcher-reviewed coding file, prepares the data for analysis, examines differences in AI-related coverage across two publications, and produces a series of interactive visualizations. The resulting analysis allows viewers to explore coverage volume, creative sector representation, media frame prevalence, changes in framing over time, and changes in coverage surrounding significant industry developments.

The Complete Script

Below is the complete R script developed for this project. Before executing the script, users will need to have the following two data files stored in the same R project folder as the script:

The first file contains the original dataset retrieved from MediaCloud, while the second contains the completed coding dataset following AI-assisted classification and researcher review.

Although the original data collection process required a MediaCloud API key, no API key or additional credentials are required to execute the current analysis using the previously saved datasets.

The script retains several intermediate stages of the research process, including preliminary headline screening, coding sheet preparation, data validation, and earlier versions of the visualizations. These sections were retained to document the development of the project and provide flexibility for future analysis.

The complete script is organized into numbered steps corresponding to the explanations provided in the previous section

# ==================================================
# FINAL PROJECT
#
# Framing Artificial Intelligence in the Creative
# Industries: A Comparative Analysis of Billboard
# and Rolling Stone
#
# Search Period:
# January 1, 2025 - June 30, 2026
#
# Research Objectives:
# 1. Examine AI-related coverage volume over time.
# 2. Identify recurring media frames in AI coverage.
# 3. Compare framing across publications.
# 4. Examine changes in framing before and after
#    significant AI-related creative industry events.
#
# Note:
# OG dataset was retrieved using a
# music-oriented MediaCloud search query.
# This project expands the analytical scope to
# include relevant developments across the
# creative industries.
# ==================================================

# ==================================================
# Step 1: Load Packages and Existing Dataset
# ==================================================

library(tidyverse)
library(lubridate)
library(tidytext)
library(plotly)

music_ai_data <- readRDS(
  "music_ai_headlines_2025_2026.rds"
)
# ==================================================
# Step 1A: Project Visualization Theme
# ==================================================

publication_colors <- c(
  "Billboard" = "#B4534B",
  "Rolling Stone" = "#287C91"
)

period_colors <- c(
  "Before" = "#94A3B8",
  "After" = "#0F766E"
)

project_theme <- theme_minimal(
  base_size = 12,
  base_family = "Arial"
) +
  theme(
    plot.title = element_text(
      face = "bold",
      size = 16,
      color = "#334155"
    ),
    plot.subtitle = element_text(
      size = 11,
      color = "#64748B"
    ),
    axis.text = element_text(
      color = "#334155"
    ),
    axis.title = element_text(
      color = "#334155"
    ),
    panel.grid.major = element_line(
      color = "#E2E8F0"
    ),
    panel.grid.minor = element_blank(),
    legend.position = "bottom",
    strip.text = element_text(
      face = "bold",
      color = "#334155"
    ),
    plot.background = element_rect(
      fill = "white",
      color = NA
    )
  )
# ==================================================
# Step 2: Verify Existing Dataset
# ==================================================
nrow(music_ai_data)

music_ai_data |>
  count(media_name)

range(music_ai_data$publish_date, na.rm = TRUE)

music_ai_data |>
  count(language)

nrow(music_ai_data) - n_distinct(music_ai_data$id)

colSums(is.na(music_ai_data))

# ==================================================
# Step 3: Export Headlines for Frame Development
# ==================================================

headlines_for_framing <- music_ai_data |>
  select(
    id,
    publish_date,
    media_name,
    title
  ) |>
  arrange(publish_date)

#View(headlines_for_framing)

write_csv(
  headlines_for_framing,
  "music_ai_headlines_for_framing.csv"
)
# ==================================================
# Step 4: Preliminary Headline Relevance Screening
# ==================================================

music_ai_screened <- music_ai_data |>
  mutate(
    publish_date = as.Date(publish_date),
    publication = recode(
      media_name,
      "billboard.com" = "Billboard",
      "rollingstone.com" = "Rolling Stone"
    )
  )

ai_pattern <- paste0(
  "\\b(",
  "AI|A\\.I\\.?|artificial intelligence|",
  "GenAI|Gen-AI|Suno|Udio|",
  "deepfakes?|Anthropic|ElevenLabs|",
  "voice cloning|machine learning",
  ")\\b"
)

music_ai_screened <- music_ai_screened |>
  mutate(
    ai_indicator = str_detect(
      title,
      regex(ai_pattern, ignore_case = TRUE)
    )
  )

music_ai_screened |>
  count(publication, ai_indicator)
# ==================================================
# Step 5: Review Headline Relevance
# ==================================================


music_ai_screened |>
  filter(ai_indicator == TRUE) |>
  select(publication, publish_date, title) |>
  View()


music_ai_screened |>
  filter(ai_indicator == FALSE) |>
  select(publication, publish_date, title) |>
  View()


music_ai_screened |>
  select(
    id,
    publish_date,
    publication,
    title,
    ai_indicator
  ) |>
  write_csv("music_ai_screened_headlines.csv")
# ==================================================
# Step 6: Create Creative Industries Coding Sheet
# ==================================================

creative_industry_coding <- music_ai_screened |>
  select(
    id,
    publish_date,
    publication,
    title,
    ai_indicator,
    url
  ) |>
  mutate(
    relevance = NA_character_,
    creative_sector = NA_character_,
    legal_copyright = NA_integer_,
    economic_impact = NA_integer_,
    creative_innovation = NA_integer_,
    artistic_authenticity = NA_integer_,
    ethics_governance = NA_integer_,
    industry_adoption = NA_integer_,
    notes = NA_character_
  ) |>
  arrange(
    desc(ai_indicator),
    publication,
    publish_date
  )


write_csv(
  creative_industry_coding,
  "ai_creative_industries_coding.csv",
  na = ""
)


#View(creative_industry_coding)

# Confirm dimensions

dim(creative_industry_coding)
# ==================================================
# Step 7: Import Researcher-Reviewed Coding Results
# ==================================================

coded_headlines <- read_csv(
  "ai_creative_industries_coded_final.csv",
  col_types = cols(id = col_character()),
  show_col_types = FALSE
)
dim(coded_headlines)

coded_headlines |>
  count(relevance)

coded_headlines |>
  count(publication, relevance)

coded_headlines |>
  filter(relevance == "include") |>
  count(creative_sector, sort = TRUE)
# ==================================================
# Step 8: Create Final Analytical Dataset
# ==================================================

creative_ai_data <- coded_headlines |>
  filter(relevance == "include") |>
  mutate(
    publish_date = as.Date(publish_date)
  )

nrow(creative_ai_data)

creative_ai_data |>
  count(publication)

creative_ai_data |>
  summarise(
    across(
      legal_copyright:industry_adoption,
      ~ sum(is.na(.x))
    )
  )

saveRDS(
  creative_ai_data,
  "ai_creative_industries_final.rds"
)

# ==================================================
# Step 9: Analyze Monthly Coverage Volume
# ==================================================

monthly_coverage <- creative_ai_data |>
  mutate(
    month = floor_date(publish_date, "month")
  ) |>
  count(month, publication) |>
  complete(
    month = seq.Date(
      as.Date("2025-01-01"),
      as.Date("2026-06-01"),
      by = "month"
    ),
    publication,
    fill = list(n = 0)
  ) |>
  arrange(month, publication)

print(monthly_coverage, n = Inf)
# ==================================================
# Step 9A: Visualization 1 - Monthly Coverage
# ==================================================

visual_1 <- ggplot(
  monthly_coverage,
  aes(x = month, y = n, color = publication)
) +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  scale_x_date(
    date_breaks = "1 month",
    date_labels = "%b %Y"
  ) +
  scale_y_continuous(
    limits = c(0, NA)
  ) +
  labs(
    title = "AI Coverage in the Creative Industries",
    subtitle = "Billboard vs. Rolling Stone | January 2025 - June 2026",
    x = "Month",
    y = "Number of Headlines",
    color = "Publication"
  ) +
  scale_color_manual(values = publication_colors) +
  project_theme +
  theme(
    axis.text.x = element_text(
      angle = 45,
      hjust = 1
    ),
    legend.position = "bottom"
  )

plotly::ggplotly(visual_1)
# ==================================================
# Step 9B: Identify Peak Coverage Months
# ==================================================

peak_months <- monthly_coverage |>
  group_by(publication) |>
  slice_max(
    order_by = n,
    n = 5,
    with_ties = FALSE
  ) |>
  ungroup() |>
  arrange(publication, desc(n))

print(peak_months, n = Inf)
# ==================================================
# Step 10: Analyze Creative Sector Distribution
# ==================================================

sector_summary <- creative_ai_data |>
  count(publication, creative_sector) |>
  group_by(publication) |>
  mutate(
    percentage = n / sum(n) * 100
  ) |>
  ungroup() |>
  arrange(publication, desc(n))

print(sector_summary, n = Inf)
# ==================================================
# Step 10A: Visualization 2 - Creative Sectors
# ==================================================

visual_2 <- ggplot(
  sector_summary,
  aes(
    x = creative_sector,
    y = percentage,
    fill = publication
  )
) +
  geom_col(position = "dodge") +
  scale_x_discrete(
    labels = c(
      music = "Music",
      film_tv = "Film & Television",
      publishing = "Publishing",
      visual_arts = "Visual Arts",
      digital_media = "Digital Media",
      cross_industry = "Cross-Industry",
      other_creative = "Other Creative"
    )
  ) +
  scale_y_continuous(
    labels = scales::label_number(suffix = "%")
  ) +
  coord_flip() +
  labs(
    title = "Creative Industries Represented in AI Coverage",
    subtitle = "Percentage of included headlines by publication",
    x = "Creative Sector",
    y = "Percentage of Headlines",
    fill = "Publication"
  ) +
  scale_fill_manual(values = publication_colors) +
  project_theme +
  theme(
    legend.position = "bottom"
  )

plotly::ggplotly(visual_2)
# ==================================================
# Step 11: Analyze Media Frame Distribution
# ==================================================

frame_columns <- c(
  "legal_copyright",
  "economic_impact",
  "creative_innovation",
  "artistic_authenticity",
  "ethics_governance",
  "industry_adoption"
)


frame_data <- creative_ai_data |>
  pivot_longer(
    cols = all_of(frame_columns),
    names_to = "frame",
    values_to = "frame_present"
  ) |>
  mutate(
    frame = recode(
      frame,
      legal_copyright = "Legal and Copyright",
      economic_impact = "Economic Impact",
      creative_innovation = "Creative Innovation",
      artistic_authenticity = "Artistic Authenticity",
      ethics_governance = "Ethics and Governance",
      industry_adoption = "Industry Adoption"
    )
  )


frame_summary <- frame_data |>
  group_by(publication, frame) |>
  summarise(
    volume = sum(frame_present),
    total_headlines = n(),
    prevalence = volume / total_headlines * 100,
    .groups = "drop"
  ) |>
  arrange(publication, desc(prevalence))

print(frame_summary, n = Inf)
# ==================================================
# Step 11A: Validate Media Frame Classifications
# ==================================================


stopifnot(
  all(
    unlist(creative_ai_data[frame_columns]) %in% c(0, 1)
  )
)


frame_validation <- creative_ai_data |>
  mutate(
    frames_per_headline = rowSums(
      across(all_of(frame_columns))
    )
  )


frame_validation |>
  count(frames_per_headline)
# ==================================================
# Step 11B: Visualization 3 - Frame Prevalence
# ==================================================

visual_3 <- ggplot(
  frame_summary,
  aes(
    x = frame,
    y = prevalence,
    fill = publication
  )
) +
  geom_col(position = "dodge") +
  coord_flip() +
  scale_y_continuous(
    labels = scales::label_number(suffix = "%")
  ) +
  labs(
    title = "How Publications Frame AI",
    subtitle = "Prevalence of media frames in creative industry coverage",
    x = "Media Frame",
    y = "Percentage of Headlines",
    fill = "Publication"
  ) +
  scale_fill_manual(values = publication_colors) +
  project_theme +
  theme(
    legend.position = "bottom"
  )

plotly::ggplotly(visual_3)
# ==================================================
# Step 12: Analyze Monthly Frame Volume
# ==================================================

monthly_frame_volume <- frame_data |>
  mutate(
    month = floor_date(publish_date, "month")
  ) |>
  group_by(month, publication, frame) |>
  summarise(
    volume = sum(frame_present),
    .groups = "drop"
  ) |>
  complete(
    month = seq.Date(
      as.Date("2025-01-01"),
      as.Date("2026-06-01"),
      by = "month"
    ),
    publication,
    frame,
    fill = list(volume = 0)
  ) |>
  arrange(month, publication, frame)

print(monthly_frame_volume, n = 20)
# ==================================================
# Step 12A: Visualization 4 - Frame Volume Over Time
# ==================================================

visual_4 <- ggplot(
  monthly_frame_volume,
  aes(
    x = month,
    y = volume,
    color = publication
  )
) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.5) +
  facet_wrap(
    ~ frame,
    ncol = 2
  ) +
  scale_x_date(
    date_breaks = "3 months",
    date_labels = "%b %y"
  ) +
  scale_y_continuous(
    limits = c(0, NA)
  ) +
  labs(
    title = "AI Media Frames Over Time",
    subtitle = "January 2025 - June 2026",
    x = "Month",
    y = "Number of Headlines",
    color = "Publication"
  ) +
  scale_color_manual(values = publication_colors) +
  project_theme +
  theme(
    axis.text.x = element_text(
      angle = 45,
      hjust = 1
    ),
    legend.position = "bottom",
    strip.text = element_text(
      face = "bold"
    )
  )

plotly::ggplotly(visual_4)
# ==================================================
# Step 12B: Identify Peak Months by Media Frame
# ==================================================

peak_frame_months <- monthly_frame_volume |>
  group_by(publication, frame) |>
  slice_max(
    order_by = volume,
    n = 3,
    with_ties = FALSE
  ) |>
  ungroup() |>
  arrange(publication, frame, desc(volume))

print(peak_frame_months, n = Inf)
# ==================================================
# Step 13: Examine Headlines During Peak Periods
# ==================================================

peak_period_headlines <- creative_ai_data |>
  mutate(
    month = floor_date(publish_date, "month")
  ) |>
  filter(
    month %in% as.Date(c(
      "2025-09-01",
      "2025-10-01",
      "2025-11-01",
      "2026-03-01"
    ))
  ) |>
  select(
    id,
    publish_date,
    publication,
    title,
    creative_sector,
    all_of(frame_columns),
    url
  ) |>
  arrange(publish_date, publication)

#View(peak_period_headlines)

nrow(peak_period_headlines)


write_csv(
  peak_period_headlines,
  "ai_peak_period_headlines.csv"
)
# ==================================================
# Step 13A: Establish Key AI-Related Events
# ==================================================

key_events <- tibble(
  event_date = as.Date(c(
    "2025-09-05",
    "2025-09-25",
    "2025-10-10",
    "2025-10-29",
    "2025-11-25",
    "2026-03-04",
    "2026-03-18"
  )),
  
  event = c(
    "Anthropic Copyright Settlement Proposal",
    "Spotify AI Protections",
    "TaTa Debut Single",
    "UMG and Udio Agreement",
    "WMG and Suno Partnership",
    "Apple Music Transparency Tags",
    "BMG Sues Anthropic"
  ),
  
  short_label = c(
    "Anthropic Settlement",
    "Spotify Policies",
    "TaTa Debut",
    "UMG-Udio",
    "WMG-Suno",
    "Apple AI Tags",
    "BMG Lawsuit"
  ),
  
  sector = c(
    "Publishing",
    "Music",
    "Music",
    "Music",
    "Music",
    "Music",
    "Music"
  ),
  
  selected_for_analysis = c(
    TRUE,
    FALSE,
    FALSE,
    FALSE,
    TRUE,
    TRUE,
    FALSE
  ),
  
  source_url = c(
    "https://www.billboard.com/pro/anthropic-ai-pay-1-5-billion-settle-lawsuit-book-authors/",
    "https://www.billboard.com/pro/spotify-updates-ai-music-policies-spam-tracks-removed/",
    "https://www.billboard.com/music/rb-hip-hop/timbaland-tata-ai-music-video-pulse-glitch-1236086619/",
    "https://www.billboard.com/pro/ai-music-udio-settles-lawsuit-universal-music-group/",
    "https://www.billboard.com/pro/suno-warner-music-sign-ai-licensing-deal-settle-lawsuit/",
    "https://www.billboard.com/pro/apple-music-introduces-ai-song-tagging/",
    "https://www.billboard.com/pro/bmg-ai-song-copyright-lawsuit-sues-claude-maker-anthropic/"
  )
)

print(key_events, n = Inf)

write_csv(
  key_events,
  "ai_key_events.csv"
)
# ==================================================
# Step 13B: Annotate Monthly Coverage With Key Events
# ==================================================

selected_events <- key_events |>
  filter(selected_for_analysis == TRUE) |>
  arrange(event_date) |>
  mutate(event_number = row_number())

event_lines <- lapply(
  seq_len(nrow(selected_events)),
  function(i) {
    list(
      type = "line",
      xref = "x",
      yref = "paper",
      x0 = as.character(selected_events$event_date[i]),
      x1 = as.character(selected_events$event_date[i]),
      y0 = 0,
      y1 = 1,
      line = list(
        color = "gray50",
        width = 1.5,
        dash = "dash"
      )
    )
  }
)


event_labels <- lapply(
  seq_len(nrow(selected_events)),
  function(i) {
    list(
      x = as.character(selected_events$event_date[i]),
      y = 1.05,
      xref = "x",
      yref = "paper",
      text = as.character(selected_events$event_number[i]),
      hovertext = selected_events$event[i],
      showarrow = FALSE,
      bgcolor = "#E5E7EB",
      bordercolor = "#9CA3AF",
      borderwidth = 1,
      borderpad = 5,
      font = list(
        size = 13,
        color = "#374151"
      )
    )
  }
)


visual_1_annotated <- plot_ly(
  data = monthly_coverage,
  x = ~month,
  y = ~n,
  color = ~publication,
  colors = publication_colors,
  type = "scatter",
  mode = "lines+markers",
  line = list(width = 2),
  marker = list(size = 6)
) |>
  layout(
    title = list(
      text = "AI Coverage in the Creative Industries"
    ),
    
    shapes = event_lines,
    annotations = event_labels,
    
    xaxis = list(
      title = "Month",
      type = "date",
      tickformat = "%b %Y",
      dtick = "M2",
      tickangle = -45
    ),
    
    yaxis = list(
      title = "Number of Headlines",
      rangemode = "tozero"
    ),
    
    legend = list(
      orientation = "h",
      x = 0.5,
      xanchor = "center",
      y = -0.3
    ),
    
    margin = list(
      l = 65,
      r = 25,
      t = 100,
      b = 120
    ),
    
    font = list(
      family = "Arial",
      size = 12,
      color = "#334155"
    ),
    
    paper_bgcolor = "#FFFFFF",
    plot_bgcolor = "#FFFFFF",
    
    autosize = TRUE
  ) |>
  
  config(
    responsive = TRUE,
    displaylogo = FALSE
  )

visual_1_annotated
# ==================================================
# Step 14: Before-and-After Event Analysis
# ==================================================

event_frame_data <- crossing(
  frame_data,
  selected_events |>
    select(event, event_date)
) |>
  mutate(
    days_from_event = as.integer(
      publish_date - event_date
    ),
    
    period = case_when(
      between(days_from_event, -30, -1) ~ "Before",
      between(days_from_event, 1, 30) ~ "After",
      TRUE ~ NA_character_
    )
  ) |>
  filter(!is.na(period))

event_summary <- event_frame_data |>
  group_by(
    event,
    publication,
    frame,
    period
  ) |>
  summarise(
    volume = sum(frame_present),
    total_headlines = n(),
    .groups = "drop"
  ) |>
  complete(
    event,
    publication,
    frame,
    period = c("Before", "After"),
    fill = list(
      volume = 0,
      total_headlines = 0
    )
  ) |>
  mutate(
    prevalence = if_else(
      total_headlines > 0,
      volume / total_headlines * 100,
      NA_real_
    ),
    
    period = factor(
      period,
      levels = c("Before", "After")
    )
  )

print(event_summary, n = Inf)
# ==================================================
# Step 14A: Calculate Changes in Media Framing
# ==================================================

event_changes <- event_summary |>
  pivot_wider(
    names_from = period,
    values_from = c(
      volume,
      prevalence,
      total_headlines
    )
  ) |>
  mutate(
    volume_change = volume_After - volume_Before,
    
    prevalence_change =
      prevalence_After - prevalence_Before
  ) |>
  arrange(
    event,
    publication,
    desc(abs(volume_change))
  )

print(event_changes, n = Inf)

write_csv(
  event_changes,
  "ai_event_frame_changes.csv"
)
# ==================================================
# Step 15: Establish Event Visualization Design
# ==================================================

frame_order <- c(
  "Legal and Copyright",
  "Economic Impact",
  "Creative Innovation",
  "Artistic Authenticity",
  "Ethics and Governance",
  "Industry Adoption"
)

frame_labels <- c(
  "Legal & Copyright",
  "Economic Impact",
  "Creative Innovation",
  "Artistic Authenticity",
  "Ethics & Governance",
  "Industry Adoption"
)

period_colors <- c(
  "Before" = "#94A3B8",
  "After" = "#0F766E"
)

event_order <- selected_events$event


volume_max <- max(
  1,
  event_summary$volume,
  na.rm = TRUE
)

# ==================================================
# Step 15A: Create Reusable Visualization Function
# ==================================================

make_event_chart <- function(
    event_name,
    metric = "prevalence"
) {
  
  is_percentage <- metric == "prevalence"
  
  event_info <- selected_events |>
    filter(event == event_name)
  
  event_date <- event_info$event_date[1]
  
  panel_data <- event_summary |>
    filter(event == event_name) |>
    mutate(
      frame_label = factor(
        frame,
        levels = frame_order,
        labels = frame_labels
      ),
      
      value = .data[[metric]],
      
      bar_label = case_when(
        is.na(value) ~ "",
        value == 0 ~ "",
        is_percentage ~ paste0(
          round(value), "%"
        ),
        TRUE ~ as.character(value)
      ),
      
      hover_label = paste0(
        "<b>", frame, "</b>",
        "<br>Publication: ", publication,
        "<br>Period: ", period,
        "<br>Frame count: ", volume,
        "<br>Total headlines: ", total_headlines,
        "<br>Prevalence: ",
        ifelse(
          is.na(prevalence),
          "Not available",
          paste0(round(prevalence, 1), "%")
        )
      )
    )
  
  # Create publication panels
  
  make_panel <- function(pub_name) {
    
    pub_data <- panel_data |>
      filter(publication == pub_name)
    
    p <- plot_ly()
    
    for (period_name in c("Before", "After")) {
      
      period_data <- pub_data |>
        filter(period == period_name)
      
      p <- p |>
        add_bars(
          data = period_data,
          x = ~value,
          y = ~frame_label,
          name = period_name,
          legendgroup = period_name,
          orientation = "h",
          
          marker = list(
            color = period_colors[[period_name]]
          ),
          
          text = ~bar_label,
          textposition = "outside",
          cliponaxis = FALSE,
          
          textfont = list(
            size = 11,
            color = "#334155"
          ),
          
          hovertext = ~hover_label,
          hoverinfo = "text",
          
          showlegend = pub_name == "Billboard"
        )
    }
    
    p |>
      layout(
        barmode = "group",
        bargap = 0.4,
        
        xaxis = list(
          range = if (is_percentage) {
            c(0, 100)
          } else {
            c(0, volume_max + 1)
          },
          
          ticksuffix = if (is_percentage) {
            "%"
          } else {
            ""
          },
          
          dtick = if (is_percentage) 25 else 2,
          tickangle = 0,
          tickfont = list(size = 10),
          gridcolor = "#E2E8F0",
          zeroline = FALSE,
          title = ""
        ),
        
        yaxis = list(
          categoryorder = "array",
          categoryarray = rev(frame_labels),
          title = "",
          showgrid = FALSE,
          tickfont = list(size = 11)
        )
      )
  }
  
  
  get_sample_label <- function(pub_name) {
    
    counts <- panel_data |>
      filter(publication == pub_name) |>
      distinct(period, total_headlines)
    
    before_n <- counts$total_headlines[
      counts$period == "Before"
    ]
    
    after_n <- counts$total_headlines[
      counts$period == "After"
    ]
    
    paste0(
      "<b>", pub_name, "</b>",
      "<br>Before: n = ", before_n,
      " | After: n = ", after_n
    )
  }
  
  # Combine publication panels
  
  subplot(
    make_panel("Billboard"),
    make_panel("Rolling Stone"),
    nrows = 1,
    shareY = TRUE,
    margin = 0.09
  ) |>
    layout(
      title = list(
        text = paste0(
          "<b>", event_name, "</b>",
          "<br><sup>",
          format(event_date, "%B %d, %Y"),
          " | 30-day comparison",
          "</sup>"
        ),
        
        x = 0.02,
        xanchor = "left",
        font = list(size = 17)
      ),
      
      annotations = list(
        list(
          text = get_sample_label("Billboard"),
          x = 0.225,
          y = 1.08,
          xref = "paper",
          yref = "paper",
          xanchor = "center",
          showarrow = FALSE,
          font = list(size = 11)
        ),
        
        list(
          text = get_sample_label("Rolling Stone"),
          x = 0.775,
          y = 1.08,
          xref = "paper",
          yref = "paper",
          xanchor = "center",
          showarrow = FALSE,
          font = list(size = 11)
        ),
        
        list(
          text = if (is_percentage) {
            "Percentage of headlines containing frame"
          } else {
            "Number of headlines containing frame"
          },
          
          x = 0.5,
          y = -0.13,
          xref = "paper",
          yref = "paper",
          showarrow = FALSE,
          font = list(size = 11)
        )
      ),
      
      legend = list(
        orientation = "h",
        x = 0.5,
        xanchor = "center",
        y = -0.25,
        font = list(size = 12)
      ),
      
      margin = list(
        l = 150,
        r = 45,
        t = 125,
        b = 100
      ),
      
      font = list(
        family = "Arial",
        color = "#334155",
        size = 12
      ),
      
      paper_bgcolor = "#FFFFFF",
      plot_bgcolor = "#FFFFFF",
      
      barmode = "group",
      height = 470,
      autosize = TRUE
    ) |>
    config(
      responsive = TRUE,
      displaylogo = FALSE
    )
}
# ==================================================
# Step 15B: Generate Event Visualizations
# ==================================================


event_charts <- lapply(
  event_order,
  function(e) {
    make_event_chart(
      e,
      metric = "prevalence"
    )
  }
)


event_volume_charts <- lapply(
  event_order,
  function(e) {
    make_event_chart(
      e,
      metric = "volume"
    )
  }
)


event_charts[[1]]
event_charts[[2]]
event_charts[[3]]

event_volume_charts[[1]]
event_volume_charts[[2]]
event_volume_charts[[3]]
# ==================================================
# Step 15C: Interactive Event Analysis Dashboard
# ==================================================

dashboard <- plot_ly(
  height = 900
)
dashboard_states <- crossing(
  event = selected_events$event,
  metric = c("prevalence", "volume")
) |>
  arrange(
    match(event, selected_events$event),
    match(metric, c("prevalence", "volume"))
  )

# --------------------------------------------------
# Create traces for every event and metric
# --------------------------------------------------

for (i in seq_len(nrow(dashboard_states))) {
  
  current_event <- dashboard_states$event[i]
  current_metric <- dashboard_states$metric[i]
  
  for (pub in c("Billboard", "Rolling Stone")) {
    
    for (p in c("Before", "After")) {
      
      chart_data <- event_summary |>
        filter(
          event == current_event,
          publication == pub,
          period == p
        ) |>
        mutate(
          value = .data[[current_metric]],
          
          frame_label = factor(
            frame,
            levels = frame_order,
            labels = frame_labels
          ),
          
          bar_label = case_when(
            is.na(value) ~ "",
            current_metric == "prevalence" ~
              paste0(round(value), "%"),
            TRUE ~ as.character(value)
          ),
          
          hover_label = paste0(
            "<b>", frame, "</b>",
            "<br>Publication: ", publication,
            "<br>Period: ", period,
            "<br>Frame count: ", volume,
            "<br>Total headlines: ", total_headlines,
            "<br>Prevalence: ",
            ifelse(
              is.na(prevalence),
              "Not available",
              paste0(round(prevalence, 1), "%")
            )
          )
        )
      
      dashboard <- dashboard |>
        add_bars(
          data = chart_data,
          
          x = ~value,
          y = ~frame_label,
          
          orientation = "h",
          
          name = p,
          legendgroup = p,
          
          marker = list(
            color = period_colors[[p]]
          ),
          
          text = ~bar_label,
          textposition = "outside",
          cliponaxis = FALSE,
          
          textfont = list(
            size = 11,
            color = "#334155"
          ),
          
          hovertext = ~hover_label,
          hoverinfo = "text",
          
          xaxis = "x",
          
          yaxis = if (pub == "Billboard") {
            "y"
          } else {
            "y2"
          },
          
          visible = i == 1,
          
          showlegend = pub == "Billboard"
        )
    }
  }
}

# --------------------------------------------------
# Create reusable dashboard title
# --------------------------------------------------

make_dashboard_title <- function(event_name) {
  
  event_info <- selected_events |>
    filter(event == event_name)
  
  list(
    text = paste0(
      "<b>", event_name, "</b>",
      "<br><sup>",
      format(
        event_info$event_date[1],
        "%B %d, %Y"
      ),
      " | 30-day comparison",
      "</sup>"
    ),
    
    x = 0.02,
    xanchor = "left",
    
    y = 0.98,
    yanchor = "top",
    
    font = list(
      size = 18,
      color = "#334155"
    )
  )
}

# --------------------------------------------------
# Create interactive dropdown menu
# --------------------------------------------------

dashboard_buttons <- lapply(
  seq_len(nrow(dashboard_states)),
  function(i) {
    
    current_event <- dashboard_states$event[i]
    current_metric <- dashboard_states$metric[i]
    
    event_info <- selected_events |>
      filter(event == current_event)
    
    is_percentage <- current_metric == "prevalence"
    
    list(
      method = "update",
      
      label = paste0(
        event_info$short_label,
        " | ",
        if (is_percentage) {
          "Prevalence (%)"
        } else {
          "Volume (n)"
        }
      ),
      
      args = list(
        
        # Display selected event and metric
        list(
          visible = rep(
            seq_len(nrow(dashboard_states)) == i,
            each = 4
          )
        ),
        
        # Update title and horizontal axis
        list(
          title = make_dashboard_title(
            current_event
          ),
          
          xaxis = list(
            
            range = if (is_percentage) {
              c(0, 110)
            } else {
              c(0, volume_max + 2)
            },
            
            ticksuffix = if (is_percentage) {
              "%"
            } else {
              ""
            },
            
            dtick = if (is_percentage) {
              25
            } else {
              2
            },
            
            title = if (is_percentage) {
              "Percentage of Headlines"
            } else {
              "Number of Headlines"
            },
            
            tickangle = 0,
            
            gridcolor = "#E2E8F0",
            
            zeroline = FALSE,
            
            anchor = "y2"
          )
        )
      )
    )
  }
)

# --------------------------------------------------
# Apply dashboard styling
# --------------------------------------------------

visual_5_dashboard <- dashboard |>
  layout(
    
    # Left-aligned title
    title = make_dashboard_title(
      dashboard_states$event[1]
    ),
    
    # Dropdown positioned below the title
    updatemenus = list(
      list(
        type = "dropdown",
        
        active = 0,
        
        buttons = dashboard_buttons,
        
        x = -0.25,
        xanchor = "left",
        
        y = 1.13,
        yanchor = "top",
        
        bgcolor = "#F8FAFC",
        
        bordercolor = "#CBD5E1",
        borderwidth = 1,
        
        font = list(
          size = 12,
          color = "#334155"
        ),
        
        pad = list(
          t = 5,
          b = 5
        )
      )
    ),
    
    # Shared horizontal axis
    xaxis = list(
      range = c(0, 110),
      
      ticksuffix = "%",
      
      dtick = 25,
      
      tickangle = 0,
      
      title = "Percentage of Headlines",
      
      gridcolor = "#E2E8F0",
      
      zeroline = FALSE,
      
      anchor = "y2"
    ),
    
    # Billboard panel
    yaxis = list(
      domain = c(0.57, 1),
      
      categoryorder = "array",
      
      categoryarray = rev(frame_labels),
      
      title = "",
      
      tickfont = list(size = 11)
    ),
    
    # Rolling Stone panel
    yaxis2 = list(
      domain = c(0, 0.43),
      
      categoryorder = "array",
      
      categoryarray = rev(frame_labels),
      
      title = "",
      
      tickfont = list(size = 11)
    ),
    
    # Publication headings
    annotations = list(
      
      list(
        text = "<b>Billboard</b>",
        
        x = 0,
        y = 1.04,
        
        xref = "paper",
        yref = "paper",
        
        xanchor = "left",
        
        showarrow = FALSE,
        
        font = list(
          size = 15,
          color = "#B4534B"
        )
      ),
      
      list(
        text = "<b>Rolling Stone</b>",
        
        x = 0,
        y = 0.47,
        
        xref = "paper",
        yref = "paper",
        
        xanchor = "left",
        
        showarrow = FALSE,
        
        font = list(
          size = 15,
          color = "#287C91"
        )
      )
    ),
    
    # Bar styling
    barmode = "group",
    
    bargap = 0.35,
    
    # Legend
    legend = list(
      orientation = "h",
      
      x = 0.5,
      xanchor = "center",
      
      y = -0.14,
      
      font = list(size = 12)
    ),
    
    # Typography
    font = list(
      family = "Arial",
      size = 12,
      color = "#334155"
    ),
    
    # Background
    paper_bgcolor = "#FFFFFF",
    
    plot_bgcolor = "#FFFFFF",
    
    # Chart spacing
    margin = list(
      l = 155,
      r = 50,
      t = 145,
      b = 100
    ),
    
    autosize = TRUE
    
  ) |>
  config(
    responsive = TRUE,
    displaylogo = FALSE
  )

# --------------------------------------------------
# Display interactive dashboard
# --------------------------------------------------

visual_5_dashboard
# ==================================================
# Step 16: Identify Largest Changes in Framing
# ==================================================

largest_frame_changes <- event_changes |>
  group_by(event, publication) |>
  slice_max(
    order_by = abs(prevalence_change),
    n = 3,
    with_ties = FALSE
  ) |>
  ungroup() |>
  select(
    event,
    publication,
    frame,
    volume_Before,
    volume_After,
    prevalence_Before,
    prevalence_After,
    prevalence_change,
    total_headlines_Before,
    total_headlines_After
  )

print(largest_frame_changes, n = Inf)