主题
ScatterChart 继承自: ft.LayoutControl, Control, BaseControl
A scatter chart control.
ScatterChart draws some points in a square space, points are defined by ScatterChartSpots.
python
fch.ScatterChart(
aspect_ratio=1.0,
spots=[
fch.ScatterChartSpot(
x=random.uniform(4, 50),
y=random.uniform(4, 50),
)
for _ in range(30)
],
)示例
python
import random
import flet as ft
import flet_charts as fch
class MySpot(fch.ScatterChartSpot):
def __init__(
self,
x: float,
y: float,
radius: float = 8.0,
color: ft.Colors = None,
show_tooltip: bool = False,
):
super().__init__(
x=x,
y=y,
radius=radius,
color=color,
show_tooltip=show_tooltip,
selected=y == 43,
)
flutter_logo_spots = [
MySpot(20, 14.5),
MySpot(20, 14.5),
MySpot(22, 16.5),
MySpot(24, 18.5),
MySpot(22, 12.5),
MySpot(24, 14.5),
MySpot(26, 16.5),
MySpot(24, 10.5),
MySpot(26, 12.5),
MySpot(28, 14.5),
MySpot(26, 8.5),
MySpot(28, 10.5),
MySpot(30, 12.5),
MySpot(28, 6.5),
MySpot(30, 8.5),
MySpot(32, 10.5),
MySpot(30, 4.5),
MySpot(32, 6.5),
MySpot(34, 8.5),
MySpot(34, 4.5),
MySpot(36, 6.5),
MySpot(38, 4.5),
# section 2
MySpot(20, 14.5),
MySpot(22, 12.5),
MySpot(24, 10.5),
MySpot(22, 16.5),
MySpot(24, 14.5),
MySpot(26, 12.5),
MySpot(24, 18.5),
MySpot(26, 16.5),
MySpot(28, 14.5),
MySpot(26, 20.5),
MySpot(28, 18.5),
MySpot(30, 16.5),
MySpot(28, 22.5),
MySpot(30, 20.5),
MySpot(32, 18.5),
MySpot(30, 24.5),
MySpot(32, 22.5),
MySpot(34, 20.5),
MySpot(34, 24.5),
MySpot(36, 22.5),
MySpot(38, 24.5),
# section 3
MySpot(10, 25),
MySpot(12, 23),
MySpot(14, 21),
MySpot(12, 27),
MySpot(14, 25),
MySpot(16, 23),
MySpot(14, 29),
MySpot(16, 27),
MySpot(18, 25),
MySpot(16, 31),
MySpot(18, 29),
MySpot(20, 27),
MySpot(18, 33),
MySpot(20, 31),
MySpot(22, 29),
MySpot(20, 35),
MySpot(22, 33),
MySpot(24, 31),
MySpot(22, 37),
MySpot(24, 35),
MySpot(26, 33),
MySpot(24, 39),
MySpot(26, 37),
MySpot(28, 35),
MySpot(26, 41),
MySpot(28, 39),
MySpot(30, 37),
MySpot(28, 43),
MySpot(30, 41),
MySpot(32, 39),
MySpot(30, 45),
MySpot(32, 43),
MySpot(34, 41),
MySpot(34, 45),
MySpot(36, 43),
MySpot(38, 45),
]
def get_random_spots():
"""Generates random spots for the scatter chart."""
return [
MySpot(
x=random.uniform(4, 50),
y=random.uniform(4, 50),
radius=random.uniform(4, 20),
)
for _ in range(len(flutter_logo_spots))
]
def main(page: ft.Page):
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
def handle_event(e: fch.ScatterChartEvent):
if e.type == fch.ChartEventType.TAP_DOWN:
e.control.spots = (
flutter_logo_spots
if (e.control.spots != flutter_logo_spots)
else get_random_spots()
)
page.add(
ft.SafeArea(
expand=True,
content=ft.Column(
expand=True,
controls=[
ft.Text(
"Tap on the chart to toggle between random spots and Flutter "
"logo spots."
),
fch.ScatterChart(
expand=True,
aspect_ratio=1.0,
min_x=0.0,
max_x=50.0,
min_y=0.0,
max_y=50.0,
left_axis=fch.ChartAxis(show_labels=False),
right_axis=fch.ChartAxis(show_labels=False),
top_axis=fch.ChartAxis(show_labels=False),
bottom_axis=fch.ChartAxis(show_labels=False),
show_tooltips_for_selected_spots_only=False,
on_event=handle_event,
animation=ft.Animation(
duration=ft.Duration(milliseconds=600),
curve=ft.AnimationCurve.FAST_OUT_SLOWIN,
),
spots=flutter_logo_spots,
),
],
),
),
)
if __name__ == "__main__":
ft.run(main)
下面是一个带有误差棒(error bars)的散点图示例:
python
import statistics
import flet as ft
import flet_charts as fch
# Five timings of one swing (in seconds) for each pendulum string length (in cm).
TIMINGS = {
20: [0.84, 0.95, 0.90, 0.88, 0.93],
40: [1.22, 1.33, 1.27, 1.25, 1.30],
60: [1.50, 1.62, 1.55, 1.52, 1.58],
80: [1.73, 1.86, 1.80, 1.76, 1.82],
100: [1.94, 2.09, 2.00, 1.98, 2.03],
120: [2.13, 2.29, 2.19, 2.17, 2.24],
}
# How far off each measured string length may be, in cm.
LENGTH_UNCERTAINTY = 3
def main(page: ft.Page):
grid_color = ft.Colors.with_opacity(0.2, ft.Colors.ON_SURFACE)
spots = []
for length, timings in TIMINGS.items():
mean = statistics.fmean(timings)
spots.append(
fch.ScatterChartSpot(
x=length,
y=mean,
radius=6,
color=ft.Colors.INDIGO,
tooltip=f"{mean:.2f} s",
x_error=fch.ChartErrorRange.symmetric(LENGTH_UNCERTAINTY),
y_error=fch.ChartErrorRange(
lower_by=mean - min(timings),
upper_by=max(timings) - mean,
),
)
)
page.add(
ft.SafeArea(
expand=True,
content=ft.Column(
expand=True,
controls=[
ft.Text(
"Mean period of a pendulum over five timings. Vertical bars "
"span the fastest and slowest timing, horizontal bars the "
f"±{LENGTH_UNCERTAINTY} cm uncertainty of the string length."
),
fch.ScatterChart(
expand=True,
min_x=0,
max_x=140,
min_y=0.5,
max_y=2.5,
border=ft.Border.all(1, grid_color),
horizontal_grid_lines=fch.ChartGridLines(
interval=0.5, color=grid_color, width=1
),
vertical_grid_lines=fch.ChartGridLines(
interval=20, color=grid_color, width=1
),
left_axis=fch.ChartAxis(
title=ft.Text("Period (s)"),
title_size=24,
label_spacing=0.5,
label_size=40,
),
bottom_axis=fch.ChartAxis(
title=ft.Text("String length (cm)"),
title_size=24,
label_spacing=20,
label_size=28,
show_max=False,
),
spots=spots,
),
],
),
)
)
if __name__ == "__main__":
ft.run(main)属性
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
spots | list[ScatterChartSpot] | [] | List of ScatterChartSpots to show on the chart. |
animation | ft.AnimationValue | ft.Animation(duration=ft.Duration(milliseconds=150)() | Controls chart implicit animation. |
interactive | bool | True | Enables automatic tooltips when hovering chart bars. |
long_press_duration | Optional[ft.DurationValue] | None | The duration of a long press on the chart. |
bgcolor | Optional[ft.ColorValue] | None | The chart's background color. |
border | Optional[ft.Border] | None | The border around the chart. |
horizontal_grid_lines | Optional[ChartGridLines] | None | Controls drawing of chart's horizontal lines. |
vertical_grid_lines | Optional[ChartGridLines] | None | Controls drawing of chart's vertical lines. |
left_axis | Optional[ChartAxis] | None | Configures the appearance of the left axis, its title and labels. |
top_axis | Optional[ChartAxis] | None | Configures the appearance of the top axis, its title and labels. |
right_axis | Optional[ChartAxis] | None | Configures the appearance of the right axis, its title and labels. |
bottom_axis | Optional[ChartAxis] | None | Configures the appearance of the bottom axis, its title and labels. |
baseline_x | Optional[ft.Number] | None | The baseline value for X axis. |
min_x | Optional[ft.Number] | None | The minimum displayed value for X axis. |
max_x | Optional[ft.Number] | None | The maximum displayed value for X axis. |
baseline_y | Optional[ft.Number] | None | Baseline value for Y axis. |
min_y | Optional[ft.Number] | None | The minimum displayed value for Y axis. |
max_y | Optional[ft.Number] | None | The maximum displayed value for Y axis. |
tooltip | ScatterChartTooltip | ScatterChartTooltip(() | The tooltip configuration for the chart. |
show_tooltips_for_selected_spots_only | bool | False | Whether to permanently and only show the tooltips of spots with their selected property set to True. |
rotation_quarter_turns | ft.Number | 0 | Number of quarter turns (90-degree increments) to rotate the chart. Ex: 1 rotates the chart 90 degrees clockwise, 2 rotates 180 degrees and 0 for no rotation. |
width | Optional[Number] | None | Imposed Control width in virtual pixels. |
height | Optional[Number] | None | Imposed Control height in virtual pixels. |
left | Optional[Number] | None | The distance that the child's left edge is inset from the left of the stack. Note: Effective only if this control is a descendant of one of the following: Stack control, overlay list. |
top | Optional[Number] | None | The distance that the child's top edge is inset from the top of the stack. Note: Effective only if this control is a descendant of one of the following: Stack control, overlay list. |
right | Optional[Number] | None | The distance that the child's right edge is inset from the right of the stack. Note: Effective only if this control is a descendant of one of the following: Stack control, overlay list. |
bottom | Optional[Number] | None | The distance that the child's bottom edge is inset from the bottom of the stack. Note: Effective only if this control is a descendant of one of the following: Stack control, overlay list. |
align | Optional[Alignment] | None | Alignment of the control within its parent. |
margin | Optional[MarginValue] | None | Sets the margin of the control. |
rotate | Optional[RotateValue] | None | Transforms this control using a rotation around its center. The value of rotate property could be one of the following types: * number - a rotation in clockwise radians. Full circle 360° is math.pi * 2 radians, 90° is pi / 2, 45° is pi / 4, etc. * Rotate - allows to specify rotation angle as well as alignment - the location of rotation center. Example: python ft.Image( src="https://picsum.photos/100/100", width=100, height=100, border_radius=5, rotate=Rotate(angle=0.25 * pi, alignment=ft.Alignment.CENTER_LEFT) ) |
scale | Optional[ScaleValue] | None | Scales this control along the 2D plane. Default scale factor is 1.0, meaning no-scale. Setting this property to 0.5, for example, makes this control twice smaller, while 2.0 makes it twice larger. Different scale multipliers can be specified for x and y axis, by setting Control.scale property to an instance of Scale class. Either scale or scale_x and scale_y could be specified, but not all of them. Example: python ft.Image( src="https://picsum.photos/100/100", width=100, height=100, border_radius=5, scale=ft.Scale(scale_x=2, scale_y=0.5) ) |
offset | Optional[OffsetValue] | None | Applies a translation transformation before painting the control. The translation is expressed as an Offset scaled to the control's size. So, Offset(x=0.25, y=0), for example, will result in a horizontal translation of one quarter the width of this control. Example The following example displays container at 0, 0 top left corner of a stack as transform applies -1 * 100, -1 * 100 (offset * control's size) horizontal and vertical translations to the control: python import flet as ft def main(page: ft.Page): page.add( ft.Stack( width=1000, height=1000, controls=[ ft.Container( bgcolor=ft.Colors.RED, width=100, height=100, left=100, top=100, offset=ft.Offset(-1, -1), ) ], ) ) ft.run(main) |
flip | Optional[Flip] | None | Flips this control horizontally and/or vertically. Set to an instance of Flip to mirror across x-axis, y-axis, or both. |
transform | Optional[Transform] | None | Applies a generic matrix transform to this control. Set to an instance of Transform with a recorded Matrix4 to describe arbitrary transform sequences. |
aspect_ratio | Optional[Number] | None | The aspect ratio of the control. It is defined as the ratio of width to height. Note: In current implementation, if aspect_ratio is set, width and height on the same control are ignored for final rendered size. |
animate_opacity | Optional[AnimationValue] | None | 启用 opacity 属性的隐式动画。 详见 此处. |
animate_size | Optional[AnimationValue] | None | 启用此控件尺寸的隐式动画。 If width or height is set, changes to those dimensions are animated. If neither dimension is set, changes to the control's natural size are animated instead. 详见 此处. |
animate_position | Optional[AnimationValue] | None | 启用定位属性(left、right、top、bottom)的隐式动画。 详见 此处. |
animate_align | Optional[AnimationValue] | None | 启用 align 属性的隐式动画。 详见 此处. |
animate_margin | Optional[AnimationValue] | None | 启用 margin 属性的隐式动画。 详见 此处. |
animate_rotation | Optional[AnimationValue] | None | 启用 rotate 属性的隐式动画。 详见 此处. |
animate_scale | Optional[AnimationValue] | None | 启用 scale 属性的隐式动画。 详见 此处. |
animate_offset | Optional[AnimationValue] | None | 启用 offset 属性的隐式动画。 详见 此处. |
size_change_interval | int | 10 | Sampling interval in milliseconds for on_size_change event. Setting to 0 calls on_size_change immediately on every change. |
expand | Annotated[Optional[Union[bool, int]], V.instance_of((bool, int))] | None | 指定此控件是否/如何扩展以填充父布局中的可用空间。 详见 此处. Note: Has effect only if the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page. Raises: ValueError: If it is not of type bool or int. |
expand_loose | bool | False | 允许控件在主轴方向上有可用空间时扩展,但不要求填满所有可用空间。 详见 此处. Note: 若 expand_loose 为 True,则仅当同时满足以下条件时生效: - expand 不为 None,且 - the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page. |
col | ResponsiveNumber | 12 | 若此控件的父控件是 ResponsiveRow,此属性用于决定该控件横跨多少个虚拟列。 可以是数字,也可以是为不同断点配置不同值的字典,例如 col={"sm": 6}。 0 表示在该断点下隐藏控件,不占用任何列。 默认横跨 12 个虚拟列。 \ |
opacity | Annotated[Number, V.between(0.0, 1.0)] | 1.0 | 定义控件的透明度,取值范围 0.0(完全透明)到 1.0(完全不透明)。 抛出异常:ValueError:若不在 0.0 到 1.0 的闭区间内。 |
badge | Optional[BadgeValue] | None | 显示在控件顶部的徽标。 |
visible | bool | True | Every control has visible property which is True by default - control is rendered on the page. Setting visible to False 完全阻止该控件(及其所有子控件)渲染到页面画布上. 隐藏的控件不能通过键盘或鼠标聚焦或选中,也不会触发任何事件。 |
disabled | bool | False | Every control has disabled property which is False by default - control and all its children are enabled. Note: The value of this property will be propagated down to all children controls recursively. Example: For example, if you have a form with multiple entry controls you can disable them all together by disabling container: python ft.Column( disabled = True, controls=[ ft.TextField(), ft.TextField() ] ) |
rtl | bool | False | 控件的文字方向是否为从右到左(RTL)。 |
data | Any | skip_ | 任意类型的自定义数据。 |
key | Optional['KeyValue'] | None | 用于在更新之间保持控件身份稳定的 key。 |
只读属性
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
parent | Optional['BaseControl'] | — | The direct ancestor(parent) of this control. It defaults to None and will only have a value when this control is mounted (added to the page tree). Page 控件(树的根)为例外 —— 它始终 parent=None。 |
page | 'Page' | — | 此控件所属的页面。 |
事件
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
on_event | Optional[ft.EventHandler[ScatterChartEvent]] | None | Called when an event occurs on this chart. |
on_size_change | Optional[EventHandler[LayoutSizeChangeEvent['LayoutControl']]] | None | Called when the size of this control changes. size_change_interval defines how often this event is called. |
on_animation_end | Optional[ControlEventHandler['LayoutControl']] | None | 动画结束时调用,可用于串联多个动画。 事件参数 data 属性包含动画的名称。 详见 此处. |
方法
| 名称 | 类型 | 默认值 | 说明 |
|---|---|---|---|
is_isolated | — | — | Return whether this control is marked as isolated. 被隔离的控件不会参与父级驱动的更新遍历,需要自行管理更新边界。 |
init | — | — | Called after control instance initialization and before the first build / update cycle. 可重写此钩子执行依赖于已初始化字段的轻量设置。 不要在这里调用 update()。 |
build | — | — | 在控件初始化期间调用一次,用于定义其子控件。 page 属性在此方法中可用。 |
before_update | — | — | 每次控件即将更新时调用。 Note: 不要在此处调用 update()。 |
before_event | — | — | 在事件处理器执行前拦截事件。 返回 False 取消分发,返回 True 或 None 则继续正常的事件处理。 |
did_mount | — | — | 在控件挂载到页面树之后调用。 可重写以启动需要已挂载页面的资源,例如订阅、定时器或服务监听。 |
will_unmount | — | — | 在控件从页面树移除之前调用。 可重写以释放 did_mount() 中创建的资源,例如订阅、定时器或外部句柄。 |
get_data_channel | — | — | Resolve the [DataChannel] allocated on the Dart side for this widget. Pattern: on_data_channel_open: Optional[ft.EventHandler[DataChannelOpenEvent]] = None def init(self): self.on_data_channel_open = self._on_open def _on_open(self, e): self._channel = self.get_data_channel(e.channel_id) Idempotent — the underlying Connection caches DataChannels by id, so repeated calls return the same instance. No error path: the id always comes from a framework-fired event, so by the time this runs the channel exists on both sides. |
update | None | — | 请求更新该控件的 UI。 在修改控件状态或属性后调用。 控件必须已挂载到页面,并且未被冻结。 |