### Example 19-7 Building a heatmap

### This Monte Carlo simulation simulates rolling 2D6 10000 times

# Generate a vector of random values of 1-6 for each of 2 dice
# Parameter replace=TRUE allows the generation of more than 6 elements

dice1 <- sample(1:6, 10000, replace = TRUE)
dice2 <- sample(1:6, 10000, replace = TRUE)

# Bind into a dataframe with sum of the two die rolls

results <- data.frame(sum=dice1+dice2,D1=dice1,D2=dice2)

# Generate the expected probabilities for each 2D6 roll

expected_probs <- data.frame(
  val = 2:12,
  prob = c(1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1) / 36
)

# Generate the expected frequencies for each bin

expected_probs$count <- expected_probs$prob * 10000

# Create a dataframe to show how often each pair of dice appear

tile_data <- aggregate(
  x = list(n = results$D1),   # n shows how often each pair appear
  by = list(D1 = results$D1, D2 = results$D2),
  FUN = length
)

# Include the ggplot2 library

library(ggplot2)

### Create a heatmap using the tileplot tool

# Create a tile plot of D1 by D2

# Set the dataset and the aesthetics
ggplot(tile_data, aes(x = D1, y = D2, fill = n)) +
  
  # Set background as white
  geom_tile(colour = "white") +
  
  # Set internal labels as white, size 4, showing the value
  geom_text(aes(label = n), colour = "white", size = 4) +
  
  # Label all x and y values
  scale_x_continuous(breaks = 1:6) +
  scale_y_continuous(breaks = 1:6) +
  
  # Define the fill gradient from light green to dark green
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +
  
  # Add the label text
  labs(
    title = "Joint Frequency of Two Dice Rolls",
    x = "Die 1",
    y = "Die 2",
    fill = "Frequency"
  ) +
  
  # Use a professional style
  theme_minimal() +
  
  # Set the axis scales to the same length to get square cells
  coord_equal()




# Create a graph using geom_line and geom_point

# Frequency tables (force all faces 1–6 to appear)
freq1 <- table(factor(dice1, levels = 1:6))
freq2 <- table(factor(dice2, levels = 1:6))

# Build data frames manually (base R)
dice1_df <- data.frame(
  face = 1:6,
  frequency = as.numeric(freq1)
)

dice2_df <- data.frame(
  face = 1:6,
  frequency = as.numeric(freq2)
)

dice1_df$dice <- "Die 1"
dice2_df$dice <- "Die 2"

combined_df <- rbind(dice1_df, dice2_df)

# Set the dataset and the aesthetics
ggplot(combined_df, aes(x = face, y = frequency, colour = dice, group = dice)) +

  # Add the lines (both lines at once, as colour and group are in the aes())
  geom_line() +

  # Add the points
  geom_point() +
  
  # Set the x-axis labels
  scale_x_continuous(breaks = 1:6) +

  # Set the main labels  
  labs(
    title = "Frequency Distributions of Two Dice",
    x = "Face",
    y = "Frequency",
    colour = "Die"
  ) +

  # Use a professional style
  theme_minimal() +
  

