File size: 5,009 Bytes
71175ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import os
import pandas as pd
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
from rpy2.robjects.packages import importr
import matplotlib.pyplot as plt

# Configuraci贸n de temas y estilos en R
def configurar_estilos_r():
    """Configura temas y estilos globales para ggplot2"""
    ro.r("""
    library(ggplot2)
    library(RColorBrewer)
    
    # Tema personalizado
    tema_personalizado <- theme_minimal() +
        theme(
            text = element_text(family = "sans", size = 12),
            plot.title = element_text(size = 16, face = "bold", hjust = 0.5),
            plot.subtitle = element_text(size = 12, hjust = 0.5),
            axis.title = element_text(face = "bold"),
            legend.position = "top",
            panel.grid.major = element_line(color = "gray90"),
            panel.grid.minor = element_blank(),
            plot.margin = unit(c(1, 1, 1, 1), "cm")
        )
    
    # Paleta de colores
    colores <- brewer.pal(8, "Set2")
    """)

# Configurar estilos al importar el m贸dulo
configurar_estilos_r()

def generar_histograma_r(df: pd.DataFrame, columna: str, output_path: str) -> str:
    """
    Genera un histograma estilizado con ggplot2
    """
    try:
        with localconverter(ro.default_converter + pandas2ri.converter):
            r_df = ro.conversion.py2rpy(df[[columna]])
        
        ro.r(f"""
        library(ggplot2)
        p <- ggplot({r_df.r_repr()}, aes(x={columna})) +
            geom_histogram(
                binwidth = diff(range({r_df.r_repr()}${columna}, na.rm=TRUE))/30,
                fill = "#2c7fb8", 
                color = "#ffffff", 
                alpha = 0.8
            ) +
            labs(
                title = "Distribuci贸n de {columna}",
                x = "{columna}",
                y = "Frecuencia"
            ) +
            tema_personalizado +
            scale_fill_brewer(palette = "Set2")
        
        ggsave(
            filename = "{output_path}",
            plot = p,
            width = 10,
            height = 6,
            dpi = 300
        )
        """)
        
        return output_path if os.path.exists(output_path) else None
    
    except Exception as e:
        print(f"Error al generar histograma: {e}")
        return None


def generar_barras_r(df: pd.DataFrame, columna: str, output_path: str) -> str:
    """
    Genera gr谩fico de barras para variables categ贸ricas
    """
    try:
        with localconverter(ro.default_converter + pandas2ri.converter):
            r_df = ro.conversion.py2rpy(df[[columna]])
        
        ro.r(f"""
        library(ggplot2)
        library(dplyr)
        
        top_data <- {r_df.r_repr()} %>%
            group_by({columna}) %>%
            summarise(count = n()) %>%
            arrange(desc(count)) %>%
            head(10)
        
        p <- ggplot(top_data, aes(
                x = reorder({columna}, count), 
                y = count,
                fill = {columna}
            )) +
            geom_bar(stat = "identity") +
            coord_flip() +
            labs(
                title = "Top 10 categor铆as en {columna}",
                x = "",
                y = "Conteo"
            ) +
            tema_personalizado +
            scale_fill_brewer(palette = "Set2") +
            theme(legend.position = "none")
        
        ggsave(
            filename = "{output_path}",
            plot = p,
            width = 10,
            height = 6,
            dpi = 300
        )
        """)
        
        return output_path if os.path.exists(output_path) else None
    
    except Exception as e:
        print(f"Error al generar gr谩fico de barras: {e}")
        return None


def generar_boxplot_r(df: pd.DataFrame, columna: str, grupo: str, output_path: str) -> str:
    """
    Genera boxplot comparativo por grupos
    """
    try:
        with localconverter(ro.default_converter + pandas2ri.converter):
            r_df = ro.conversion.py2rpy(df[[columna, grupo]])
        
        ro.r(f"""
        p <- ggplot({r_df.r_repr()}, aes(
                x = {grupo}, 
                y = {columna},
                fill = {grupo}
            )) +
            geom_boxplot(
                alpha = 0.7,
                outlier.color = "#e34a33"
            ) +
            labs(
                title = "Distribuci贸n de {columna} por {grupo}",
                x = "{grupo}",
                y = "{columna}"
            ) +
            tema_personalizado +
            scale_fill_brewer(palette = "Set2") +
            theme(axis.text.x = element_text(angle = 45, hjust = 1))
        
        ggsave(
            filename = "{output_path}",
            plot = p,
            width = 10,
            height = 6,
            dpi = 300
        )
        """)
        
        return output_path if os.path.exists(output_path) else None
    
    except Exception as e:
        print(f"Error al generar boxplot: {e}")
        return None