MCPcopy
hub / github.com/MaartenGr/BERTopic / _plotly_topic_visualization

Function _plotly_topic_visualization

bertopic/plotting/_topics.py:123–214  ·  view source on GitHub ↗

Create plotly-based visualization of topics with a slider for topic selection.

(df: pd.DataFrame, topic_list: List[str], title: str, width: int, height: int)

Source from the content-addressed store, hash-verified

121
122
123def _plotly_topic_visualization(df: pd.DataFrame, topic_list: List[str], title: str, width: int, height: int):
124 """Create plotly-based visualization of topics with a slider for topic selection."""
125
126 def get_color(topic_selected):
127 if topic_selected == -1:
128 marker_color = ["#B0BEC5" for _ in topic_list]
129 else:
130 marker_color = ["red" if topic == topic_selected else "#B0BEC5" for topic in topic_list]
131 return [{"marker.color": [marker_color]}]
132
133 # Prepare figure range
134 x_range = (
135 df.x.min() - abs((df.x.min()) * 0.15),
136 df.x.max() + abs((df.x.max()) * 0.15),
137 )
138 y_range = (
139 df.y.min() - abs((df.y.min()) * 0.15),
140 df.y.max() + abs((df.y.max()) * 0.15),
141 )
142
143 # Plot topics
144 fig = px.scatter(
145 df,
146 x="x",
147 y="y",
148 size="Size",
149 size_max=40,
150 template="simple_white",
151 labels={"x": "", "y": ""},
152 hover_data={"Topic": True, "Words": True, "Size": True, "x": False, "y": False},
153 )
154 fig.update_traces(marker=dict(color="#B0BEC5", line=dict(width=2, color="DarkSlateGrey")))
155
156 # Update hover order
157 fig.update_traces(
158 hovertemplate="<br>".join(
159 [
160 "<b>Topic %{customdata[0]}</b>",
161 "%{customdata[1]}",
162 "Size: %{customdata[2]}",
163 ]
164 )
165 )
166
167 # Create a slider for topic selection
168 steps = [dict(label=f"Topic {topic}", method="update", args=get_color(topic)) for topic in topic_list]
169 sliders = [dict(active=0, pad={"t": 50}, steps=steps)]
170
171 # Stylize layout
172 fig.update_layout(
173 title={
174 "text": f"{title}",
175 "y": 0.95,
176 "x": 0.5,
177 "xanchor": "center",
178 "yanchor": "top",
179 "font": dict(size=22, color="Black"),
180 },

Callers 1

visualize_topicsFunction · 0.85

Calls 1

get_colorFunction · 0.85

Tested by

no test coverage detected