### Example 19-5 Adding a line plot to the histogram

### 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 basic histogram of the sum using 11 columns

hist(results$sum, breaks=11)

### Create a more complex histogram using ggplot2

# Include the ggplot2 library

library(ggplot2)

# Create the visualisation

# First create a plotting object ggplot(), then define the dataset
# and map the column sum to the x-axis

ggplot(results, aes(x = sum, fill="white")) +
  
  # Create a histogram with red bins outlined in white, each of width 1
  geom_histogram(binwidth = 1, fill="red", colour="white") +
  
  # Define the labels as title, x-axis and y-axis
  labs(title="Distribution of Dice Roll Sums",
       x = "Sum of Two Dice",
       y = "Frequency") +
  
  # Add a text layer to show the number of times each value appears
  geom_text(stat = "bin",
            binwidth = 1,
            aes(label = after_stat(count)),
            vjust = -0.3) +
  
  # Label all x values
  scale_x_continuous(breaks = 2:12) +
  
  # Add a blue line showing the expected frequencies
  geom_line(
    data = expected_probs,
    aes(x = val, y = count),
    colour = "blue",
    linewidth = 1) +
  
  # Add the points on the line
  geom_point(
    data = expected_probs,
    aes(x = val, y = count),
    colour = "blue",
    size = 2) +
  
  # Apply a minimalist theme (good for academic and professional purposes)
  theme_minimal()
