### Install Dependencies Source: https://py.dreamplet.com/tutorials/line-chart Install the required optional packages for data handling and date manipulation. ```bash pip install polars pendulum ``` -------------------------------- ### Install pyDreamplet Source: https://py.dreamplet.com/tutorials/combo-chart Install the required library using pip. ```bash pip install pydreamplet ``` -------------------------------- ### Install pyDreamplet with notebook support Source: https://py.dreamplet.com/getting-started Install the library with optional dependencies for inline display in Jupyter notebooks. ```bash uv add "pydreamplet[notebook]" ``` ```bash pip install "pydreamplet[notebook]" ``` -------------------------------- ### SVG ViewBox Initialization Source: https://py.dreamplet.com/reference/svg Examples of initializing SVG with different viewBox formats. ```python dp.SVG((540, 360)) dp.SVG([0, 0, 540, 360]) ``` -------------------------------- ### Install pyDreamplet core package Source: https://py.dreamplet.com/getting-started Install the base library using common Python package managers. ```bash uv add pydreamplet ``` ```bash pip install pydreamplet ``` -------------------------------- ### Create and Configure Text Source: https://py.dreamplet.com/reference/text Example of initializing a text element with position and style attributes. ```python text = dp.Text( "Hello", pos=(10, 20), font_size=12, font_weight=700, text_anchor="middle", ) print(text.pos) # Vector(x=10.0, y=20.0) print(str(text)) # Hello ``` -------------------------------- ### Initialize LinearGradient Source: https://py.dreamplet.com/reference/definitions Example of creating a linear gradient and adding color stops. ```python gradient = dp.LinearGradient( id="accent", x1="0%", y1="0%", x2="100%", y2="0%", ) gradient.add_stop("0%", "#14b8a6") gradient.add_stop("100%", "#38bdf8") ``` -------------------------------- ### Line Instantiation Source: https://py.dreamplet.com/reference/shapes Example of creating a Line instance with endpoints and stroke styling. ```python line = dp.Line( 24, 96, 196, 36, stroke="currentColor", stroke_width=6, stroke_linecap="round", ) ``` -------------------------------- ### Initialize RadialGradient Source: https://py.dreamplet.com/reference/definitions Example of creating a radial gradient with multiple stops. ```python glow = dp.RadialGradient(id="glow", cx="50%", cy="50%", r="60%") glow.add_stop("0%", "#ffffff", opacity=0.9) glow.add_stop("100%", "#14b8a6", opacity=0) ``` -------------------------------- ### Example usage of path and ring helpers Source: https://py.dreamplet.com/reference/shape-helpers Demonstrates linear path creation and ring generation with assertions. ```python import pydreamplet as dp assert dp.linear_path([(0, 0), (10, 20), (30, 0)]) == ( "M 0.00,0.00 L 10.00,20.00 L 30.00,0.00" ) assert dp.ring(inner_radius=5, outer_radius=10, start_angle=30, end_angle=30) == "" ``` -------------------------------- ### Initialize TypographyMeasurer Source: https://py.dreamplet.com/reference/typography Examples of initializing the measurer with a file path or theme settings. ```python measurer = TypographyMeasurer(font_path="assets/fonts/Inter-Regular.ttf") ``` ```python theme = dp.Theme() measurer = TypographyMeasurer( font_family=theme.font_family, weight=theme.font_weight, ) width, height = measurer.measure_text("Measured label", font_size=18) ``` -------------------------------- ### Calculating Bounding Box Source: https://py.dreamplet.com/reference/paths Example of retrieving the bounding box for a path. ```python path = dp.Path("M10 20 h100 v50 h-100 z") box = path.bbox print(box) # BoundingBox(x=10.0, y=20.0, width=100.0, height=50.0) ``` -------------------------------- ### Usage of get_system_font_path Source: https://py.dreamplet.com/reference/typography Example of searching for a specific font weight. ```python font_path = get_system_font_path("Arial", 700) if font_path is None: print("Font not found") else: print(font_path) ``` -------------------------------- ### Retrieving Path Dimensions Source: https://py.dreamplet.com/reference/paths Example of accessing width, height, and center properties. ```python path = dp.Path("M10 20 L110 20 L110 70 Z") print(path.w) # 100.0 print(path.h) # 50.0 print(path.center) # Vector(x=60.0, y=45.0) ``` -------------------------------- ### Rect Instantiation Source: https://py.dreamplet.com/reference/shapes Example of creating a Rect instance with position, dimensions, corner radius, and fill color. ```python rect = dp.Rect( pos=(30, 24), width=160, height=92, rx=10, fill="#95cf20", ) ``` -------------------------------- ### Creating a Path with Attributes Source: https://py.dreamplet.com/reference/paths Example of defining a path with specific SVG data and styling attributes. ```python path = dp.Path( "M40 120 L120 40 L200 120 Z", fill="#14b8a6", stroke="currentColor", stroke_width=5, ) ``` -------------------------------- ### Creating and referencing markers Source: https://py.dreamplet.com/reference/markers Example demonstrating how to define markers within a Defs block and apply them to a line element. ```python import pydreamplet as dp from pydreamplet.markers import ARROW_BASIC, DOT, Marker svg = dp.SVG(300, 130) defs = dp.Defs() arrow = Marker("arrow-head", ARROW_BASIC, 10, 10, fill="#14b8a6", orient="auto") dot = Marker("dot-start", DOT, 8, 8, fill="#f83898") defs.append(arrow, dot) svg.append(defs) line = dp.Line( 38, 76, 252, 76, stroke="currentColor", stroke_width=3, stroke_linecap="round", ) line.marker_start = dot.url line.marker_end = arrow.url svg.append( line, dp.Text("marker_start", x=38, y=48, font_size=12, text_anchor="middle", fill="currentColor"), dp.Text("marker_end", x=252, y=48, font_size=12, text_anchor="middle", fill="currentColor"), dp.Text("Marker(...).url", x=92, y=108, font_size=12, fill="currentColor"), ) ``` -------------------------------- ### LinkGenerator Usage Example Source: https://py.dreamplet.com/reference/generators Instantiates a LinkGenerator with source and target accessors and generates a link. ```python link = dp.LinkGenerator( source=lambda item, _index: item["source"], target=lambda item, _index: item["target"], ) d = link({"source": (0, 10), "target": (100, 50)}) ``` -------------------------------- ### ArcGenerator Usage Source: https://py.dreamplet.com/reference/generators Example of initializing an ArcGenerator with accessor functions for radii and angles. ```python arc = dp.ArcGenerator( inner_radius=lambda _item, _index: 20, outer_radius=lambda _item, _index: 48, start_angle=lambda item, _index: item.start_angle, end_angle=lambda item, _index: item.end_angle, ) ``` -------------------------------- ### Create a visual chart with scales Source: https://py.dreamplet.com/reference/scales Example demonstrating the use of multiple scale types to render an SVG chart. ```python import pydreamplet as dp values = [12, 35, 24, 50] labels = ["A", "B", "C", "D"] x = dp.BandScale(labels, (30, 310), padding=0.2) y = dp.LinearScale((0, 50), (150, 30)) color = dp.ColorScale((0, 50), ("#14b8a6", "#f83898")) radius = dp.CircleScale((0, 50), (8, 24)) svg = dp.SVG(340, 180) svg.append(dp.Line(24, 150, 320, 150, stroke="currentColor", stroke_width=2, opacity=0.35)) for label, value in zip(labels, values): cx = x.map(label) + x.bandwidth / 2 cy = y.map(value) svg.append( dp.Circle(cx=cx, cy=cy, r=radius.map(value), fill=color.map(value), opacity=0.9), dp.Text(label, x=cx, y=168, font_size=14, text_anchor="middle", fill="currentColor"), ) ``` -------------------------------- ### Visualizing Shapes Source: https://py.dreamplet.com/reference/shape-helpers Example demonstrating various shape helpers rendered within an SVG container. ```python import pydreamplet as dp svg = dp.SVG(420, 190) svg.append( dp.Path(dp.star(58, 58, n=5, inner_radius=18, outer_radius=40, angle=-90), fill="currentColor"), dp.Path(dp.superellipse(155, 58, rx=48, ry=34, exponent=4, n=48), fill="currentColor", opacity=0.68), dp.Path(dp.rounded_polygon([(245, 22), (320, 36), (306, 106), (232, 100)], radius=14), fill="none", stroke="currentColor", stroke_width=4), dp.Path(dp.blob(372, 64, radius=38, variance=0.22, n=10, seed=5), fill="currentColor", opacity=0.35), dp.Path(dp.ring(96, 142, inner_radius=20, outer_radius=42, start_angle=-35, end_angle=250), fill="currentColor", opacity=0.45), dp.Path(dp.cross(210, 142, size=74, thickness=22, angle=35), fill="none", stroke="currentColor", stroke_width=4), ) ``` -------------------------------- ### Ellipse Instantiation Source: https://py.dreamplet.com/reference/shapes Example of creating an Ellipse instance with specific position, radii, and fill color. ```python ellipse = dp.Ellipse( pos=(110, 70), rx=72, ry=34, fill="#38bdf8", ) ``` -------------------------------- ### Using predefined path constants Source: https://py.dreamplet.com/reference/markers Example of using a predefined path constant as the d argument for a Marker. ```python from pydreamplet.markers import ARROW_CONCAVE, Marker marker = Marker("concave-arrow", ARROW_CONCAVE, 10, 10, fill="#14b8a6") ``` -------------------------------- ### Performing Linear Measurements Source: https://py.dreamplet.com/reference/paths Example of calculating length, point at distance, and tangent at distance. ```python route = dp.Path("M0 0 L10 0 L10 10") print(route.length) # 20.0 print(route.point_at(15)) # Vector(x=10.0, y=5.0) print(route.tangent_at(15)) # Vector(x=0.0, y=1.0) ``` -------------------------------- ### Creating Text on a Path Source: https://py.dreamplet.com/reference/text Example of creating an SVG with a path and attaching text to it using TextOnPath. ```python svg = dp.SVG(360, 180) path = dp.Path( id="curve", d="M40 120 C95 30 265 30 320 120", fill="none", stroke="currentColor", stroke_width=3, ) label = dp.TextOnPath( "Text follows the curve", path_id="curve", text_path_args={ "startOffset": "50%", "text_anchor": "middle", }, fill="currentColor", font_size=24, font_weight=700, ) svg.append(path).append(label) ``` -------------------------------- ### Access Animation Properties Source: https://py.dreamplet.com/reference/animation Examples of reading and writing repeat_count and values properties. ```python anim.repeat_count -> int | str anim.repeat_count = value ``` ```python anim = dp.Animate("opacity") anim.repeat_count = "5" print(anim.element.get("repeatCount")) # 5 ``` ```python anim.values -> list[str] anim.values = value: list[Any] ``` ```python anim = dp.Animate("r") anim.values = [8, 24, 8] print(anim.element.get("values")) # 8;24;8 ``` -------------------------------- ### Implement Arc Commands Source: https://py.dreamplet.com/reference/paths Example of creating an arc; boolean values for large_arc and sweep are automatically serialized to integers. ```python arc = ( dp.PathBuilder() .move_to(40, 100) .arc_to(60, 60, 0, False, True, 160, 100) ) ``` -------------------------------- ### PieGenerator Usage Source: https://py.dreamplet.com/reference/generators Example of generating pie slices from a list of values and verifying slice properties. ```python slices = dp.PieGenerator(start_angle=-90)([1, 2, 3]) assert slices[1].angle == 120 assert slices[1].mid_angle == 30 ``` -------------------------------- ### Create and Transform SVG Group Source: https://py.dreamplet.com/reference/transforms Example of creating a group, adding elements, and applying transformations. ```python svg = dp.SVG(360, 180) group = dp.G(pos=(180, 90), angle=25, scale=dp.Vector(1.25, 1.25)) group.append(dp.Rect(x=-45, y=-28, width=90, height=56, rx=8, fill="currentColor", opacity=0.18)) group.append(dp.Line(-70, 0, 70, 0, stroke="currentColor", stroke_width=2, opacity=0.45)) group.append(dp.Text("G", x=0, y=6, fill="currentColor", font_size=28, font_weight=800, text_anchor="middle")) svg.append(group) print(group.transform) # translate(180 90) rotate(25) scale(1.25 1.25) ``` -------------------------------- ### Define and Apply Mask Source: https://py.dreamplet.com/reference/definitions Constructor signature for Mask and examples of appending elements and assigning the mask to a shape. ```python dp.Mask(id: str | None = None, **kwargs) ``` ```python mask = dp.Mask(id="fade") mask.append( dp.Rect(x=0, y=0, width=260, height=160, fill="black"), dp.Circle(cx=130, cy=80, r=58, fill="white"), ) ``` ```python shape.mask = mask.url ``` -------------------------------- ### Handling Unsupported Measurement Commands Source: https://py.dreamplet.com/reference/paths Example showing that curves raise a ValueError during linear measurement. ```python curve = dp.Path("M0 0 C10 0 20 10 30 10") try: curve.length except ValueError: print("curves are not supported by linear measurement") ``` -------------------------------- ### Measure and Visualize Text Source: https://py.dreamplet.com/reference/typography Example of measuring a Text element and drawing a bounding box around it. ```python import pydreamplet as dp from pydreamplet.typography import TypographyMeasurer, get_system_font_path font_path = get_system_font_path("Arial", 400) if font_path is None: raise RuntimeError("Arial is not available on this system.") label = dp.Text( "pyDreamplet", x=32, y=78, font_family="Arial", font_size=32, font_weight=400, fill="currentColor", ) measurer = TypographyMeasurer(font_path=font_path) width, height = measurer.measure_text(label) svg = dp.SVG(300, 140) svg.append( dp.Rect( x=label.x, y=label.y - height * 0.78, width=width, height=height, fill="none", stroke="#14b8a6", stroke_width=2, stroke_dasharray="5 4", ), dp.Line(label.x, label.y, label.x + width, label.y, stroke="#f83898", stroke_width=2), label, dp.Text(f"{width:.1f} x {height:.1f}", x=32, y=116, font_size=12, fill="currentColor"), ) ``` -------------------------------- ### Define theme overrides in JSON Source: https://py.dreamplet.com/reference/colors Example JSON structure for overriding default theme font and color settings. ```json { "font": { "fontFamily": "Roboto", "fontSize": 12, "fontWeight": 400, "lineHeight": 1.5 }, "colors": { "ink": "oklch(27.4% 0.006 286.033)", "surface": "oklch(96.7% 0.001 286.375)", "brand": "oklch(62.3% 0.214 259.815)" } } ``` -------------------------------- ### Linear Path Function Usage Source: https://py.dreamplet.com/reference/paths Example usage of path iteration, length calculation, and point retrieval on linear path data. ```python path_data = "M0 0 H10 V10" segments = dp.iter_path_segments(path_data) print(len(segments)) # 2 print(dp.path_length(path_data)) # 20.0 print(dp.point_at_length(path_data, 12)) # Vector(x=10.0, y=2.0) ``` -------------------------------- ### Initialize default Theme Source: https://py.dreamplet.com/reference/colors Create a Theme instance using built-in defaults. ```python theme = dp.Theme() assert theme.font_family == "sans-serif" assert theme.font_size == 14 assert theme.blue == "oklch(62.3% 0.214 259.815)" assert theme.color is theme.colors ``` -------------------------------- ### Define Project Directory Structure Source: https://py.dreamplet.com/tutorials/combo-chart Set up the necessary file structure for the project. ```text combo-chart/ ├── assets/ │ ├── revenue.svg │ └── stock_price.svg ├── data/ │ └── apple.csv ├── data_reader.py └── main.py ``` -------------------------------- ### Accessing marker stroke Source: https://py.dreamplet.com/reference/markers Get or set the nested path stroke. ```python marker.stroke -> str | None marker.stroke = "currentColor" ``` -------------------------------- ### Accessing marker fill Source: https://py.dreamplet.com/reference/markers Get or set the nested path fill. ```python marker.fill -> str | None marker.fill = "#14b8a6" ``` -------------------------------- ### Initialize pyDreamplet Environment Source: https://py.dreamplet.com/tutorials/polar-noise Sets up the theme, noise generator, and SVG canvas. Using a fixed seed ensures consistent results across multiple runs. ```python import pydreamplet as dp from pydreamplet.noise import SimplexNoise2D theme = dp.Theme() noise = SimplexNoise2D(seed=42) svg = dp.SVG(1024, 1024) ``` -------------------------------- ### Generate an area path Source: https://py.dreamplet.com/reference/generators Example usage of AreaGenerator with a custom y0 accessor. ```python area = dp.AreaGenerator(y0=lambda _item, _index: 10) assert area([(0, 0), (10, 20), (30, 0)]).endswith("Z") ``` -------------------------------- ### Initializing a Path Source: https://py.dreamplet.com/reference/paths Constructor signature for creating a new Path object. ```python dp.Path(d: str | dp.PathBuilder = "", **kwargs) ``` -------------------------------- ### Initialize Imports and Colors Source: https://py.dreamplet.com/tutorials/layered-svg-art Sets up the necessary pydreamplet modules and defines the color palette for the artwork. ```python import pydreamplet as dp from pydreamplet.colors import blend from pydreamplet.shapes import ring color1 = "#e2cbc5" color2 = "#691016" color3 = "#92a1c2" color4 = "#082137" ``` -------------------------------- ### Using Position and Size Setters Source: https://py.dreamplet.com/reference/svg-element Demonstrates setting position and size. set_position() handles cx/cy for circles and x/y for other elements. ```python circle = dp.Circle(r=18).set_position((40, 50)) rect = dp.Rect().set_position(20, 30).set_size(120, 80) ``` -------------------------------- ### Animate SVG Transforms Source: https://py.dreamplet.com/reference/animation Example of using AnimateTransform to rotate a group element. ```python svg = dp.SVG(300, 300) g = dp.G(pos=(150, 150)) g.append(dp.Circle(cx=72, cy=0, r=18, fill="currentColor")) g.append(dp.AnimateTransform("rotate", from_=0, to=360, dur="8s")) svg.append(g) ``` -------------------------------- ### Create and reference elements with Use Source: https://py.dreamplet.com/reference/definitions Demonstrates creating an SVG element and using the Use class to reference it, including applying attributes like clip_path. ```python dp.Use(href: str | dp.SvgElement | None = None, **kwargs) ``` ```python heart = dp.Path( id="heart", d="M10,30 A20,20,0,0,1,50,30 A20,20,0,0,1,90,30 Q90,60,50,90 Q10,60,10,30 Z", ) copy = dp.Use(heart, fill="red") assert copy.href == "#heart" ``` ```python clip = dp.ClipPath(id="myClip").append(dp.Circle(cx=40, cy=35, r=35)) svg.ensure_defs().append(clip) svg.append( heart, dp.Use(heart, clip_path=clip.url, fill="red"), ) ``` -------------------------------- ### Get Font Size Source: https://py.dreamplet.com/reference/text The font_size getter returns the numeric value as a float. ```python text = dp.Text("Label", font_size="18px") print(text.font_size) # 18.0 ``` -------------------------------- ### Using Color Helper Functions Source: https://py.dreamplet.com/reference/colors Demonstrates usage of hexStr and str2rgb functions with assertions. ```python from pydreamplet.colors import hexStr, str2rgb assert hexStr(16) == "10" assert str2rgb("#f00") == {"r": 255, "g": 0, "b": 0} assert str2rgb("notacolor") == {"r": 0, "g": 0, "b": 0} ``` -------------------------------- ### Scaling Around a Pivot Source: https://py.dreamplet.com/reference/transforms Example of scaling a matrix relative to a specific pivot point. ```python matrix = dp.Matrix2D.scale_at(2, 3, 10, 20) print(matrix.as_tuple()) # (2.0, 0.0, 0.0, 3.0, -10.0, -40.0) print(matrix.apply(10, 20)) # Vector(x=10.0, y=20.0) ``` -------------------------------- ### Initialize SimplexNoise3D Source: https://py.dreamplet.com/reference/noise The constructor signature for the SimplexNoise3D class. ```python SimplexNoise3D(seed: int | None = None) ``` -------------------------------- ### Initialize SimplexNoise Source: https://py.dreamplet.com/reference/noise The constructor signature for the SimplexNoise class. ```python SimplexNoise(seed: int | None = None) ``` -------------------------------- ### Accessing marker stroke width Source: https://py.dreamplet.com/reference/markers Get or set the nested path stroke width. ```python marker.stroke_width -> Real | None marker.stroke_width = "2" ``` -------------------------------- ### Initialize Canvas and Scales Source: https://py.dreamplet.com/tutorials/line-chart Set up the SVG canvas and define linear and point scales for mapping data to coordinates. ```python svg = dp.SVG(800, 400) defs = svg.ensure_defs() axis_layer = dp.G() svg.append(axis_layer) margin = {"left": 50, "right": 105, "top": 18, "bottom": 50} dates = df["date"].to_list() min_value = df.select(products).min_horizontal().min() max_value = df.select(products).max_horizontal().max() scale_x = PointScale(dates, (margin["left"], svg.w - margin["right"])) scale_y = LinearScale((min_value, max_value), (svg.h - margin["bottom"], margin["top"])) x_values = [] for date in dates: x = scale_x.map(date) assert x is not None x_values.append(x) ``` -------------------------------- ### Accessing marker path data Source: https://py.dreamplet.com/reference/markers Get or replace the nested marker path data. ```python marker.d -> str marker.d = ARROW_CONVEX ``` -------------------------------- ### Initialize and Use Noise Source: https://py.dreamplet.com/reference/noise Create a bounded random walk generator and retrieve values. ```python from pydreamplet.noise import Noise walk = Noise(0.0, 100.0, 0.12, seed=4) values = [walk.value for _ in range(6)] ``` -------------------------------- ### Invalid SVG Constructor Arguments Source: https://py.dreamplet.com/reference/svg Examples of invalid arguments that raise a ValueError during SVG initialization. ```python dp.SVG(540) # ValueError dp.SVG(0, 0, 540) # ValueError dp.SVG("540", "360") # ValueError ``` -------------------------------- ### Importing pydreamplet and math modules Source: https://py.dreamplet.com/tutorials/dancing-circles Initializes the theme and imports necessary math functions for radial coordinate calculations. ```python from math import cos, radians, sin import pydreamplet as dp theme = dp.Theme() ``` -------------------------------- ### Initialize SimplexNoise2D Source: https://py.dreamplet.com/reference/noise The constructor signature for the SimplexNoise2D class. ```python SimplexNoise2D(seed: int | None = None) ``` -------------------------------- ### Create a Polyline instance Source: https://py.dreamplet.com/reference/shapes Instantiate an open polyline with stroke styling. ```python polyline = dp.Polyline( [20, 100, 70, 40, 120, 90, 180, 30], fill="none", stroke="#14b8a6", stroke_width=5, stroke_linejoin="round", ) ``` -------------------------------- ### SvgElement Signature and Initialization Source: https://py.dreamplet.com/reference/svg-element The constructor accepts a tag name and optional keyword arguments for attributes. ```python dp.SvgElement(tag: str, **kwargs) ``` ```python filter_node = dp.SvgElement("feDropShadow", dx=0, dy=4, stdDeviation=3) ``` -------------------------------- ### Configure Theme with overrides Source: https://py.dreamplet.com/reference/colors Load a custom JSON theme file and modify theme properties programmatically. ```python theme = dp.Theme("themes/light.json") theme.font_family = "Roboto" theme.font_size = 12 theme.font_weight = 600 theme.brand = (212, 136, 113) theme.muted = (212, 136, 113, 0.5) theme.gray = 128 assert theme.brand == "#d48871" assert theme.muted == "rgba(212, 136, 113, 0.5)" assert theme.gray == "#808080" assert theme.colors.brand == "#d48871" assert theme.colors["surface"] == "oklch(96.7% 0.001 286.375)" ``` -------------------------------- ### Generate and render a color palette Source: https://py.dreamplet.com/reference/colors Demonstrates generating a color palette and rendering it as an SVG. ```python import pydreamplet as dp palette = dp.generate_colors("#db45f9", n=8) svg = dp.SVG(360, 120) for index, color in enumerate(palette): svg.append( dp.Rect(x=20 + index * 40, y=24, width=34, height=52, rx=6, fill=color), dp.Text(str(index + 1), x=37 + index * 40, y=96, font_size=13, text_anchor="middle", fill="currentColor"), ) ``` -------------------------------- ### Animate SVG Attributes Source: https://py.dreamplet.com/reference/animation Example of appending Animate instances to a circle to modify its properties over time. ```python svg = dp.SVG(360, 180) svg.append(dp.Line(90, 90, 270, 90, stroke="currentColor", stroke_width=3, stroke_dasharray="8 8", opacity=0.35)) circle = dp.Circle( cx=90, cy=90, r=24, fill="currentColor", opacity=0.7, stroke="currentColor", stroke_width=4, ) circle.append( dp.Animate("cx", values=[90, 270, 90], dur="3s"), dp.Animate("r", values=[24, 38, 24], dur="3s"), dp.Animate("opacity", values=[0.45, 1, 0.45], dur="3s"), ) svg.append(circle) ``` -------------------------------- ### Initialize SVG and Access Attributes Source: https://py.dreamplet.com/reference/svg Demonstrates creating an SVG object and accessing its default viewBox, width, and height attributes. ```python svg = dp.SVG(540, 360) print(svg.viewBox) # 0 0 540 360 print(svg.width) # 540px print(svg.height) # 360px ``` -------------------------------- ### dp.Theme() Source: https://py.dreamplet.com/reference/colors Initializes a new theme object. Can be used with default settings or by providing a path to a JSON configuration file to override theme properties. ```APIDOC ## dp.Theme(path=None) ### Description Initializes a theme container for font settings and color tokens. If no path is provided, built-in defaults are used. ### Parameters - **path** (str) - Optional - File path to a JSON configuration file to override default theme settings. ### Usage ```python import pydreamplet as dp # Initialize with defaults theme = dp.Theme() # Initialize with custom JSON config theme = dp.Theme("themes/light.json") ``` ``` -------------------------------- ### Generate a line path Source: https://py.dreamplet.com/reference/generators Example usage of LineGenerator to create an SVG path string from coordinate tuples. ```python generator = dp.LineGenerator() assert generator([(0, 0), (10, 20), (30, 0)]) == ( "M 0.00,0.00 L 10.00,20.00 L 30.00,0.00" ) ``` -------------------------------- ### BandScale(domain, output_range, padding=0.1, outer_padding=None) Source: https://py.dreamplet.com/reference/scales Maps distinct categorical values to band start positions. ```APIDOC ## BandScale(domain, output_range, padding=0.1, outer_padding=None) ### Description Maps distinct categorical values to band start positions. Useful for bar charts. ### Properties - **bandwidth** (float) - Computed width of one band. - **step** (float) - Distance between band starts. ``` -------------------------------- ### Initialize PathBuilder Source: https://py.dreamplet.com/reference/paths Instantiate a new PathBuilder object. ```python dp.PathBuilder() ``` -------------------------------- ### Creating SVG paths with generators Source: https://py.dreamplet.com/reference/generators Demonstrates initializing line, area, and symbol generators and rendering them into an SVG container. ```python import pydreamplet as dp line = dp.LineGenerator(curve="catmull-rom") area = dp.AreaGenerator(y0=lambda _item, _index: 150, curve="linear") symbol = dp.SymbolGenerator(symbol=lambda item, _index: item["symbol"], size=180) points = [(24, 130), (82, 54), (148, 96), (214, 34), (290, 88)] symbols = [ {"x": 52, "y": 146, "symbol": "circle"}, {"x": 116, "y": 146, "symbol": "diamond"}, {"x": 180, "y": 146, "symbol": "triangle"}, {"x": 244, "y": 146, "symbol": "star"}, ] svg = dp.SVG(330, 180) svg.append(dp.Path(area(points), fill="currentColor", opacity=0.16)) svg.append(dp.Path(line(points), fill="none", stroke="currentColor", stroke_width=4)) for item in symbols: svg.append( dp.Path( symbol(item), fill="currentColor", transform=f"translate({item['x']} {item['y']})", ) ) ``` -------------------------------- ### Initialize the PyDreamplet Canvas Source: https://py.dreamplet.com/tutorials/combo-chart Sets up the necessary imports, file paths, theme, and SVG canvas dimensions with defined margins for axes and headers. ```python from pathlib import Path import pydreamplet as dp from pydreamplet.markers import TICK_BOTTOM, Marker from pydreamplet.utils import calculate_ticks from data_reader import read_combo_chart_data BASE_DIR = Path(__file__).parent DATA_PATH = BASE_DIR / "data" / "apple.csv" OUTPUT_PATH = BASE_DIR / "apple_combo_chart.svg" theme = dp.Theme() data = read_combo_chart_data(DATA_PATH) svg = dp.SVG( 1024, 680, font_family=theme.font_family, font_size=theme.font_size, ) margin = {"left": 88, "right": 88, "top": 112, "bottom": 72} plot_left = margin["left"] plot_right = svg.w - margin["right"] plot_top = margin["top"] plot_bottom = svg.h - margin["bottom"] ``` -------------------------------- ### place_labels_1d Source: https://py.dreamplet.com/reference/utilities Wraps resolve_collisions_1d and returns LabelPlacement records containing position, anchor, size, start, and end data. ```APIDOC ## place_labels_1d(anchors, sizes, *, gap=0, bounds=None) ### Description Calculates label placements by resolving collisions and returning structured LabelPlacement objects. ### Parameters - **anchors** (Sequence[Real]) - Required - Initial positions of the labels. - **sizes** (Sequence[Real]) - Required - Sizes of the labels. - **gap** (Real) - Optional - Minimum gap between labels. - **bounds** (tuple[Real, Real] | None) - Optional - Range to keep the full extent of labels within. ### Example ```python from pydreamplet.utils import place_labels_1d placements = place_labels_1d([0, 1], [4, 4], gap=1) ``` ``` -------------------------------- ### Initialize Text Element Source: https://py.dreamplet.com/reference/text Constructor signature for creating a new SVG text element. ```python dp.Text( initial_text: str = "", *, pos: PointLike | None = None, x: Real | None = None, y: Real | None = None, v_space: Real | None = None, **kwargs, ) ``` -------------------------------- ### Complete Polar Noise Script Source: https://py.dreamplet.com/tutorials/polar-noise Full implementation including SVG setup, filter definitions, and the animation loop. ```python import pydreamplet as dp from pydreamplet.noise import SimplexNoise2D theme = dp.Theme() noise = SimplexNoise2D(seed=42) svg = dp.SVG(1024, 1024) defs = svg.ensure_defs() shadow = dp.Filter( id="drop-shadow", x="-20%", y="-20%", width="140%", height="140%", ) shadow.append( dp.SvgElement( "feDropShadow", dx=0, dy=10, stdDeviation=8, flood_color="#000000", flood_opacity=0.65, ) ) defs.append(shadow) margin = 64 group = dp.G(pos=(svg.w / 2, svg.h / 2)) svg.append(group) shape_count = 8 line = dp.LineGenerator(curve="linear") offset = dp.Vector(1, 1) palette = dp.generate_colors("#db45f9", n=shape_count) min_radius = 20 max_radius = svg.w / 2 - margin radius_step = (max_radius - min_radius) / (shape_count - 1) wave_phases = (0, 90, 180, 270, 360) wave_duration = "7s" for shape_index, color in enumerate(palette): base_radius = max_radius - shape_index * radius_step wave_paths: list[str] = [] for phase in wave_phases: points: list[tuple[float, float]] = [] angle = 0.0 while angle < 360: direction = dp.Vector.from_polar(angle) noise_direction = dp.Vector.from_polar(angle + phase) radius = base_radius + noise.noise( noise_direction.x, noise_direction.y, frequency=1.5, amplitude=50, ) points.append((direction * radius + offset).xy) angle += 5 wave_paths.append(f"{line(points)} Z") path = dp.Path( wave_paths[0], opacity=0.75, stroke=theme.ink, fill=color, filter="url(#drop-shadow)", ) path.append(dp.Animate("d", values=wave_paths, dur=wave_duration)) group.append(path) svg.save("polar_noise.svg") ``` -------------------------------- ### Matrix2D Instance Methods Source: https://py.dreamplet.com/reference/transforms Methods for performing operations on an existing Matrix2D instance. ```APIDOC ## Matrix2D Instance Methods - **multiply(other: dp.Matrix2D) -> dp.Matrix2D**: Multiplies the matrix by another Matrix2D and returns a new matrix. - **apply(x: Real, y: Real) -> dp.Vector**: Transforms a point (x, y) and returns a Vector. - **as_tuple() -> tuple[float, float, float, float, float, float]**: Returns the matrix values as a tuple (a, b, c, d, e, f). ``` -------------------------------- ### Import pyDreamplet Source: https://py.dreamplet.com/reference/creative Initial import required to access creative helper functions. ```python import pydreamplet as dp ``` -------------------------------- ### Handling Path IDs Source: https://py.dreamplet.com/reference/text Demonstrates how path_id is handled when it already includes the hash prefix. ```python label = dp.TextOnPath("around", path_id="#curve") print(label.text_path.href) # #curve ``` -------------------------------- ### Sample SimplexNoise Source: https://py.dreamplet.com/reference/noise Generate 1D simplex noise values. ```python noise = SimplexNoise(seed=42) value = noise.noise(0.5, frequency=2.0, amplitude=1.5) ``` ```python noise(x: float, frequency: float = 1, amplitude: float = 1) -> float ``` -------------------------------- ### Configure Canvas and Layers Source: https://py.dreamplet.com/tutorials/layered-svg-art Initializes the SVG canvas and creates separate groups for the background circle and foreground arcs. ```python svg = dp.SVG(600, 600, width="300px", height="300px") circle_layer = dp.G() arc_layer = dp.G() svg.append(circle_layer, arc_layer) ``` -------------------------------- ### Importing Marker components Source: https://py.dreamplet.com/reference/markers Basic import statement for the Marker class and predefined path constants. ```python from pydreamplet.markers import ARROW_BASIC, Marker ``` -------------------------------- ### Create and save an SVG Source: https://py.dreamplet.com/getting-started Initialize a canvas, add a circle shape, and export the result to a file. ```python import pydreamplet as dp svg = dp.SVG(300, 300) circle = dp.Circle( cx=150, cy=150, r=90, fill="#14b8a6", stroke="#0f172a", stroke_width=4, ) svg.append(circle) svg.save("example.svg") ``` -------------------------------- ### Create measured layouts Source: https://py.dreamplet.com/text-basics Demonstrates using measured dimensions to dynamically draw surrounding shapes like rectangles around text. ```python from pydreamplet.typography import TypographyMeasurer, get_system_font_path font_path = get_system_font_path("sans-serif", 700) if font_path is None: raise RuntimeError("No sans-serif font is available on this system.") label = dp.Text( "pyDreamplet", x=0, y=0, font_family="sans-serif", font_size=42, font_weight=700, fill="currentColor", text_anchor="middle", alignment_baseline="middle", ) width, height = TypographyMeasurer(font_path=font_path).measure_text(label) group = dp.G(pos=(svg.w / 2, svg.h / 2)) group.append( dp.Rect( x=-width / 2, y=-height / 2, width=width, height=height, fill="none", stroke="#14b8a6", stroke_width=2, ), label, ) svg.append(group) ``` -------------------------------- ### Defining canvas and layout parameters Source: https://py.dreamplet.com/tutorials/dancing-circles Sets up the SVG dimensions and calculates radius steps based on the canvas width and margin. ```python svg = dp.SVG(1024, 1024) margin = 24 min_radius = 10 circle_count = 32 max_radius = svg.w / 2 - margin radius_step = (max_radius - min_radius) / (circle_count - 1) ``` -------------------------------- ### Registering and Instantiating SVG Elements Source: https://py.dreamplet.com/reference/svg-element Use register to map custom tags to subclasses, and from_element to create instances from XML elements. ```python dp.SvgElement.register(tag: str, subclass: type[SvgElement]) -> None dp.SvgElement.from_element(element: xml.etree.ElementTree.Element) -> SvgElement ``` -------------------------------- ### Render and Save the Chart Source: https://py.dreamplet.com/tutorials/waffle-chart Create the SVG object, apply colors to the generated paths, and save the output file. ```python svg = dp.SVG(side, side) colors = ["#14b8a6", "#f59e0b", "#6366f1"] for group_index, path_data in paths.items(): if path_data: svg.append(dp.Path(d=path_data, fill=colors[group_index])) svg.save("waffle-chart.svg") ``` -------------------------------- ### Initialize SVG Canvas Source: https://py.dreamplet.com/drawing-basics Create an SVG canvas with specified dimensions or a viewBox. Use width and height arguments to override display size independently of the coordinate system. ```python import pydreamplet as dp svg = dp.SVG(540, 360) ``` ```python svg = dp.SVG(10, 10, 540, 360) print(svg.viewBox) # 10 10 540 360 ``` ```python svg = dp.SVG(540, 360, width="1080px", height="720px") ``` -------------------------------- ### Initialize Animated Circles Source: https://py.dreamplet.com/tutorials/dancing-circles Creates circle objects with specific positions, radii, and stroke colors. ```python for i in range(circle_count): angle = radians(i * angle_step) r = min_radius + i * radius_step final_cx = max_radius * cos(angle) final_cy = max_radius * sin(angle) circle = dp.Circle( pos=(final_cx, final_cy), r=min_radius, fill=theme.transparent, stroke=colors[i], ) ``` -------------------------------- ### Import Typography Utilities Source: https://py.dreamplet.com/reference/typography Basic import statement for typography components. ```python from pydreamplet.typography import TypographyMeasurer, get_system_font_path ``` -------------------------------- ### Using the set_style Method Source: https://py.dreamplet.com/reference/svg-element Sets CSS styles using a dictionary with underscore-to-hyphen convention. ```python rect.set_style({ "paint_order": "stroke", "vector_effect": "non-scaling-stroke", }) ``` -------------------------------- ### Sample SimplexNoise3D Source: https://py.dreamplet.com/reference/noise Generate 3D simplex noise values. ```python noise = SimplexNoise3D(seed=42) frame_value = noise.noise(0.25, 0.75, 0.1, frequency=1.8) ``` ```python noise( x: float, y: float, z: float, frequency: float = 1, amplitude: float = 1, ) -> float ``` -------------------------------- ### Sample SimplexNoise2D Source: https://py.dreamplet.com/reference/noise Generate 2D simplex noise values. ```python noise = SimplexNoise2D(seed=42) value = noise.noise(0.25, 0.75, frequency=1.8) ``` ```python noise(x: float, y: float, frequency: float = 1, amplitude: float = 1) -> float ``` -------------------------------- ### Marker constructor signature Source: https://py.dreamplet.com/reference/markers The signature for initializing a new Marker instance. ```python Marker( id: str, d: str, width: Real, height: Real, **kwargs: Any, ) ``` -------------------------------- ### Importing Color Helpers Source: https://py.dreamplet.com/reference/colors Import the available utility functions from the pydreamplet.colors module. ```python from pydreamplet.colors import hexStr, random_int, str2rgb ``` -------------------------------- ### Generate Visual Layouts with Points and Tiles Source: https://py.dreamplet.com/reference/creative Demonstrates using phyllotaxis points and hexagonal tiles to construct an SVG layout. ```python import pydreamplet as dp svg = dp.SVG(360, 180) for point in dp.phyllotaxis_points(90, spacing=6, center=(95, 90)): svg.append(dp.Circle(cx=point.x, cy=point.y, r=2.8, fill="currentColor")) for tile in dp.hex_tiles(5, 3, 14, origin=(220, 42), gap=4): points = [] for corner in tile.corners: points.extend(corner.xy) svg.append(dp.Polygon(points, fill="none", stroke="currentColor", stroke_width=2, opacity=0.65)) ``` -------------------------------- ### dp.SVG(width, height, viewBox_x, viewBox_y, width, height) Source: https://py.dreamplet.com/reference/svg Initializes a new SVG object. The constructor supports defining the coordinate system via viewBox parameters and setting the rendered output dimensions. ```APIDOC ## dp.SVG(width, height, width=None, height=None) ### Description Creates an SVG instance. If only two arguments are provided, they define the viewBox width and height starting from origin 0,0. Providing four arguments defines the viewBox origin (x, y) and dimensions (width, height). ### Parameters - **width** (int/float) - Required - The width of the viewBox or the width of the SVG. - **height** (int/float) - Required - The height of the viewBox or the height of the SVG. - **width** (int/float) - Optional - Explicit rendered width. - **height** (int/float) - Optional - Explicit rendered height. ### Example ```python # Basic initialization svg = dp.SVG(540, 360) # Initialization with explicit origin svg = dp.SVG(-270, -180, 540, 360) # Initialization with explicit rendered dimensions svg = dp.SVG(540, 360, width=1080, height=720) ``` ``` -------------------------------- ### Initialize PathCommand Source: https://py.dreamplet.com/reference/paths Create a PathCommand instance to represent an SVG path command and its associated numeric values. ```python command = dp.PathCommand("l", (10.0, 20.0)) print(command.is_relative) # True print(command.absolute_command) # L print(command.to_string()) # l10 20 ``` -------------------------------- ### dp.Polyline(points: list[Real], **kwargs) Source: https://py.dreamplet.com/reference/shapes Initializes an open polyline shape defined by a flat list of coordinates. ```APIDOC ## dp.Polyline ### Description Represents an open element. The points parameter requires a flat list of coordinates [x0, y0, x1, y1, ...]. ### Constructor `dp.Polyline(points: list[Real], **kwargs)` ### Properties - **points** (list[Real]) - Flat coordinate list: [x0, y0, x1, y1, ...]. - **bbox** (object) - Bounding box covering all points. ### Example ```python polyline = dp.Polyline( [20, 100, 70, 40, 120, 90, 180, 30], fill="none", stroke="#14b8a6", stroke_width=5, stroke_linejoin="round", ) ``` ``` -------------------------------- ### Initialize LineGenerator Source: https://py.dreamplet.com/reference/generators Constructor signature for the LineGenerator class. ```python LineGenerator( *, x: Accessor[T] | None = None, y: Accessor[T] | None = None, defined: Callable[[T, int], bool] | None = None, curve: CurveName = "linear", tension: float = 0.0, ) ```