
Having a good environment is a step further into developing quality software. We will install Visual Studio Code with some essentials extensions + node.js + Github desktop + Angular cli
Our first project, DashboardOne, will be our support to start delving into svg and introduce d3.js to angular.
Having created our project we will now add the d3 and bootstrap npm dependencies.
We will be using bootstrap as a support library to simplify the html coding so we can focus more on d3.
In this lesson we will create the dashboard component. We will be adding our test charts to visualize our work while learning about d3
Decompose charts into simple components: circles, lines, rectangles, and text, and position and style them to create interactive charts in Angular using D3. The same elements build different chart types.
Why choosing the SVG format? What advantages does it bring to our charts?
Map a data array to SVG rects to create a column chart. Style the bars with inline or CSS and adjust x and y positions; note they render upside down.
Invert the y axis in svg charts by computing each rectangle's y as the svg height minus its height, and generate the rectangles with an Angular for loop.
Resize the rectangles to fit the svg by setting each width to the svg width divided by the number of rectangles, using angular elementRef and getBoundingClientRect to adapt on init.
Scale chart heights by mapping data values to pixels using a 250-pixel reference, compute the max with the spread operator, and update the rectangle heights and y positions.
Define left, right, top, and bottom margins; compute inner width and height from the SVG dimensions; update dimensions accordingly and reserve space for legends.
Learn how SVG line elements use x1, y1 and x2, y2 to define start and end, style with stroke and stroke-dasharray, and animate all parameters with CSS.
Explore svg path commands with d3 and Angular, including move, line, horizontal and vertical lines, cubic and quadratic bezier curves, and arc parameters with flags to generate figures.
Create an svg project to test svg path and add a grid. Add horizontal and vertical grid lines every 100 pixels, style with a dashed stroke, and control opacity.
Learn how to build polygons with SVG path commands, including move, line, horizontal and vertical variants, relative versions, and closing with Z, plus setting stroke and fill.
Create non-polygon svg paths using quadratic and cubic bezier curves with control points and end points, styled with a blue stroke and white fill.
Explore the svg text element to label charts with x and y positioning, rotation, font size, color, and text anchor for alignment; also render curved labels with a text path.
Add a horizontal axis by drawing an SVG line with x1, y1, x2, y2 coordinates, style it with CSS stroke on the x axis, and position it at y=50.
Learn to make a chart input-driven using ngOnChanges, resize on data changes, and refactor to SetParams for API data and D3 integration.
The SVG specs. Basic elements: Rect, Circle, Line, Path, Polyline
To better understand how svg works, we will create a basic column chart by manually writing all the elements
In this lesson we will introduce d3 to angular and learn how to create the same column chart by using d3.
D3 keywords: select, selectAll, enter, append
Explore the d3 update pattern by binding data to a selection, using enter and exit with groups to append three rectangles for data 10, 20, and 30.
Bind data to rectangles with d3, use enter to set height 10,20,30 by index, position with i times width and padding, then style with blue fill using .style() and .attr().
Explore the D3 update pattern to handle changing data by updating existing elements, appending new ones with enter, and managing removals with exit to reflect data changes in a chart.
Learn how the D3 update pattern handles exit selections by removing elements, updating remaining rectangles’ heights with accessor functions, and properly clearing attributes using null.
Recreate chart two using D3 by importing input data from Angular core, wiring data into rectangles based on employee age, and handling undefined data with ngOnChanges and a draw method.
Apply scaleLinear to map employee age and salary to chart coordinates, fix variable usage for height and y, and use max salary to scale rectangles for consistent visuals.
Add left, right, top, and bottom margins to the chart and adjust the x domain and y range with inner width and inner height.
Learn to simplify d3 charts in angular by using a data container. Translate for margins, place rectangles, and use inner height for sizing.
Discover the d3 axis, its four position types, and how to customize styling by selecting elements, applying properties, and appending axes to containers using scales.
Practice adding a vertical y axis to the chart in d3 by creating a y axis container and a left-positioned y axis, then adjust the left margin for proper fit.
Learn to customize D3 axes beyond default styles by using axis methods and post-selection, controlling tick counts, formats, and custom tick values mapped from the scale’s max.
Style D3 axis grids and ticks, apply selective styling to lines only, and add a rotated y-axis label by wrapping text in a container and positioning it with margins.
Replace axis ids with employee names by binding names to tick elements, rotate labels 45 degrees, adjust margins and translation, and implement set labels to organize chart for future data.
This lecture demonstrates the d3 update pattern to toggle between full and filtered data using a getter and a data state, updating enter, update, and exit to redraw the chart.
Learn how the d3 update pattern binds data to bars and uses enter, update, and exit selections, with colors illustrating each phase.
Add the iris dataset to the API by implementing a get iris method that fetches a CSV from GitHub, parses it into JSON objects, and applies a three-time retry.
Implement in-chart dropdowns for a D3 and Angular chart, managing two selects (x and y) inside the chart via a short form component, with responsive styling.
Finish the dropdowns in the interactive chart by wiring two selections, x and y, to capture changes, populate options from columns, handle empty data, and prepare the update chart method.
Create empty methods for set dimensions, set elements, set params, set labels, set axis, and draw to structure the svg chart before adding data.
Implement the scatterData getter to produce numeric x and y points from the selected sepal length and sepal width, returning an empty array until both values are chosen.
Define x and y linear scales with domains and inverted ranges using inner width and height, compute max values from data with the D3 math function, and finalize parameters.
The src for the angular initial setup, already with chart 5, is available here in the src.zip
Add a chart component in Angular by generating a new charts component, wiring input data from Angular core, and embedding the Covid data dashboard in the app HTML.
Implement chart methods by setting dimensions, elements, params, labels, axis, legend, and draw, then update the chart on changes and initialize on init.
Explain d3 time concepts by converting strings to dates with timeParse and formatting them with timeFormat, while configuring x time scales, y linear scales, and color scales.
Define the x domain from dates, handle null data, and build multiple line series (hospitalized, deaths, hospitalized currently) with date/value points for SVG paths.
Bind data to legend items, create entering elements, append circles and text, and position with padding and radius; merge updates colors and labels for all legend items.
Reposition the legend in an interactive D3 and Angular chart by recalculating item widths, padding, and centering the legend for accurate alignment.
Implement mouse over and click events to manage default, over, and inactive states, highlighting hovered legend lines and toggling visibility based on selected data and active status.
Bind the legend onClick to receive the event and item name, toggle the corresponding active line by index, and redraw the chart after each toggle in d3 and angular.
Add a chart component to an Angular app by creating an SVG with class short six, importing ElementRef, configuring view encapsulation none, binding input data, and rendering with D3.
Define the config interface for a donut chart by outlining inner radius coefficient, hidden opacity, legend item properties, transition timing, and arc attributes, then move margins into the config.
Explore implementing chart methods in a D3 and Angular setup, including setting the svg dimensions, elements, legends, and drawing, with update chart and highlight interactions on data or config changes.
Compute chart dimensions using the SVG's bounding client rect to derive inner width and height after margins, then calculate radius and inner radius, and position chart containers.
Define setParams to initialize an arc generator with inner and outer radii, a pie generator with a value, and a category ten ordinal color scale with IDs.
Learn to implement the set labels method by extracting the title, ensure set dimensions and set elements run on ngOnInit, and then update the chart.
Implement the set legend method by creating containers, adding legend items, symbols and labels, binding API data, and centering the legend using dimensions and margins.
Implement mouse enter, mouse leave, and click interactions on the legend to highlight the corresponding arc, fade others, and redraw the chart.
Define and wire legend mouse events, including enter, leave, and click, to toggle visibility by updating hidden IDs, filter pie arcs, and redraw the chart.
Improve arc transitions in interactive charts by refining the arcTween method to handle enabling and disabling edges, interpolating start and end angles, and maintaining smooth, sequential animations.
Learn how arcTween: enter animates new edges by binding previous and current data, extending previous data with the enter selection, and interpolating start and end angles for new elements.
Convert the chart configuration into an input, enabling two charts with distinct configurations (donut and pie), and implement a default and private config with deep copying to preserve styling.
We will create the method UpdateObjectWithPartialValues which allow us to set only some properties of an object, while keeping all the other properties unchanged
Create chart component with ng generate component, define input data and config, switch to string template with inline styling for svg class, and wire data into app component HTML.
Map API data to a multidimensional chart by structuring each element with year, gender, and age group, and convert incoming data to the domain, group, stack, and value format.
Learn to build interactive charts with d3 array by grouping and roll up data using group, groups, roll up, and flat roll up to sum by year, country, and gender.
Map each data element to domain, group, and stack using year, gender, age group, and value; define a unique key and build reusable helpers for flexible data transformation.
Define interfaces for group stack data and stack config, then use the stack helper to set stacks with population data by year, gender, and age group in millions.
Explore the anatomy of a d3 chart by structuring dimensions, margins, and inner dimensions with reusable helpers, then assemble axes, svg containers, legend, tooltip, and color scales.
Define chart structure by setting dimensions, elements, parameters, labels, axes, legend, and the draw method, with tooltip and highlight methods driven by events to update chart on init.
Define a default group stack config with opacity, transition, and margins, importing the correct interfaces. Implement a getter that returns the default when config is missing.
Setting a helper to calculate the most common points used in the chart
Import short dimensions, define setDimensions with a new short dimensions from the dome rect and margins, and store the resulting dimensions as a global variable.
Implement the set elements by creating and positioning the x axis container, y axis container, data container, legend, tooltip, title, and y label, using margins and transforms.
Define setParams by configuring x domain as years, y from the max stack total, width and height ranges, group scale bandwidth, and colors with domain stack IDs using interpolate spectral.
Reorder charts by adjusting the app component HTML to place the pie chart on the left and the stacked bar chart on the right.
For this lecture we will visit the d3-scale-chromatic github page to understand how to use the d3 color library
Apply a value formatter to the stack helper to transform data into millions by dividing values by 1 million, enabling setStacks without breaking when data changes.
Learn to stack data with d3.stack in practice using a year-based dataset with apples, bananas, cherries, and dates, converting data to stack arrays and rendering rectangles with scales and colors.
Build stacked data by domain and group to visualize year and gender across domains, using stacks and scales to color each key and refine the data for correct ordering.
Learn how to implement a sorting facility for stacked charts by specifying stack order and stack IDs, adjusting the data (CSV) and legends with short names to fit the chart.
Add a legend to the chart by creating legend item containers with rectangles and labels, then add the rectangles and text elements and finally reposition the items.
Explore tooltips in interactive charts by designing both svg and div tooltips, sizing and positioning them to convey the data message clearly with proper titles, units, and responsive resizing.
Learn how to simplify stacked data in D3 and Angular by using flatmap, min and max, and key-based filtering, while handling missing data with domain and group.
Refactor the drawRectangles method to render rectangles directly from a flat data array, replacing series containers with d.max and d.min bounds, adding color, and preparing the tooltip.
Define interfaces for tooltip data in interactive charts, map title, color, key, and value from stack data, and convert the tooltip to an arrow function for chart context.
Learn how to set up a tooltip in an interactive chart by binding tooltip data to title and value, fixing bugs, updating key and color, and preparing for positioning.
Configure tooltips by setting x and y padding, background color, and label properties like font size, height, and text separator to position and style svg tooltips.
Improve tooltip usability by implementing show and hide methods for the tooltip container with visibility styling, and address flickering by adjusting its positioning.
Improve tooltip show and hide in D3 and Angular charts by updating on rectangle entry, moving with the svg, and hiding when leaving the svg area.
Highlight the corresponding series and legend items on legend hover in interactive D3 charts with Angular, updating highlights on mouse enter and reset on leave, and prepare for click events.
Improve bar transitions on toggle in an interactive D3 and Angular chart by adding enter transitions for new rectangles with zero height and millisecond durations for smooth visual cues.
Improve interactive charts by ensuring disabled elements do not highlight or fade others, and apply the same fade to legend labels and legend items.
Add a transition to the y scale and y axis so removal animates the chart, using the slow duration to match the short duration.
Fix legend highlight for charts with groups and stacks by choosing stack data when available and otherwise using group data, ensuring accurate legend interactions in D3 and Angular.
Build an interactive map visualization using geojson data, projections, and path functions to render svg polygons across world layers, with tooltips and a covid-19 daily deaths timeline.
Add geo data via a countries geo data API to power an interactive D3 chart in an Angular app. Fetch json from assets, wire observables, and render geo arcs.
Combine two observables—covid by country data and country codes—from map countries.json using RxJS combineLatest to produce a single data stream, then subscribe and unsubscribe on destroy.
Create a map helper to convert covid data, including deaths, into map-ready format by mapping locations to iso3 codes and grouping data by date, with a title showing current date.
Set the dimensions on a dimension surface, define elements, parameters, labels, and legend, then draw the method and highlights using a non-linear scale and a map tooltip event emitter.
We are moving the DimensionHelper class into an angular service that can be injected into the charts
Set the map projection and path to convert polygons into an SVG path, then configure features and colors for the interactive charts, and next lesson explores projections.
Install topojson and import it into an angular chart; convert topojson to geojson with feature method and bind features to a path to render a map, addressing data loading timing.
Explore d3.geoPath and d3.projection by examining default scale (152.63), default translate (480 by 250), and default center (0,0), then adjust scale and translate to see projections update.
Draw data layers by filtering features using iso3 codes and binding to data features for the update chart. Use a color function to map values and gracefully handle nulls.
Set a single chart label from data.title and style it with svg attributes: text-anchor middle, font size 12, bold, dominant-baseline middle, and a 40 px top margin.
Bind threshold data to legend items, create and position legend item containers with rectangles and text, and wire mouse and click interactions.
Highlight legend items and features on mouse enter, reset on mouse leave, using data-driven highlighting with a highlighted class and a black stroke for rectangles.
Implement legend highlights in a d3 and angular chart by color-based feature selection, converting colors to rgb with d3 color, applying highlight and faded styles, and adding reset for base layer and feature data.
Develop the timeline tooltip and map tooltip components, use absolute positioning with left and top, and implement a tooltip state (visible, x, y) driven by the tooltip event payload.
Set up a timeline tooltip component in Angular by configuring inputs, host access, SVG dimensions, and margins.
Define the interfaces for the timeline tooltip, including tooltip state, timeline data, and timeline config, with properties for visibility, position, title, active time, margins, dimensions, and typography.
Implement a timeline tooltip in a D3 and angular map by defining tooltip state, mapping country IDs to names, and wiring tooltip data to the map display.
Set up the SVG elements for the timeline tooltip, including title, axis and area/line paths, plus an active data container with a circle and labels, bound to map data.
Fix the tooltip overflow by adjusting the app component: set the width to the max content and add a z-index of ten, removing overflow hidden from the short styling.
Set update chart parameters, labels, lines, and active data; compute the maximum value and active value from the current time, then configure scales and the area and line functions.
Set up x and y scales for the timeline chart with d3. Define the x domain from min to max date and the y domain from zero to max value.
Explore implementing d3 timeline visuals using setArea and setLine, defining y zero and y one with a date domain, and handling null values to skip drawing.
Update the timeline tooltip styling by correcting position, applying the background color, and setting title and label typography—alignment, font size, weight, and anchor during the chart update.
Draw the timeline line and area using drawLine and drawArea in a D3 and Angular chart, styling with rgb(253, 141, 60) stroke and 0.5 opacity for the area tooltip.
Update the timeline tooltip configuration by adding line stroke, area fill, and opacity, and extend the axis with color and optional dasharray for customizable tooltips.
Adjust tooltip positioning in the map helper by tweaking coordinates (270px width, 150px height) to place the tooltip near the cursor, e.g., 125, with 20 pixels above the mouse.
Install and add the play slider component to the app HTML before the map tooltip, and style the short body and controller for a 250-pixel height.
Create a play slider component with a play/pause toggle, a range input, and custom slider styling, wired to change events in an Angular D3 project.
Fixes the timeline tooltip by anchoring the date text to start on the left and to end on the right, ensuring the current date stays visible.
Update the map config to set title font weight and size, base fill and stroke, data label colors, and color schemes for d3 and angular maps.
Learn to resize charts by handling window resize events with a debounce time in RxJS, in an Angular and D3 setup, and manage subscriptions to implement the resize chart method.
Adjust chart dimensions, then reposition elements and set parameters, data, features, labels, legends, and draws, then resize and update the chart, testing with the map to verify correct resizing.
Enable strict mode, install d3 and topojson types, and update the config with required properties; then adjust code to fix typing errors and initialize variables in components.
Set up tsconfig and angular compiler options, install the type files for these three and topojson, and fix implicit typing and missing initializers when serving the app.
Debug the application by tracing undefined config and data errors, define config as null for the default, and fix filtered and stacked data to restore maps and bar chart.
Fix the timeline tooltip error in the interactive charts with D3 and Angular by marking the max value as optional with a question mark, preventing undefined data from breaking computations.
The source code for the strict mode can be found here in the resources. However, You'll need to add the missing packages and change the tsconfig.json in order for the application to work.
Create a swarm chart from demographics data by continent and year using force simulation and Voronoi partitions, then build reusable base charts, legend and tooltip services, and optimize performance.
Define the component and interfaces for swarm config and ai swarm data, implement the dimension and tooltip services, and apply a force to circles with the d3 color scheme.
Create the short line component with inline template and style, skip tests, move the map within the app and insert the new chart, then explore the API and interfaces.
Set up an Angular app component to fetch demographics from the API, subscribe to the demographics swarm observable, and convert data to the final format using a swarm helper.
Define interfaces for chart data, establish the swarm helper with data and set data methods. Assign five attributes: id, label, value, category, group to drive tooltips, year, and continent coloring.
Finish the setData method by converting an array of items into swarm data elements, including id, label, category, group, and value, with a configurable rounding function for decimals.
Set up a swarm helper in the app component, configure data mappings (title, category, id, label, value, group, units), and update it with converted data for the chart.
Design a reusable chart base for swarm charts by outlining common methods, inputs, and events; extend it to create specific charts with shared resize, update, and tooltip logic.
Extend the chart by subclassing the base chart into a swarm short component, wiring input data, config, and output events, and calling the superclass constructor to demonstrate inheritance.
Continue building the short chart component by handling init, resize, and chart updates with RxJS subscriptions, setting SVG, dimensions, and elements, then updating the chart on resize.
Select the SVG element from the host and apply the set SVG attributes, add more elements for a standards-based profile, and declare the type as SVGSVGElement to implement set dimensions.
Define base SVG dimensions from the node and update the surface with config margins, then set the viewBox; make set elements, set params, set labels, set legend, and draw abstract.
Set up the SVG chart elements for an interactive D3 and Angular chart, append the title and Y label, set up the axes and data containers, deferring legend and Voronoi.
Set groups for a D3 and Angular chart by using the group key as continent names and sorting alphabetically. Initialize data and map groups to arrays.
Implement the set scales for x, y, and color using D3, define the x domain as years with a zero to inner width range, and adjust grouping by category.
Define a linear y scale with a domain (min to max) and a range from inner height to zero, using extent and accessors, while handling empty data and undefined values.
Define margins to fit the axis, set up x and y axes, adjust scales and padding, remove last tick, apply grid lines with styled ticks, and refine for readable charts.
Define and apply scaled data for Type II swarm data elements by transforming data elements with x and y scales, preserving properties, and prepare to feed into the simulation.
Apply force simulation to scaled data, using force X, force Y, and force collide to move nodes toward target positions; visualize dynamics through ticks and adjustable strength.
Discover the abstract legend service for interactive charts with d3 and angular, defining data and config, and implementing generate, update, and set legend items with repositioning and highlighting.
Define legend interfaces for the legend service, including a legend item with id, label, color, and a legend data list of items; set default data to an empty items array.
Implement the click event in the legend to toggle visibility and styling of chart items, fading inactive items to 0.3 opacity and restoring them on re-click.
Highlight methods identify a group by id via the legend, fade other items with opacity, and reset highlights when the legend interaction ends.
Improve the legend by preventing disabled items from affecting the chart when hovering over Africa, using an id check for hidden groups to keep other points interactive.
Explore advanced legend interactions in interactive charts with D3 and Angular, including onMouseClick variations, selecting and toggling groups, and updating hidden items.
Implement hide all orders, reverse hidden, and the natural click behavior in the list legend service, using item ids and updating styles while emitting events.
Explore circle highlights in interactive charts by hovering over a circle to fade unrelated points, display a tooltip with the point information (Denmark, 1970), and highlight related time series.
Append a time series line as an SVG path, hidden until a circle is highlighted; build it with x/y accessors, filter and sort by id and x, then bind datum.
Improve styling of interactive charts by applying a black stroke to highlighted elements and increasing their radius to three, while inactive ones stay at radius two.
Create a new tooltip service, export the class, decorate it with Angular core's injectable, and inject it via the constructor so it is available in the chart.
Move tooltip interfaces to a dedicated file and import tooltip data and config, then update components to use the new file so the chart works again.
Learners will implement the setTooltip function, assign tooltip data including year, category, color, country name, and value, and trigger showing the tooltip on the chart.
Learn to build and customize a tooltip service for D3 charts in Angular, using setElements to update data, styling via font size and weight, and accurately positioning the tooltip.
Learn to implement a tooltip positioning service in a D3 and Angular chart, computing x and y via the three-pointer method, translating the tooltip, and flipping sides to avoid clipping.
Adjust tooltip position by compensating for tooltip background padding with background x padding and background y padding, then apply config offset x to place it at the upper left corner.
Configure tooltip offsets to align with the circle position, applying horizontal offsets for left, right, and middle, and vertical adjustments for top and bottom.
Determine tooltip alignment in D3 and Angular interactive charts by comparing the x coordinate to the chart center and returning left or right positions.
Explore Delaunay triangulation and Voronoi partitions to simplify pointer navigation and tooltips in interactive charts. Learn to compute triangle circumcenters and map regions to circles for responsive highlighting.
Fix a legend onMouseClick bug by syncing legend clicks with item resets, updating highlights and IDs so Europe and Asia render immediately, then proceed with Voronoi development.
Update the voronoi to reflect filtered data by removing hidden legend items and resetting the voronoi on legend clicks, drawing updated partitions for regions like North America and Europe.
Finish the swarm chart by adapting chart seven to the new tooltip service, implement the changes, and return after completing the update.
Add an onMouseLeave handler in the draw rectangles method to reset highlights and apply a 300 millisecond opacity transition for smooth fading.
D3 is such a powerful language, however it can be difficult to start with.
Angular is an amazing framework but it lacks in data visualizations.
We will connect both worlds and create together amazing interactive charts that will bring your pages to another level.
For the absolute beginners, we will start from zero, understanding the d3 library, how it works, and how to use it. We will go into a depth analysis of the d3 update pattern so you can master the library and avoid the most common mistakes beginners do.
You will connect to api services and transform your data into the right format for each chart.
You will learn the SVG format and standards and how you can use it to create your own customized data visualizations.
We will use angular services and asynchronous data flows to inject data on the charts,
If you already know d3, you will learn about more advanced concepts, using the different d3 libraries, like the d3-array, the d3-force, voronoi partitions and others.
We will create legend and tooltip services, sending and receiving actions to charts and reacting to user inputs.
We will move into reusable charts by creating basic charts and extending them using inheritance.
Finally, you will end the course with a solid base to create your own reusable charts building upon the foundations of what you study here.
Welcome to the world of d3 and angular!