################################################################################
# CE092 - Árvores de classificação e regressão
# Figura 7 - Gráficos para os dados de classificação (iris)
################################################################################

options(device = 'x11')

rm(list = ls())

x11(width = 8, height = 5)
################################################################################
# Pacotes
################################################################################

library(ggplot2)
library(ggpubr)
library(rpart)
library(rpart.plot)

################################################################################
# Base de dados
################################################################################

data(iris)

################################################################################
# Paleta (elegante e consistente)
################################################################################

cores <- c("setosa"     = "#1b9e77",
           "versicolor" = "#d95f02",
           "virginica"  = "#7570b3")

################################################################################
# Tema padrão (seu estilo)
################################################################################

tema_padrao <- theme_classic(base_size = 14) +
    theme(
        legend.position = "bottom",
        legend.title = element_blank(),
        legend.text = element_text(size = 12)
    )

################################################################################
# Gráficos
################################################################################

g1 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
    geom_jitter(size = 2) +
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    labs(x = "Comprimento da pétala",
         y = "Largura da pétala") +
    tema_padrao

g2 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Width, color = Species)) +
    geom_jitter(size = 2) +
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    labs(x = "Comprimento da sépala",
         y = "Largura da pétala") +
    tema_padrao

g3 <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Width, color = Species)) +
    geom_jitter(size = 2) +
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    labs(x = "Comprimento da pétala",
         y = "Largura da sépala") +
    tema_padrao

g4 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
    geom_jitter(size = 2) +
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    labs(x = "Comprimento da sépala",
         y = "Largura da sépala") +
    tema_padrao

################################################################################
# Arranjo final (legenda única)
################################################################################

fig_final <- ggarrange(
    g1, g2, g3, g4,
    nrow = 2, ncol = 2,
    common.legend = TRUE,
    legend = "bottom"
)

fig_final



################################################################################

data(iris)

ajuste_arvore <- rpart(
    Species ~ .,
    data = iris,
    method = "class"
)

rpart.plot(
    ajuste_arvore,
    type = 2,
    extra = 104,
    under = TRUE,
    fallen.leaves = TRUE,
    nn = FALSE,
    digits = 2,
    varlen = 15,
    faclen = 15,
    tweak = 1.05
)


################################################################################

################################################################################
# CE092 - Árvores de classificação e regressão
# Figura 9 - versão refinada
################################################################################

data(iris)

cores <- c("setosa"     = "#1b9e77",
           "versicolor" = "#d95f02",
           "virginica"  = "#7570b3")

g9 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
    geom_jitter(size = 2.2, alpha = 0.9) +
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    scale_x_continuous(breaks = seq(1, 7, by = 1)) +
    scale_y_continuous(breaks = seq(0.5, 2.5, by = 0.5)) +
    labs(x = "Comprimento da pétala",
         y = "Largura da pétala",
         color = NULL) +
    theme_classic(base_size = 14) +
    theme(
        legend.position = "bottom",
        legend.title = element_blank(),
        legend.text = element_text(size = 12)
    )

g9

################################################################################
# CE092 - Árvores de classificação e regressão
# Figura 10 - Partição 1 com anotação
################################################################################

data(iris)

cores <- c("setosa"     = "#1b9e77",
           "versicolor" = "#d95f02",
           "virginica"  = "#7570b3")

corte_1 <- 2.4

g10 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
    geom_jitter(size = 2.2, alpha = 0.9) +
    geom_vline(xintercept = corte_1,
               linetype = 2,
               linewidth = 0.8) +
    annotate("text",
             x = corte_1 + 0.15, y = 2.35,
             label = "Petal.Length = 2.4",
             hjust = 0, size = 4.2) +
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    scale_x_continuous(breaks = seq(1, 7, by = 1)) +
    scale_y_continuous(breaks = seq(0.5, 2.5, by = 0.5)) +
    labs(x = "Comprimento da pétala",
         y = "Largura da pétala",
         color = NULL) +
    theme_classic(base_size = 14) +
    theme(
        legend.position = "bottom",
        legend.title = element_blank(),
        legend.text = element_text(size = 12)
    )

g10



################################################################################
# CE092 - Árvores de classificação e regressão
# Figura 11 - versão com identificação das regiões
################################################################################

data(iris)

cores <- c("setosa"     = "#1b9e77",
           "versicolor" = "#d95f02",
           "virginica"  = "#7570b3")

corte_x <- 2.4
corte_y <- 1.8

g11 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
    geom_jitter(size = 2.2, alpha = 0.9) +
    geom_vline(xintercept = corte_x,
               linetype = 2,
               linewidth = 0.8) +
    annotate("segment",
             x = corte_x, xend = 7.1,
             y = corte_y, yend = corte_y,
             linetype = 2,
             linewidth = 0.8) +
    
    annotate("text", x = 1.7, y = 2.35, label = "Setosa", size = 5) +
    annotate("text", x = 4.6, y = 1.1,  label = "Versicolor", size = 5) +
    annotate("text", x = 6.0, y = 2.25, label = "Virginica", size = 5) +
    
    scale_color_manual(values = cores,
                       labels = c("Setosa", "Versicolor", "Virginica")) +
    scale_x_continuous(breaks = seq(1, 7, by = 1)) +
    scale_y_continuous(breaks = seq(0.5, 2.5, by = 0.5)) +
    labs(x = "Comprimento da pétala",
         y = "Largura da pétala",
         color = NULL) +
    theme_classic(base_size = 14) +
    theme(
        legend.position = "bottom",
        legend.title = element_blank(),
        legend.text = element_text(size = 12)
    )

g11



################################################################################

################################################################################
# Figura 12 - Medidas de impureza para árvores de classificação
# Versão em ggplot2
################################################################################

library(ggplot2)

x11(width = 8, height = 5)

#----------------------------------------------------------------------------
# 1) Base de dados
#----------------------------------------------------------------------------

p <- seq(0, 1, by = 0.001)

gini <- 2 * p * (1 - p)

entropia <- ifelse(
    p %in% c(0, 1),
    0,
    -p * log(p) - (1 - p) * log(1 - p)
)

dados <- rbind(
    data.frame(
        p = p,
        impureza = entropia,
        medida = "Informação"
    ),
    data.frame(
        p = p,
        impureza = gini,
        medida = "Gini"
    )
)

#----------------------------------------------------------------------------
# 2) Posições para rótulos diretos
#----------------------------------------------------------------------------

rotulos <- data.frame(
    p = c(0.78, 0.78),
    impureza = c(
        -0.78 * log(0.78) - (1 - 0.78) * log(1 - 0.78),
        2.4 * 0.78 * (1 - 0.78)
    ),
    medida = c("Informação", "Gini")
)

#----------------------------------------------------------------------------
# 3) Gráfico
#----------------------------------------------------------------------------

x11(width = 8, height = 5)

ggplot(dados, aes(x = p, y = impureza, color = medida)) +
    geom_line(linewidth = 1.3, lineend = "round") +
    
    geom_hline(yintercept = 0, linewidth = 0.3, color = "grey70") +
    geom_vline(xintercept = 0.5, linetype = "dashed", linewidth = 0.4, color = "grey65") +
    
    geom_point(
        data = data.frame(
            p = c(0.5, 0.5),
            impureza = c(log(2), 0.5),
            medida = c("Informação", "Gini")
        ),
        size = 2.2,
        show.legend = FALSE
    ) +
    
    geom_text(
        data = rotulos,
        aes(label = medida),
        hjust = -0.05,
        vjust = c(-0.5, 1.3),
        size = 5,
        show.legend = FALSE
    ) +
    
    annotate(
        "text",
        x = 0.5,
        y = log(2),
        label = "máximo da entropia",
        vjust = -1.1,
        size = 4.1,
        color = "grey30"
    ) +
    
    annotate(
        "text",
        x = 0.5,
        y = 0.5,
        label = "máximo do Gini",
        vjust = 1.8,
        size = 4.1,
        color = "grey30"
    ) +
    
    scale_color_manual(
        values = c(
            "Informação" = "steelblue4",
            "Gini" = "darkorange3"
        )
    ) +
    
    scale_x_continuous(
        name = "p",
        breaks = seq(0, 1, by = 0.1),
        limits = c(0, 1),
        expand = expansion(mult = c(0.01, 0.12))
    ) +
    
    scale_y_continuous(
        name = "Impureza",
        breaks = seq(0, 0.7, by = 0.1),
        limits = c(0, 0.75),
        expand = expansion(mult = c(0.02, 0.03))
    ) +
    
    
    theme_minimal(base_size = 14) +
    theme(
        legend.position = "none",
        panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color = "grey88", linewidth = 0.4),
        axis.title = element_text(size = 14),
        axis.text = element_text(size = 12),
        plot.title = element_text(face = "bold", size = 16),
        plot.subtitle = element_text(size = 12, color = "grey30")
    )



################################################################################

################################################################################
# Figura 16 - Curva de custo-complexidade (com regra 1SE)
################################################################################

################################################################################
# Figura 16 - Curva de custo-complexidade (com regra 1SE)
################################################################################

library(ggplot2)

#------------------------------------------------------------------------------
# 1) Dados ilustrativos
#------------------------------------------------------------------------------

dados_ccp <- data.frame(
    tamanho_arvore = c(1, 2, 4, 7, 11, 15, 20),
    impureza_cv    = c(1.00, 0.60, 0.40, 0.25, 0.20, 0.22, 0.25)
)

# ponto escolhido (mínimo)
ponto_escolhido <- data.frame(
    tamanho_arvore = 7,
    impureza_cv    = 0.25
)

# ponto 1SE (árvore mais simples dentro do limiar)
ponto_1se <- data.frame(
    tamanho_arvore = 11,
    impureza_cv    = 0.20
)

# linha horizontal (limiar 1SE)
ref <- 0.30

#------------------------------------------------------------------------------
# 2) Gráfico
#------------------------------------------------------------------------------

ggplot(dados_ccp, aes(x = tamanho_arvore, y = impureza_cv)) +
    
    # linha principal
    geom_line(
        linewidth = 0.8,
        color = "grey40",
        lineend = "round"
    ) +
    
    # pontos
    geom_point(size = 2.4, color = "black") +
    
    # ponto mínimo
    geom_point(
        data = ponto_escolhido,
        color = "firebrick3",
        fill  = "firebrick2",
        size  = 3.2,
        shape = 21,
        stroke = 0.6
    ) +
    
    # ponto 1SE
    geom_point(
        data = ponto_1se,
        color = "dodgerblue4",
        fill  = "dodgerblue3",
        size  = 3.2,
        shape = 21,
        stroke = 0.6
    ) +
    
    # linha horizontal (limiar)
    geom_hline(
        yintercept = ref,
        linetype = "dashed",
        linewidth = 0.5,
        color = "firebrick3"
    ) +
    
    # linha vertical (regra 1SE)
    geom_segment(
        data = ponto_1se,
        aes(
            x = tamanho_arvore,
            xend = tamanho_arvore,
            y = impureza_cv,
            yend = ref
        ),
        linetype = "dotted",
        linewidth = 0.6,
        color = "dodgerblue4"
    ) +
    
    # anotação regra 1SE
    annotate(
        "text",
        x = 11.2,
        y = (ref + 0.20)/2,
        label = "regra 1SE",
        hjust = 0,
        size = 4.2,
        color = "dodgerblue4"
    ) +
    
    # anotação limiar
    annotate(
        "text",
        x = 16,
        y = ref,
        label = "limiar (1SE)",
        hjust = 0,
        vjust = -0.7,
        size = 4.0,
        color = "firebrick4"
    ) +
    
    scale_x_continuous(
        name = "Tamanho da árvore",
        breaks = 1:20,
        limits = c(1, 20)
    ) +
    
    scale_y_continuous(
        name = "Impureza (validação cruzada)",
        limits = c(0.15, 1.05),
        breaks = seq(0.2, 1.0, by = 0.2),
        expand = expansion(mult = c(0.02, 0.04))
    ) +

    theme_classic(base_size = 14) +
    theme(
        panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_line(color = "grey87", linewidth = 0.4),
        axis.title = element_text(size = 14),
        axis.text = element_text(size = 11),
        plot.title = element_text(face = "bold", size = 16),
        plot.subtitle = element_text(size = 12, color = "grey30")
    )



################################################################################
# Figura 3 - Partições e árvore correspondente
# Versão corrigida
################################################################################

library(ggplot2)
library(patchwork)

#===============================================================================
# 1) Painel das partições
#===============================================================================

regioes <- data.frame(
    xmin   = c(0.00, 0.40, 0.40, 0.70),
    xmax   = c(0.40, 0.70, 0.70, 1.00),
    ymin   = c(0.00, 0.00, 0.55, 0.00),
    ymax   = c(1.00, 0.55, 1.00, 1.00),
    regiao = c("R1", "R2", "R3", "R4"),
    x      = c(0.20, 0.55, 0.55, 0.85),
    y      = c(0.50, 0.25, 0.77, 0.50)
)

g_particoes <- ggplot() +
    geom_rect(
        data = regioes,
        aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
        fill = "white",
        color = "grey25",
        linewidth = 0.7
    ) +
    geom_text(
        data = regioes,
        aes(x = x, y = y, label = regiao),
        family = "serif",
        size = 6
    ) +
    annotate(
        "text",
        x = 0.40, y = -0.04,
        label = "t1",
        family = "serif",
        size = 4.5
    ) +
    annotate(
        "text",
        x = 0.70, y = -0.04,
        label = "t3",
        family = "serif",
        size = 4.5
    ) +
    annotate(
        "text",
        x = 0.73, y = 0.55,
        label = "t2",
        family = "serif",
        size = 4.5,
        hjust = 0
    ) +
    scale_x_continuous(
        limits = c(0, 1),
        expand = c(0, 0)
    ) +
    scale_y_continuous(
        limits = c(-0.08, 1),
        expand = c(0, 0)
    ) +
    coord_fixed(clip = "off") +
    labs(
        x = expression(x[1]),
        y = expression(x[2]),
        title = "Partições"
    ) +
    theme_minimal(base_size = 15) +
    theme(
        panel.grid = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(hjust = 0.5, face = "bold", size = 15),
        axis.title = element_text(size = 15)
    )

#===============================================================================
# 2) Painel da árvore - corrigido
#===============================================================================

# Nós internos
raiz      <- c(0.50, 1.00)   # x1 < t1
no_x1_t3  <- c(0.72, 0.70)   # x1 < t3
no_x2_t2  <- c(0.60, 0.40)   # x2 < t2

# Folhas
folha_r1 <- c(0.18, 0.05)
folha_r2 <- c(0.50, 0.05)
folha_r3 <- c(0.68, 0.05)
folha_r4 <- c(0.88, 0.05)

segmentos <- data.frame(
    x    = c(
        raiz[1],      raiz[1],
        no_x1_t3[1],  no_x1_t3[1],
        no_x2_t2[1],  no_x2_t2[1]
    ),
    y    = c(
        raiz[2],      raiz[2],
        no_x1_t3[2],  no_x1_t3[2],
        no_x2_t2[2],  no_x2_t2[2]
    ),
    xend = c(
        folha_r1[1],  no_x1_t3[1],
        no_x2_t2[1],  folha_r4[1],
        folha_r2[1],  folha_r3[1]
    ),
    yend = c(
        folha_r1[2],  no_x1_t3[2],
        no_x2_t2[2],  folha_r4[2],
        folha_r2[2],  folha_r3[2]
    )
)

g_arvore <- ggplot() +
    geom_segment(
        data = segmentos,
        aes(x = x, y = y, xend = xend, yend = yend),
        linewidth = 0.8,
        color = "grey20",
        lineend = "round"
    ) +
    annotate(
        "text",
        x = raiz[1], y = 1.07,
        label = "x1 < t1",
        family = "serif",
        size = 5
    ) +
    annotate(
        "text",
        x = no_x1_t3[1] + 0.08, y = no_x1_t3[2] + 0.02,
        label = "x1 < t3",
        family = "serif",
        size = 5,
        hjust = 0
    ) +
    annotate(
        "text",
        x = no_x2_t2[1] - 0.08, y = no_x2_t2[2] + 0.02,
        label = "x2 < t2",
        family = "serif",
        size = 5,
        hjust = 1
    ) +
    annotate(
        "text",
        x = folha_r1[1], y = -0.01,
        label = "R1",
        family = "serif",
        size = 6,
        vjust = 1
    ) +
    annotate(
        "text",
        x = folha_r2[1], y = -0.01,
        label = "R2",
        family = "serif",
        size = 6,
        vjust = 1
    ) +
    annotate(
        "text",
        x = folha_r3[1], y = -0.01,
        label = "R3",
        family = "serif",
        size = 6,
        vjust = 1
    ) +
    annotate(
        "text",
        x = folha_r4[1], y = -0.01,
        label = "R4",
        family = "serif",
        size = 6,
        vjust = 1
    ) +
    coord_cartesian(
        xlim = c(0.10, 0.95),
        ylim = c(-0.06, 1.12),
        clip = "off"
    ) +
    labs(title = "Árvore") +
    theme_void() +
    theme(
        plot.title = element_text(hjust = 0.5, face = "bold", size = 15)
    )

#===============================================================================
# 3) Figura final
#===============================================================================

x11(width = 8, height = 5)
figura3_nova <- g_particoes + g_arvore +
    plot_layout(widths = c(1, 1)) 

figura3_nova

#===============================================================================
# 4) Salvar
#===============================================================================

ggsave(
    filename = "Figura3_particoes_arvore_corrigida.png",
    plot = figura3_nova,
    width = 10,
    height = 5.5,
    dpi = 300,
    bg = "white"
)



################################################################################
################################################################################
# Figura ilustrativa - Curva de custo-complexidade
# Eixo y: R_alpha(T)
# Eixo x: alpha
# Curva estritamente decrescente
################################################################################

library(ggplot2)

#------------------------------------------------------------------------------
# 1) Dados ilustrativos
#------------------------------------------------------------------------------

alpha <- seq(0, 1.2, length.out = 300)

# Curva suave, estritamente decrescente
R_alpha <- 1.05 - 0.78 * (1 - exp(-3.2 * alpha))

dados <- data.frame(
    alpha = alpha,
    R_alpha = R_alpha
)

#------------------------------------------------------------------------------
# 2) Gráfico
#------------------------------------------------------------------------------

ggplot(dados, aes(x = alpha, y = R_alpha)) +
    geom_line(
        linewidth = 1.2,
        color = "grey25",
        lineend = "round"
    ) +
    scale_x_continuous(
        name = expression(alpha),
        expand = expansion(mult = c(0.02, 0.02))
    ) +
    scale_y_continuous(
        name = expression(R[alpha](T)),
        expand = expansion(mult = c(0.03, 0.03))
    ) +
    labs(
        title = "Curva de custo-complexidade",
        subtitle = "Representação ilustrativa"
    ) +
    theme_minimal(base_size = 15) +
    theme(
        panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color = "grey88", linewidth = 0.4),
        axis.title = element_text(size = 15),
        axis.text = element_text(size = 12),
        plot.title = element_text(face = "bold", size = 17),
        plot.subtitle = element_text(size = 12, color = "grey35")
    )


################################################################################

################################################################################
# Figura ilustrativa - versão mais seca para slide
################################################################################

library(ggplot2)

x11(width = 8, height = 5)

dados_cc <- data.frame(
    alpha   = c(0.00, 0.10, 0.22, 0.38, 0.58, 0.82, 1.10, 1.45),
    R_alpha = c(1.00, 0.90, 0.79, 0.68, 0.57, 0.48, 0.40, 0.34)
)

ggplot(dados_cc, aes(x = alpha, y = R_alpha)) +
    geom_line(
        linewidth = 0.8,
        color = "grey20"
    ) +
    geom_point(
        size = 2.6,
        color = "grey10"
    ) +
    scale_x_continuous(
        name = expression(alpha),
        breaks = dados_cc$alpha,
        expand = expansion(mult = c(0.02, 0.02))
    ) +
    scale_y_continuous(
        name = expression(R[alpha](T)),
        expand = expansion(mult = c(0.03, 0.03))
    )  +
    theme_classic(base_size = 15) +
    theme(
        axis.title = element_text(size = 15),
        axis.text = element_text(size = 11),
        plot.title = element_text(face = "bold", size = 17)
    )
