bintangyosua commited on
Commit
c54fba5
·
verified ·
1 Parent(s): 22a1c62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +347 -406
app.py CHANGED
@@ -1,406 +1,347 @@
1
- import marimo
2
-
3
- __generated_with = "0.9.14"
4
- app = marimo.App(width="full")
5
-
6
-
7
- @app.cell(hide_code=True)
8
- def __(mo):
9
- mo.md(
10
- """
11
- # Political Ideologies Analysis
12
-
13
- This project provides a detailed analysis of political ideologies using data from the Huggingface Political Ideologies dataset. The code leverages various data science libraries and visualization tools to map, analyze, and visualize political ideology text data.
14
- Project Structure
15
-
16
- This analysis is based on huggingface dataset repository. <br>
17
- You can visit right [here](https://huggingface.co/datasets/JyotiNayak/political_ideologies)
18
- """
19
- )
20
- return
21
-
22
-
23
- @app.cell(hide_code=True)
24
- def __():
25
- import marimo as mo
26
- import pandas as pd
27
- import numpy as np
28
-
29
- import matplotlib.pyplot as plt
30
- import seaborn as sns
31
- import altair as alt
32
-
33
- from gensim.models import Word2Vec
34
- from sklearn.manifold import TSNE
35
-
36
- import tensorflow as tf
37
- from tensorflow.keras.models import Sequential
38
- from tensorflow.keras.layers import Embedding, Bidirectional, LSTM, Dense
39
-
40
- mo.md("""
41
- ## 1. Import all libraries needed
42
-
43
- The initial cells import the necessary libraries for data handling, visualization, and word embedding.
44
- """)
45
- return (
46
- Bidirectional,
47
- Dense,
48
- Embedding,
49
- LSTM,
50
- Sequential,
51
- TSNE,
52
- Word2Vec,
53
- alt,
54
- mo,
55
- np,
56
- pd,
57
- plt,
58
- sns,
59
- tf,
60
- )
61
-
62
-
63
- @app.cell(hide_code=True)
64
- def __(mo):
65
- mo.md(
66
- """
67
- Here are the mapped of label and issue type columns.
68
-
69
- ```yaml
70
- Label Mapping: {'conservative': 0, 'liberal': 1 }
71
- Issue Type Mapping: {
72
- 'economic': 0, 'environmental': 1,
73
- 'family/gender': 2, 'geo-political and foreign policy': 3,
74
- 'political': 4, 'racial justice and immigration': 5,
75
- 'religious': 6, 'social, health and education': 7
76
- }
77
- ```
78
- """
79
- )
80
- return
81
-
82
-
83
- @app.cell(hide_code=True)
84
- def __(mo, pd):
85
- df = pd.concat(
86
- [pd.read_parquet(f'{name}.parquet') for name in ['train', 'val', 'test']],
87
- axis=0,
88
- )
89
-
90
- df = df.drop('__index_level_0__', axis=1)
91
-
92
- mo.md("""
93
- ## 2. Dataset Loading
94
-
95
- The dataset files (`train.parquet`, `val.parquet`, and `test.parquet`) are loaded, concatenated, and cleaned to form a single DataFrame (df). Columns are mapped to readable labels for ease of understanding.
96
- """)
97
- return (df,)
98
-
99
-
100
- @app.cell(hide_code=True)
101
- def __():
102
- label_mapping = {
103
- 'conservative': 0,
104
- 'liberal': 1
105
- }
106
-
107
- issue_type_mapping = {
108
- 'economic': 0,
109
- 'environmental': 1,
110
- 'family/gender': 2,
111
- 'geo-political and foreign policy': 3,
112
- 'political': 4,
113
- 'racial justice and immigration': 5,
114
- 'religious': 6,
115
- 'social, health and education': 7
116
- }
117
- return issue_type_mapping, label_mapping
118
-
119
-
120
- @app.cell(hide_code=True)
121
- def __(issue_type_mapping, label_mapping):
122
- label_mapping_reversed = {v: k for k, v in label_mapping.items()}
123
- issue_type_mapping_reversed = {v: k for k, v in issue_type_mapping.items()}
124
-
125
- print(label_mapping_reversed)
126
- print(issue_type_mapping_reversed)
127
- return issue_type_mapping_reversed, label_mapping_reversed
128
-
129
-
130
- @app.cell(hide_code=True)
131
- def __(df, issue_type_mapping_reversed, label_mapping_reversed, mo):
132
- df['label_text'] = df['label'].replace(label_mapping_reversed)
133
- df['issue_type_text'] = df['issue_type'].replace(issue_type_mapping_reversed)
134
-
135
- labels_grouped = df['label_text'].value_counts().rename_axis('label_text').reset_index(name='counts')
136
- issue_types_grouped = (
137
- df["issue_type_text"]
138
- .value_counts()
139
- .rename_axis("issue_type_text")
140
- .reset_index(name="counts")
141
- )
142
-
143
- mo.md("""
144
- ## 3. Mapping Labels and Issue Types
145
-
146
- Two dictionaries map labels (conservative and liberal) and issue types (e.g., economic, environmental, etc.) to numerical values for machine learning purposes. Reversed mappings are created to convert numerical labels back into their text form.
147
- """)
148
- return issue_types_grouped, labels_grouped
149
-
150
-
151
- @app.cell(hide_code=True)
152
- def __(df):
153
- df.iloc[:, :6].head(7)
154
- return
155
-
156
-
157
- @app.cell(hide_code=True)
158
- def __(mo):
159
- mo.md(
160
- """
161
- ## 4. Visualizing Data Distributions
162
-
163
- Bar plots visualize the proportions of conservative vs. liberal ideologies and the count of different issue types. These provide an overview of the dataset composition.
164
- """
165
- )
166
- return
167
-
168
-
169
- @app.cell(hide_code=True)
170
- def __(alt, labels_grouped, mo):
171
- mo.ui.altair_chart(
172
- alt.Chart(labels_grouped).mark_bar(
173
- fill='#4C78A8',
174
- cursor='pointer',
175
- ).encode(
176
- x=alt.X('label_text', axis=alt.Axis(labelAngle=0)),
177
- y='counts:Q'
178
- )
179
- )
180
- return
181
-
182
-
183
- @app.cell(hide_code=True)
184
- def __(alt, issue_types_grouped, mo):
185
- mo.ui.altair_chart(
186
- alt.Chart(issue_types_grouped)
187
- .mark_bar(
188
- fill="#4C78A8",
189
- cursor="pointer",
190
- )
191
- .encode(
192
- x=alt.X(
193
- "issue_type_text:O",
194
- axis=alt.Axis(
195
- labelAngle=-10, labelAlign="center", labelPadding=10
196
- ),
197
- ),
198
- y="counts:Q",
199
- )
200
- )
201
- return
202
-
203
-
204
- @app.cell(hide_code=True)
205
- def __(mo):
206
- mo.md(
207
- """
208
- ## 5. Word Embedding with Word2Vec
209
-
210
- Using Word2Vec, word embeddings are created from text statements in the dataset. The model trains on tokenized sentences, generating a 100-dimensional embedding for each word. Statements are averaged to form document-level embeddings.
211
- """
212
- )
213
- return
214
-
215
-
216
- @app.cell(hide_code=True)
217
- def __(Word2Vec, df):
218
- df['tokens'] = df['statement'].apply(lambda x: x.lower().split())
219
- word2vec_model = Word2Vec(sentences=df['tokens'], vector_size=100, window=5, min_count=1, seed=0)
220
- return (word2vec_model,)
221
-
222
-
223
- @app.cell(hide_code=True)
224
- def __(np, word2vec_model):
225
- def get_doc_embedding(tokens):
226
- vectors = [word2vec_model.wv[word] for word in tokens if word in word2vec_model.wv]
227
- if vectors:
228
- return np.mean(vectors, axis=0)
229
- else:
230
- return np.zeros(word2vec_model.vector_size)
231
- return (get_doc_embedding,)
232
-
233
-
234
- @app.cell(hide_code=True)
235
- def __(df, get_doc_embedding, np):
236
- df['embedding'] = df['tokens'].apply(get_doc_embedding)
237
- embeddings_matrix = np.vstack(df['embedding'].values)
238
- return (embeddings_matrix,)
239
-
240
-
241
- @app.cell(hide_code=True)
242
- def __(mo):
243
- mo.md(
244
- """
245
- ## 6. Dimensionality Reduction with TSNE
246
-
247
- Embeddings are projected into a 2D space using TSNE for visualization. The embeddings are colored by issue type, showing clusters of similar statements.
248
- """
249
- )
250
- return
251
-
252
-
253
- @app.cell(hide_code=True)
254
- def __(TSNE, alt, df, embeddings_matrix, plt, sns):
255
- tsne = TSNE(n_components=2, random_state=0)
256
- tsne_results = tsne.fit_transform(embeddings_matrix)
257
- df['x'] = tsne_results[:, 0]
258
- df['y'] = tsne_results[:, 1]
259
-
260
- # Brush for selection
261
- brush = alt.selection_interval()
262
- size = 350
263
-
264
- plt.figure(figsize=(10, 6))
265
- sns.scatterplot(data=df, x='x', y='y', hue='issue_type_text', palette='Set1', s=100)
266
- plt.title("2D Visualization of Text Data by Ideology (Word2Vec Embeddings)")
267
- plt.xlabel("t-SNE Dimension 1")
268
- plt.ylabel("t-SNE Dimension 2")
269
- plt.legend(title='Ideology')
270
- plt.show()
271
- return brush, size, tsne, tsne_results
272
-
273
-
274
- @app.cell(hide_code=True)
275
- def __(mo):
276
- mo.md(
277
- """
278
- ## 7. Interactive Visualizations
279
-
280
- Interactive scatter plots in Altair show ideology and issue types in 2D space. A brush selection tool allows users to explore specific points and view tooltip information.
281
-
282
- ### Combined Scatter Plot
283
-
284
- Combines the two scatter plots into a side-by-side visualization for direct comparison of ideologies vs. issue types.
285
- Running the Code
286
-
287
- Run the code using the marimo.App instance. This notebook can also be run as a standalone Python script:
288
- """
289
- )
290
- return
291
-
292
-
293
- @app.cell(hide_code=True)
294
- def __(alt, brush, df, mo, size):
295
- points1 = alt.Chart(df, height=size, width=size).mark_point().encode(
296
- x='x:Q',
297
- y='y:Q',
298
- color=alt.condition(brush, 'label_text', alt.value('grey')),
299
- tooltip=['x:Q', 'y:Q', 'statement:N', 'label_text:N']
300
- ).add_params(brush).properties(title='By Political Ideologies')
301
-
302
- scatter_chart1 = mo.ui.altair_chart(points1)
303
-
304
- points2 = alt.Chart(df, height=size, width=size).mark_point().encode(
305
- x='x:Q',
306
- y='y:Q',
307
- color=alt.condition(brush, 'issue_type_text', alt.value('grey')),
308
- tooltip=['x:Q', 'y:Q', 'statement:N', 'issue_type:N']
309
- ).add_params(brush).properties(title='By Issue Types')
310
-
311
- scatter_chart2 = mo.ui.altair_chart(points2)
312
-
313
- combined_chart = (scatter_chart1 | scatter_chart2)
314
- combined_chart
315
- return combined_chart, points1, points2, scatter_chart1, scatter_chart2
316
-
317
-
318
- @app.cell(hide_code=True)
319
- def __(combined_chart):
320
- combined_chart.value[['statement', 'label_text', 'issue_type_text']]
321
- return
322
-
323
-
324
- @app.cell(hide_code=True)
325
- def __(combined_chart):
326
- combined_chart.value['statement']
327
- return
328
-
329
-
330
- @app.cell(hide_code=True)
331
- def __(mo):
332
- mo.md(
333
- r"""
334
- ## Data Insights
335
-
336
- - Ideology Distribution: Visualizes proportions of conservative and liberal ideologies.
337
- - Issue Types: Bar plot reveals the diversity and frequency of issue types in the dataset.
338
- - Word Embeddings: Using TSNE for 2D projections helps identify clusters in political statements.
339
- - Interactive Exploration: Offers detailed, interactive views on ideology vs. issue type distribution.
340
-
341
- This code provides a thorough analysis pipeline, from data loading to interactive visualizations, enabling an in-depth exploration of political ideologies.
342
- """
343
- )
344
- return
345
-
346
-
347
- @app.cell
348
- def __(mo):
349
- mo.md(r"""## Building Bidirection LSTM Model""")
350
- return
351
-
352
-
353
- @app.cell
354
- def __():
355
- max_length = 100
356
- embedding_dim = 100
357
- num_classes = 2
358
- return embedding_dim, max_length, num_classes
359
-
360
-
361
- @app.cell
362
- def __(
363
- Bidirectional,
364
- Dense,
365
- Embedding,
366
- LSTM,
367
- Sequential,
368
- embedding_dim,
369
- max_length,
370
- num_classes,
371
- word2vec_model,
372
- ):
373
- model = Sequential()
374
- model.add(Embedding(input_dim=len(word2vec_model.wv.index_to_key), output_dim=embedding_dim, input_length=max_length))
375
- model.add(Bidirectional(LSTM(64, return_sequences=False)))
376
- model.add(Dense(num_classes, activation='softmax'))
377
- return (model,)
378
-
379
-
380
- @app.cell
381
- def __(model):
382
- model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
383
- model.summary()
384
- return
385
-
386
-
387
- @app.cell
388
- def __(df, np):
389
- X = np.vstack(df['embedding'].values)
390
- y = df['label'].values
391
- return X, y
392
-
393
-
394
- @app.cell
395
- def __(X, model, y):
396
- model.fit(X, y, epochs=10, batch_size=32, validation_split=0.2)
397
- return
398
-
399
-
400
- @app.cell
401
- def __():
402
- return
403
-
404
-
405
- if __name__ == "__main__":
406
- app.run()
 
1
+ import marimo
2
+
3
+ __generated_with = "0.9.14"
4
+ app = marimo.App(width="full")
5
+
6
+
7
+ @app.cell(hide_code=True)
8
+ def __(mo):
9
+ mo.md(
10
+ """
11
+ # Political Ideologies Analysis
12
+
13
+ This project provides a detailed analysis of political ideologies using data from the Huggingface Political Ideologies dataset. The code leverages various data science libraries and visualization tools to map, analyze, and visualize political ideology text data.
14
+ Project Structure
15
+
16
+ This analysis is based on huggingface dataset repository. <br>
17
+ You can visit right [here](https://huggingface.co/datasets/JyotiNayak/political_ideologies)
18
+ """
19
+ )
20
+ return
21
+
22
+
23
+ @app.cell(hide_code=True)
24
+ def __():
25
+ import marimo as mo
26
+ import pandas as pd
27
+ import numpy as np
28
+
29
+ import matplotlib.pyplot as plt
30
+ import seaborn as sns
31
+ import altair as alt
32
+
33
+ from gensim.models import Word2Vec
34
+ from sklearn.manifold import TSNE
35
+
36
+ import tensorflow as tf
37
+ from tensorflow.keras.models import Sequential
38
+ from tensorflow.keras.layers import Embedding, Bidirectional, LSTM, Dense
39
+
40
+ mo.md("""
41
+ ## 1. Import all libraries needed
42
+
43
+ The initial cells import the necessary libraries for data handling, visualization, and word embedding.
44
+ """)
45
+ return (
46
+ Bidirectional,
47
+ Dense,
48
+ Embedding,
49
+ LSTM,
50
+ Sequential,
51
+ TSNE,
52
+ Word2Vec,
53
+ alt,
54
+ mo,
55
+ np,
56
+ pd,
57
+ plt,
58
+ sns,
59
+ tf,
60
+ )
61
+
62
+
63
+ @app.cell(hide_code=True)
64
+ def __(mo):
65
+ mo.md(
66
+ """
67
+ Here are the mapped of label and issue type columns.
68
+
69
+ ```yaml
70
+ Label Mapping: {'conservative': 0, 'liberal': 1 }
71
+ Issue Type Mapping: {
72
+ 'economic': 0, 'environmental': 1,
73
+ 'family/gender': 2, 'geo-political and foreign policy': 3,
74
+ 'political': 4, 'racial justice and immigration': 5,
75
+ 'religious': 6, 'social, health and education': 7
76
+ }
77
+ ```
78
+ """
79
+ )
80
+ return
81
+
82
+
83
+ @app.cell(hide_code=True)
84
+ def __(mo, pd):
85
+ df = pd.concat(
86
+ [pd.read_parquet(f'{name}.parquet') for name in ['train', 'val', 'test']],
87
+ axis=0,
88
+ )
89
+
90
+ df = df.drop('__index_level_0__', axis=1)
91
+
92
+ mo.md("""
93
+ ## 2. Dataset Loading
94
+
95
+ The dataset files (`train.parquet`, `val.parquet`, and `test.parquet`) are loaded, concatenated, and cleaned to form a single DataFrame (df). Columns are mapped to readable labels for ease of understanding.
96
+ """)
97
+ return (df,)
98
+
99
+
100
+ @app.cell(hide_code=True)
101
+ def __():
102
+ label_mapping = {
103
+ 'conservative': 0,
104
+ 'liberal': 1
105
+ }
106
+
107
+ issue_type_mapping = {
108
+ 'economic': 0,
109
+ 'environmental': 1,
110
+ 'family/gender': 2,
111
+ 'geo-political and foreign policy': 3,
112
+ 'political': 4,
113
+ 'racial justice and immigration': 5,
114
+ 'religious': 6,
115
+ 'social, health and education': 7
116
+ }
117
+ return issue_type_mapping, label_mapping
118
+
119
+
120
+ @app.cell(hide_code=True)
121
+ def __(issue_type_mapping, label_mapping):
122
+ label_mapping_reversed = {v: k for k, v in label_mapping.items()}
123
+ issue_type_mapping_reversed = {v: k for k, v in issue_type_mapping.items()}
124
+
125
+ print(label_mapping_reversed)
126
+ print(issue_type_mapping_reversed)
127
+ return issue_type_mapping_reversed, label_mapping_reversed
128
+
129
+
130
+ @app.cell(hide_code=True)
131
+ def __(df, issue_type_mapping_reversed, label_mapping_reversed, mo):
132
+ df['label_text'] = df['label'].replace(label_mapping_reversed)
133
+ df['issue_type_text'] = df['issue_type'].replace(issue_type_mapping_reversed)
134
+
135
+ labels_grouped = df['label_text'].value_counts().rename_axis('label_text').reset_index(name='counts')
136
+ issue_types_grouped = (
137
+ df["issue_type_text"]
138
+ .value_counts()
139
+ .rename_axis("issue_type_text")
140
+ .reset_index(name="counts")
141
+ )
142
+
143
+ mo.md("""
144
+ ## 3. Mapping Labels and Issue Types
145
+
146
+ Two dictionaries map labels (conservative and liberal) and issue types (e.g., economic, environmental, etc.) to numerical values for machine learning purposes. Reversed mappings are created to convert numerical labels back into their text form.
147
+ """)
148
+ return issue_types_grouped, labels_grouped
149
+
150
+
151
+ @app.cell(hide_code=True)
152
+ def __(df):
153
+ df.iloc[:, :6].head(7)
154
+ return
155
+
156
+
157
+ @app.cell(hide_code=True)
158
+ def __(mo):
159
+ mo.md(
160
+ """
161
+ ## 4. Visualizing Data Distributions
162
+
163
+ Bar plots visualize the proportions of conservative vs. liberal ideologies and the count of different issue types. These provide an overview of the dataset composition.
164
+ """
165
+ )
166
+ return
167
+
168
+
169
+ @app.cell(hide_code=True)
170
+ def __(alt, labels_grouped, mo):
171
+ mo.ui.altair_chart(
172
+ alt.Chart(labels_grouped).mark_bar(
173
+ fill='#4C78A8',
174
+ cursor='pointer',
175
+ ).encode(
176
+ x=alt.X('label_text', axis=alt.Axis(labelAngle=0)),
177
+ y='counts:Q'
178
+ )
179
+ )
180
+ return
181
+
182
+
183
+ @app.cell(hide_code=True)
184
+ def __(alt, issue_types_grouped, mo):
185
+ mo.ui.altair_chart(
186
+ alt.Chart(issue_types_grouped)
187
+ .mark_bar(
188
+ fill="#4C78A8",
189
+ cursor="pointer",
190
+ )
191
+ .encode(
192
+ x=alt.X(
193
+ "issue_type_text:O",
194
+ axis=alt.Axis(
195
+ labelAngle=-10, labelAlign="center", labelPadding=10
196
+ ),
197
+ ),
198
+ y="counts:Q",
199
+ )
200
+ )
201
+ return
202
+
203
+
204
+ @app.cell(hide_code=True)
205
+ def __(mo):
206
+ mo.md(
207
+ """
208
+ ## 5. Word Embedding with Word2Vec
209
+
210
+ Using Word2Vec, word embeddings are created from text statements in the dataset. The model trains on tokenized sentences, generating a 100-dimensional embedding for each word. Statements are averaged to form document-level embeddings.
211
+ """
212
+ )
213
+ return
214
+
215
+
216
+ @app.cell(hide_code=True)
217
+ def __(Word2Vec, df):
218
+ df['tokens'] = df['statement'].apply(lambda x: x.lower().split())
219
+ word2vec_model = Word2Vec(sentences=df['tokens'], vector_size=100, window=5, min_count=1, seed=0)
220
+ return (word2vec_model,)
221
+
222
+
223
+ @app.cell(hide_code=True)
224
+ def __(np, word2vec_model):
225
+ def get_doc_embedding(tokens):
226
+ vectors = [word2vec_model.wv[word] for word in tokens if word in word2vec_model.wv]
227
+ if vectors:
228
+ return np.mean(vectors, axis=0)
229
+ else:
230
+ return np.zeros(word2vec_model.vector_size)
231
+ return (get_doc_embedding,)
232
+
233
+
234
+ @app.cell(hide_code=True)
235
+ def __(df, get_doc_embedding, np):
236
+ df['embedding'] = df['tokens'].apply(get_doc_embedding)
237
+ embeddings_matrix = np.vstack(df['embedding'].values)
238
+ return (embeddings_matrix,)
239
+
240
+
241
+ @app.cell(hide_code=True)
242
+ def __(mo):
243
+ mo.md(
244
+ """
245
+ ## 6. Dimensionality Reduction with TSNE
246
+
247
+ Embeddings are projected into a 2D space using TSNE for visualization. The embeddings are colored by issue type, showing clusters of similar statements.
248
+ """
249
+ )
250
+ return
251
+
252
+
253
+ @app.cell(hide_code=True)
254
+ def __(TSNE, alt, df, embeddings_matrix, plt, sns):
255
+ tsne = TSNE(n_components=2, random_state=0)
256
+ tsne_results = tsne.fit_transform(embeddings_matrix)
257
+ df['x'] = tsne_results[:, 0]
258
+ df['y'] = tsne_results[:, 1]
259
+
260
+ # Brush for selection
261
+ brush = alt.selection_interval()
262
+ size = 350
263
+
264
+ plt.figure(figsize=(10, 6))
265
+ sns.scatterplot(data=df, x='x', y='y', hue='issue_type_text', palette='Set1', s=100)
266
+ plt.title("2D Visualization of Text Data by Ideology (Word2Vec Embeddings)")
267
+ plt.xlabel("t-SNE Dimension 1")
268
+ plt.ylabel("t-SNE Dimension 2")
269
+ plt.legend(title='Ideology')
270
+ plt.show()
271
+ return brush, size, tsne, tsne_results
272
+
273
+
274
+ @app.cell(hide_code=True)
275
+ def __(mo):
276
+ mo.md(
277
+ """
278
+ ## 7. Interactive Visualizations
279
+
280
+ Interactive scatter plots in Altair show ideology and issue types in 2D space. A brush selection tool allows users to explore specific points and view tooltip information.
281
+
282
+ ### Combined Scatter Plot
283
+
284
+ Combines the two scatter plots into a side-by-side visualization for direct comparison of ideologies vs. issue types.
285
+ Running the Code
286
+
287
+ Run the code using the marimo.App instance. This notebook can also be run as a standalone Python script:
288
+ """
289
+ )
290
+ return
291
+
292
+
293
+ @app.cell(hide_code=True)
294
+ def __(alt, brush, df, mo, size):
295
+ points1 = alt.Chart(df, height=size, width=size).mark_point().encode(
296
+ x='x:Q',
297
+ y='y:Q',
298
+ color=alt.condition(brush, 'label_text', alt.value('grey')),
299
+ tooltip=['x:Q', 'y:Q', 'statement:N', 'label_text:N']
300
+ ).add_params(brush).properties(title='By Political Ideologies')
301
+
302
+ scatter_chart1 = mo.ui.altair_chart(points1)
303
+
304
+ points2 = alt.Chart(df, height=size, width=size).mark_point().encode(
305
+ x='x:Q',
306
+ y='y:Q',
307
+ color=alt.condition(brush, 'issue_type_text', alt.value('grey')),
308
+ tooltip=['x:Q', 'y:Q', 'statement:N', 'issue_type:N']
309
+ ).add_params(brush).properties(title='By Issue Types')
310
+
311
+ scatter_chart2 = mo.ui.altair_chart(points2)
312
+
313
+ combined_chart = (scatter_chart1 | scatter_chart2)
314
+ combined_chart
315
+ return combined_chart, points1, points2, scatter_chart1, scatter_chart2
316
+
317
+
318
+ @app.cell(hide_code=True)
319
+ def __(combined_chart):
320
+ combined_chart.value[['statement', 'label_text', 'issue_type_text']]
321
+ return
322
+
323
+
324
+ @app.cell(hide_code=True)
325
+ def __(combined_chart):
326
+ combined_chart.value['statement']
327
+ return
328
+
329
+
330
+ @app.cell(hide_code=True)
331
+ def __(mo):
332
+ mo.md(
333
+ r"""
334
+ ## Data Insights
335
+
336
+ - Ideology Distribution: Visualizes proportions of conservative and liberal ideologies.
337
+ - Issue Types: Bar plot reveals the diversity and frequency of issue types in the dataset.
338
+ - Word Embeddings: Using TSNE for 2D projections helps identify clusters in political statements.
339
+ - Interactive Exploration: Offers detailed, interactive views on ideology vs. issue type distribution.
340
+
341
+ This code provides a thorough analysis pipeline, from data loading to interactive visualizations, enabling an in-depth exploration of political ideologies.
342
+ """
343
+ )
344
+ return
345
+
346
+ if __name__ == "__main__":
347
+ app.run()