File size: 10,290 Bytes
48909ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""
Visualization module for the Business Intelligence Dashboard.

This module creates various types of charts and visualizations
using the Strategy Pattern for different chart types.
"""

from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Tuple, Any
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from utils import detect_column_types
from constants import (
    HISTOGRAM_BINS,
    MAX_CATEGORY_DISPLAY,
    MIN_NUMERICAL_COLUMNS_FOR_CORRELATION
)


class VisualizationStrategy(ABC):
    """Abstract base class for visualization strategies."""
    
    @abstractmethod
    def create_chart(
        self, 
        df: pd.DataFrame, 
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        **kwargs
    ) -> go.Figure:
        """
        Create a visualization.
        
        Args:
            df: Input DataFrame
            x_column: X-axis column
            y_column: Y-axis column
            aggregation: Aggregation method (sum, mean, count, median)
            **kwargs: Additional parameters
            
        Returns:
            Plotly figure object
        """
        pass


class TimeSeriesStrategy(VisualizationStrategy):
    """Strategy for creating time series plots."""
    
    def create_chart(
        self, 
        df: pd.DataFrame, 
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        **kwargs
    ) -> go.Figure:
        """Create time series plot."""
        if x_column is None or y_column is None:
            raise ValueError("Both x_column and y_column required for time series")
        
        # Convert date column
        df = df.copy()
        df[x_column] = pd.to_datetime(df[x_column], errors='coerce')
        df = df.dropna(subset=[x_column, y_column])
        
        # Aggregate if needed
        if aggregation != 'none':
            df = df.groupby(x_column)[y_column].agg(aggregation).reset_index()
        
        fig = px.line(
            df, 
            x=x_column, 
            y=y_column,
            title=f'Time Series: {y_column} over {x_column}',
            labels={x_column: x_column, y_column: y_column}
        )
        
        fig.update_layout(
            xaxis_title=x_column,
            yaxis_title=y_column,
            hovermode='x unified',
            template='plotly_white'
        )
        
        return fig


class DistributionStrategy(VisualizationStrategy):
    """Strategy for creating distribution plots."""
    
    def create_chart(
        self, 
        df: pd.DataFrame, 
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        sub_chart_type: str = 'histogram',
        **kwargs
    ) -> go.Figure:
        """Create distribution plot (histogram or box plot)."""
        if x_column is None:
            raise ValueError("x_column required for distribution plot")
        
        # Get sub_chart_type from kwargs if provided, otherwise use parameter
        # Check both 'sub_chart_type' (new) and 'chart_type' (legacy) for compatibility
        sub_chart_type = kwargs.pop('sub_chart_type', kwargs.pop('chart_type', sub_chart_type))
        
        df = df.copy()
        df = df.dropna(subset=[x_column])
        
        if sub_chart_type == 'histogram':
            fig = px.histogram(
                df,
                x=x_column,
                title=f'Distribution of {x_column}',
                labels={x_column: x_column, 'count': 'Frequency'},
                nbins=HISTOGRAM_BINS
            )
        else:  # box plot
            fig = px.box(
                df,
                y=x_column,
                title=f'Box Plot of {x_column}',
                labels={x_column: x_column}
            )
        
        fig.update_layout(
            template='plotly_white',
            showlegend=False
        )
        
        return fig


class CategoryAnalysisStrategy(VisualizationStrategy):
    """Strategy for creating category analysis charts."""
    
    def create_chart(
        self, 
        df: pd.DataFrame, 
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        sub_chart_type: str = 'bar',
        **kwargs
    ) -> go.Figure:
        """Create category analysis (bar chart or pie chart)."""
        if x_column is None:
            raise ValueError("x_column required for category analysis")
        
        # Get sub_chart_type from kwargs if provided, otherwise use parameter
        # Check both 'sub_chart_type' (new) and 'chart_type' (legacy) for compatibility
        sub_chart_type = kwargs.pop('sub_chart_type', kwargs.pop('chart_type', sub_chart_type))
        
        df = df.copy()
        df = df.dropna(subset=[x_column])
        
        if y_column:
            # Aggregate by category
            if aggregation != 'none':
                df_agg = df.groupby(x_column)[y_column].agg(aggregation).reset_index()
                df_agg.columns = [x_column, y_column]
            else:
                df_agg = df[[x_column, y_column]]
            
            # Sort by value
            df_agg = df_agg.sort_values(y_column, ascending=False).head(MAX_CATEGORY_DISPLAY)
            
            if sub_chart_type == 'bar':
                fig = px.bar(
                    df_agg,
                    x=x_column,
                    y=y_column,
                    title=f'{y_column} by {x_column}',
                    labels={x_column: x_column, y_column: y_column}
                )
            else:  # pie
                fig = px.pie(
                    df_agg,
                    names=x_column,
                    values=y_column,
                    title=f'{y_column} Distribution by {x_column}'
                )
        else:
            # Count by category
            value_counts = df[x_column].value_counts().head(MAX_CATEGORY_DISPLAY)
            
            if sub_chart_type == 'bar':
                fig = px.bar(
                    x=value_counts.index,
                    y=value_counts.values,
                    title=f'Count by {x_column}',
                    labels={'x': x_column, 'y': 'Count'}
                )
            else:  # pie
                fig = px.pie(
                    values=value_counts.values,
                    names=value_counts.index,
                    title=f'Distribution of {x_column}'
                )
        
        fig.update_layout(template='plotly_white')
        return fig


class ScatterStrategy(VisualizationStrategy):
    """Strategy for creating scatter plots."""
    
    def create_chart(
        self, 
        df: pd.DataFrame, 
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        color_column: Optional[str] = None,
        **kwargs
    ) -> go.Figure:
        """Create scatter plot."""
        if x_column is None or y_column is None:
            raise ValueError("Both x_column and y_column required for scatter plot")
        
        df = df.copy()
        df = df.dropna(subset=[x_column, y_column])
        
        fig = px.scatter(
            df,
            x=x_column,
            y=y_column,
            color=color_column,
            title=f'Scatter Plot: {y_column} vs {x_column}',
            labels={x_column: x_column, y_column: y_column},
            hover_data=df.columns.tolist()
        )
        
        fig.update_layout(template='plotly_white')
        return fig


class CorrelationHeatmapStrategy(VisualizationStrategy):
    """Strategy for creating correlation heatmaps."""
    
    def create_chart(
        self, 
        df: pd.DataFrame, 
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        **kwargs
    ) -> go.Figure:
        """Create correlation heatmap."""
        numerical, _, _ = detect_column_types(df)
        
        if len(numerical) < MIN_NUMERICAL_COLUMNS_FOR_CORRELATION:
            raise ValueError(
                f"Need at least {MIN_NUMERICAL_COLUMNS_FOR_CORRELATION} "
                "numerical columns for correlation"
            )
        
        corr_matrix = df[numerical].corr()
        
        fig = px.imshow(
            corr_matrix,
            title='Correlation Heatmap',
            labels=dict(x="Column", y="Column", color="Correlation"),
            color_continuous_scale='RdBu',
            aspect="auto"
        )
        
        fig.update_layout(template='plotly_white')
        return fig


class VisualizationFactory:
    """Factory class for creating visualizations using Strategy Pattern."""
    
    def __init__(self):
        """Initialize with visualization strategies."""
        self._strategies = {
            'time_series': TimeSeriesStrategy(),
            'distribution': DistributionStrategy(),
            'category': CategoryAnalysisStrategy(),
            'scatter': ScatterStrategy(),
            'correlation': CorrelationHeatmapStrategy()
        }
    
    def create_visualization(
        self,
        chart_type: str,
        df: pd.DataFrame,
        x_column: Optional[str] = None,
        y_column: Optional[str] = None,
        aggregation: str = 'sum',
        **kwargs
    ) -> go.Figure:
        """
        Create visualization using appropriate strategy.
        
        Args:
            chart_type: Type of chart to create
            df: Input DataFrame
            x_column: X-axis column
            y_column: Y-axis column
            aggregation: Aggregation method
            **kwargs: Additional parameters
            
        Returns:
            Plotly figure object
        """
        if chart_type not in self._strategies:
            raise ValueError(f"Unknown chart type: {chart_type}")
        
        strategy = self._strategies[chart_type]
        return strategy.create_chart(
            df, 
            x_column=x_column, 
            y_column=y_column,
            aggregation=aggregation,
            **kwargs
        )