File size: 20,756 Bytes
870ab6b |
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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 |
"""gr.ScatterPlot() component."""
from __future__ import annotations
from typing import Callable, Literal
import altair as alt
import pandas as pd
from gradio_client.documentation import document, set_documentation_group
from pandas.api.types import is_numeric_dtype
from gradio.components.base import _Keywords
from gradio.components.plot import AltairPlot, Plot
set_documentation_group("component")
@document()
class ScatterPlot(Plot):
"""
Create a scatter plot.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a pandas dataframe with the data to plot.
Demos: scatter_plot
Guides: creating-a-dashboard-from-bigquery-data
"""
def __init__(
self,
value: pd.DataFrame | Callable | None = None,
x: str | None = None,
y: str | None = None,
*,
color: str | None = None,
size: str | None = None,
shape: str | None = None,
title: str | None = None,
tooltip: list[str] | str | None = None,
x_title: str | None = None,
y_title: str | None = None,
x_label_angle: float | None = None,
y_label_angle: float | None = None,
color_legend_title: str | None = None,
size_legend_title: str | None = None,
shape_legend_title: str | None = None,
color_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
size_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
shape_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
height: int | None = None,
width: int | None = None,
x_lim: list[int | float] | None = None,
y_lim: list[int | float] | None = None,
caption: str | None = None,
interactive: bool | None = True,
label: str | None = None,
every: float | None = None,
show_label: bool | None = None,
container: bool = True,
scale: int | None = None,
min_width: int = 160,
visible: bool = True,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
):
"""
Parameters:
value: The pandas dataframe containing the data to display in a scatter plot, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
x: Column corresponding to the x axis.
y: Column corresponding to the y axis.
color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
size: The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size.
shape: The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape.
title: The title to display on top of the chart.
tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
x_title: The title given to the x-axis. By default, uses the value of the x parameter.
y_title: The title given to the y-axis. By default, uses the value of the y parameter.
x_label_angle: The angle for the x axis labels rotation. Positive values are clockwise, and negative values are counter-clockwise.
y_label_angle: The angle for the y axis labels rotation. Positive values are clockwise, and negative values are counter-clockwise.
color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
size_legend_title: The title given to the size legend. By default, uses the value of the size parameter.
shape_legend_title: The title given to the shape legend. By default, uses the value of the shape parameter.
color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
size_legend_position: The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
shape_legend_position: The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
height: The height of the plot in pixels.
width: The width of the plot in pixels.
x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
caption: The (optional) caption to display below the plot.
interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
label: The (optional) label to display on the top left corner of the plot.
every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
show_label: Whether the label should be displayed.
visible: Whether the plot should be visible.
elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
"""
self.x = x
self.y = y
self.color = color
self.size = size
self.shape = shape
self.tooltip = tooltip
self.title = title
self.x_title = x_title
self.y_title = y_title
self.x_label_angle = x_label_angle
self.y_label_angle = y_label_angle
self.color_legend_title = color_legend_title
self.color_legend_position = color_legend_position
self.size_legend_title = size_legend_title
self.size_legend_position = size_legend_position
self.shape_legend_title = shape_legend_title
self.shape_legend_position = shape_legend_position
self.caption = caption
self.interactive_chart = interactive
self.width = width
self.height = height
self.x_lim = x_lim
self.y_lim = y_lim
super().__init__(
value=value,
label=label,
every=every,
show_label=show_label,
container=container,
scale=scale,
min_width=min_width,
visible=visible,
elem_id=elem_id,
elem_classes=elem_classes,
)
def get_config(self):
config = super().get_config()
config["caption"] = self.caption
return config
def get_block_name(self) -> str:
return "plot"
@staticmethod
def update(
value: pd.DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE,
x: str | None = None,
y: str | None = None,
color: str | None = None,
size: str | None = None,
shape: str | None = None,
title: str | None = None,
tooltip: list[str] | str | None = None,
x_title: str | None = None,
y_title: str | None = None,
x_label_angle: float | None = None,
y_label_angle: float | None = None,
color_legend_title: str | None = None,
size_legend_title: str | None = None,
shape_legend_title: str | None = None,
color_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
size_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
shape_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
height: int | None = None,
width: int | None = None,
x_lim: list[int | float] | None = None,
y_lim: list[int | float] | None = None,
interactive: bool | None = None,
caption: str | None = None,
label: str | None = None,
show_label: bool | None = None,
container: bool | None = None,
scale: int | None = None,
min_width: int | None = None,
visible: bool | None = None,
):
"""Update an existing plot component.
If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified.
Parameters:
value: The pandas dataframe containing the data to display in a scatter plot.
x: Column corresponding to the x axis.
y: Column corresponding to the y axis.
color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
size: The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size.
shape: The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape.
title: The title to display on top of the chart.
tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
x_title: The title given to the x axis. By default, uses the value of the x parameter.
y_title: The title given to the y axis. By default, uses the value of the y parameter.
x_label_angle: The angle for the x axis labels rotation. Positive values are clockwise, and negative values are counter-clockwise.
y_label_angle: The angle for the y axis labels rotation. Positive values are clockwise, and negative values are counter-clockwise.
color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
size_legend_title: The title given to the size legend. By default, uses the value of the size parameter.
shape_legend_title: The title given to the shape legend. By default, uses the value of the shape parameter.
color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
size_legend_position: The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
shape_legend_position: The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
height: The height of the plot in pixels.
width: The width of the plot in pixels.
x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
caption: The (optional) caption to display below the plot.
label: The (optional) label to display in the top left corner of the plot.
show_label: Whether the label should be displayed.
visible: Whether the plot should be visible.
"""
properties = [
x,
y,
color,
size,
shape,
title,
tooltip,
x_title,
y_title,
x_label_angle,
y_label_angle,
color_legend_title,
size_legend_title,
shape_legend_title,
color_legend_position,
size_legend_position,
shape_legend_position,
height,
width,
x_lim,
y_lim,
interactive,
]
if any(properties):
if not isinstance(value, pd.DataFrame):
raise ValueError(
"In order to update plot properties the value parameter "
"must be provided, and it must be a Dataframe. Please pass a value "
"parameter to gr.ScatterPlot.update."
)
if x is None or y is None:
raise ValueError(
"In order to update plot properties, the x and y axis data "
"must be specified. Please pass valid values for x an y to "
"gr.ScatterPlot.update."
)
chart = ScatterPlot.create_plot(value, *properties)
value = {"type": "altair", "plot": chart.to_json(), "chart": "scatter"}
updated_config = {
"label": label,
"show_label": show_label,
"container": container,
"scale": scale,
"min_width": min_width,
"visible": visible,
"value": value,
"caption": caption,
"__type__": "update",
}
return updated_config
@staticmethod
def create_plot(
value: pd.DataFrame,
x: str,
y: str,
color: str | None = None,
size: str | None = None,
shape: str | None = None,
title: str | None = None,
tooltip: list[str] | str | None = None,
x_title: str | None = None,
y_title: str | None = None,
x_label_angle: float | None = None,
y_label_angle: float | None = None,
color_legend_title: str | None = None,
size_legend_title: str | None = None,
shape_legend_title: str | None = None,
color_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
size_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
shape_legend_position: Literal[
"left",
"right",
"top",
"bottom",
"top-left",
"top-right",
"bottom-left",
"bottom-right",
"none",
]
| None = None,
height: int | None = None,
width: int | None = None,
x_lim: list[int | float] | None = None,
y_lim: list[int | float] | None = None,
interactive: bool | None = True,
):
"""Helper for creating the scatter plot."""
interactive = True if interactive is None else interactive
encodings = {
"x": alt.X(
x, # type: ignore
title=x_title or x, # type: ignore
scale=AltairPlot.create_scale(x_lim), # type: ignore
axis=alt.Axis(labelAngle=x_label_angle)
if x_label_angle is not None
else alt.Axis(),
), # ignore: type
"y": alt.Y(
y, # type: ignore
title=y_title or y, # type: ignore
scale=AltairPlot.create_scale(y_lim), # type: ignore
axis=alt.Axis(labelAngle=y_label_angle)
if y_label_angle is not None
else alt.Axis(),
),
}
properties = {}
if title:
properties["title"] = title
if height:
properties["height"] = height
if width:
properties["width"] = width
if color:
if is_numeric_dtype(value[color]):
domain = [value[color].min(), value[color].max()]
range_ = [0, 1]
type_ = "quantitative"
else:
domain = value[color].unique().tolist()
range_ = list(range(len(domain)))
type_ = "nominal"
encodings["color"] = {
"field": color,
"type": type_,
"legend": AltairPlot.create_legend(
position=color_legend_position, title=color_legend_title or color
),
"scale": {"domain": domain, "range": range_},
}
if tooltip:
encodings["tooltip"] = tooltip
if size:
encodings["size"] = {
"field": size,
"type": "quantitative" if is_numeric_dtype(value[size]) else "nominal",
"legend": AltairPlot.create_legend(
position=size_legend_position, title=size_legend_title or size
),
}
if shape:
encodings["shape"] = {
"field": shape,
"type": "quantitative" if is_numeric_dtype(value[shape]) else "nominal",
"legend": AltairPlot.create_legend(
position=shape_legend_position, title=shape_legend_title or shape
),
}
chart = (
alt.Chart(value) # type: ignore
.mark_point(clip=True) # type: ignore
.encode(**encodings)
.properties(background="transparent", **properties)
)
if interactive:
chart = chart.interactive()
return chart
def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None:
# if None or update
if y is None or isinstance(y, dict):
return y
if self.x is None or self.y is None:
raise ValueError("No value provided for required parameters `x` and `y`.")
chart = self.create_plot(
value=y,
x=self.x,
y=self.y,
color=self.color,
size=self.size,
shape=self.shape,
title=self.title,
tooltip=self.tooltip,
x_title=self.x_title,
y_title=self.y_title,
x_label_angle=self.x_label_angle,
y_label_angle=self.y_label_angle,
color_legend_title=self.color_legend_title,
size_legend_title=self.size_legend_title,
shape_legend_title=self.size_legend_title,
color_legend_position=self.color_legend_position, # type: ignore
size_legend_position=self.size_legend_position, # type: ignore
shape_legend_position=self.shape_legend_position, # type: ignore
interactive=self.interactive_chart,
height=self.height,
width=self.width,
x_lim=self.x_lim,
y_lim=self.y_lim,
)
return {"type": "altair", "plot": chart.to_json(), "chart": "scatter"}
|