File size: 7,256 Bytes
d1ae699
 
f7d9f2d
d1ae699
 
 
81b031b
 
f7d9f2d
81b031b
dcae7f9
8ec449d
dcae7f9
f7d9f2d
944bc86
dcae7f9
9b66796
 
dcae7f9
81b031b
 
 
dcae7f9
 
735010b
81b031b
 
dcae7f9
9b66796
944bc86
dcae7f9
9b66796
 
944bc86
 
9b66796
4b10064
9b66796
 
dcae7f9
4b10064
9b66796
 
f7d9f2d
 
dcae7f9
9b66796
4b10064
9b66796
 
4b10064
9b66796
4b10064
 
 
9b66796
4b10064
944bc86
4b10064
d1ae699
f7d9f2d
81b031b
f7d9f2d
dcae7f9
8ec449d
dcae7f9
4b10064
 
 
 
735010b
81b031b
4b10064
9b66796
735010b
f7d9f2d
c4a9b3e
dcae7f9
9b66796
 
 
4b10064
f7d9f2d
 
a791ab7
9b66796
4b10064
a791ab7
735010b
 
 
f7d9f2d
9b66796
86e4e85
f7d9f2d
81b031b
 
dcae7f9
9b66796
735010b
dcae7f9
f7d9f2d
8ec449d
81b031b
9b66796
d1ae699
81b031b
d1ae699
9b66796
f7d9f2d
944bc86
81b031b
9b66796
86e4e85
 
76038a5
81b031b
a791ab7
 
 
f7d9f2d
81b031b
 
7167a40
81b031b
f7d9f2d
a791ab7
f7d9f2d
81b031b
 
f7d9f2d
 
81b031b
f7d9f2d
5d6ace3
81b031b
f7d9f2d
 
86e4e85
f7d9f2d
81b031b
e45c34b
 
f7d9f2d
4b10064
f7d9f2d
4b10064
f7d9f2d
735010b
944bc86
 
f7d9f2d
eebd9e7
9b66796
944bc86
81b031b
dcae7f9
 
 
 
f7d9f2d
 
 
 
86e4e85
f7d9f2d
 
 
 
 
 
 
dcae7f9
f7d9f2d
 
 
 
 
 
 
 
dcae7f9
f7d9f2d
 
 
 
 
 
 
dcae7f9
f7d9f2d
 
9b66796
f7d9f2d
dcae7f9
f7d9f2d
 
 
9b66796
f7d9f2d
 
 
 
9b66796
f7d9f2d
9b66796
f7d9f2d
9b66796
f7d9f2d
bdb968f
 
 
f7d9f2d
 
 
 
 
 
bdb968f
f7d9f2d
bdb968f
f7d9f2d
 
 
bdb968f
 
f7d9f2d
 
 
 
 
 
9b66796
f7d9f2d
 
9b66796
f7d9f2d
bdb968f
f7d9f2d
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
#!/usr/bin/env python3
"""
Plotly Express Test Interface - Try Different Examples
"""

import gradio as gr

def create_pyodide_interface():
    """Simple interface to test different Express examples"""
    
    pyodide_html = '''
    <div id="pyodide-container" style="border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin: 10px 0;">
        <div id="status" style="font-weight: bold; padding: 10px; background: #f0f0f0; border-radius: 3px;">
            πŸ”„ Loading Pyodide...
        </div>
        <div id="output" style="display:none; margin-top: 10px;">
            <h4>Output:</h4>
            <pre id="text-output" style="background: #f8f8f8; padding: 10px; border-radius: 3px; max-height: 200px; overflow-y: auto;"></pre>
            <div id="plots" style="margin-top: 15px;"></div>
        </div>
    </div>
    
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script src="https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js"></script>
    
    <script>
        let pyodide = null;
        let ready = false;
        let plotCount = 0;
        
        function updateStatus(msg, color = 'black') {
            document.getElementById('status').innerHTML = msg;
            document.getElementById('status').style.color = color;
        }
        
        window.createPlot = function(data, layout) {
            try {
                plotCount++;
                const plotId = 'plot-' + plotCount;
                const plotsDiv = document.getElementById('plots');
                
                const plotDiv = document.createElement('div');
                plotDiv.innerHTML = `
                    <h5>πŸ“Š Plot ${plotCount}</h5>
                    <div id="${plotId}" style="width: 100%; height: 400px; border: 1px solid #ccc; margin: 10px 0;"></div>
                `;
                plotsDiv.appendChild(plotDiv);
                
                if (typeof data === 'string') data = JSON.parse(data);
                if (typeof layout === 'string') layout = JSON.parse(layout);
                
                Plotly.newPlot(plotId, data, layout, {responsive: true});
                return true;
                
            } catch (error) {
                console.error('Plot error:', error);
                return false;
            }
        };
        
        async function init() {
            try {
                updateStatus('πŸ”„ Loading...', 'blue');
                pyodide = await loadPyodide();
                
                await pyodide.loadPackage(['numpy', 'pandas', 'micropip']);
                await pyodide.runPythonAsync(`
                    import micropip
                    await micropip.install('plotly')
                `);
                
                pyodide.runPython(`
import json
from js import createPlot

def show_plot(fig):
    try:
        fig_dict = fig.to_dict()
        data_json = json.dumps(fig_dict.get('data', []))
        layout_json = json.dumps(fig_dict.get('layout', {}))
        success = createPlot(data_json, layout_json)
        if success:
            print("Plot displayed!")
        return success
    except Exception as e:
        print(f"Plot error: {e}")
        return False

try:
    import plotly.graph_objects as go
    import plotly.express as px
    go.Figure.show = lambda self, *args, **kwargs: show_plot(self)
    print("Plotly ready!")
except Exception as e:
    print(f"Setup error: {e}")
                `);
                
                ready = true;
                updateStatus('βœ… Ready!', 'green');
                
                document.getElementById('output').style.display = 'block';
                document.getElementById('text-output').textContent = 'Ready to test Plotly Express examples!';
                
            } catch (error) {
                updateStatus('❌ Error: ' + error.message, 'red');
            }
        }
        
        async function runCode(code) {
            if (!ready) return 'Not ready';
            
            try {
                updateStatus('▢️ Running...', 'blue');
                
                document.getElementById('plots').innerHTML = '';
                
                pyodide.runPython(`
import sys
from io import StringIO
old_stdout = sys.stdout
sys.stdout = capture = StringIO()
                `);
                
                pyodide.runPython(code);
                
                let output = pyodide.runPython(`
sys.stdout = old_stdout
capture.getvalue()
                `);
                
                document.getElementById('text-output').textContent = output || 'Code executed';
                updateStatus('βœ… Done', 'green');
                
                return output || 'Success';
                
            } catch (error) {
                const err = 'Error: ' + error.toString();
                document.getElementById('text-output').textContent = err;
                updateStatus('❌ Error', 'red');
                return err;
            }
        }
        
        function waitForCDN() {
            if (typeof loadPyodide !== 'undefined' && typeof Plotly !== 'undefined') {
                init();
            } else {
                setTimeout(waitForCDN, 1000);
            }
        }
        
        waitForCDN();
        
        window.runCode = runCode;
        
    </script>
    '''
    
    return pyodide_html

# Example templates
examples = {
    "Minimal Test": '''# Absolute minimal test
import plotly.express as px

print("Testing minimal Express...")
fig = px.scatter(x=[1, 2], y=[1, 2], title="Minimal")
fig.show()
print("Minimal test complete!")''',
    
    "Direct Arrays": '''# Test without DataFrame
import plotly.express as px

print("Testing direct arrays...")
fig = px.scatter(x=[1, 2, 3, 4], y=[1, 4, 9, 16], title="Direct Arrays")
fig.show()
print("Direct arrays test complete!")''',
    
    "Simple DataFrame": '''# Simple DataFrame test
import plotly.express as px
import pandas as pd

print("Creating DataFrame...")
df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [2, 4, 6, 8, 10]
})
print("DataFrame:")
print(df)

print("Creating plot...")
fig = px.scatter(df, x='x', y='y', title='DataFrame Test')
fig.show()
print("DataFrame test complete!")''',
    
    "Line Chart": '''# Line chart test
import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [1, 4, 2, 8, 5]
})

fig = px.line(df, x='x', y='y', title='Line Chart')
fig.show()
print("Line chart complete!")''',
    
    "Bar Chart": '''# Bar chart test
import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    'category': ['A', 'B', 'C', 'D'],
    'values': [20, 35, 30, 25]
})

fig = px.bar(df, x='category', y='values', title='Bar Chart')
fig.show()
print("Bar chart complete!")''',
    
    "Data Types": '''# Test different data types
import plotly.express as px
import pandas as pd
import numpy as np

print("Creating mixed data types...")
df = pd.DataFrame({
    'int_col': [1, 2, 3, 4],
    'float_col': [1.1, 2.2, 3.3, 4.4], 
    'numpy_col': np.array([1, 2, 3, 4])
})

print("DataFrame info:")
print(df.dtypes)

fig = px.scatter(df, x='int_col', y='float_col', title='Data Types')
fig.show()
print("Data typ