Visualizing an Animal Popularity Poll with D3.js: Exploring SVG and Square Root Scales

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This Article
This article is generated via an automated workflow leveraging generative AI. Using mock data and browser interactions, you will learn the use cases, mechanics, and failure observation points of D3.js. No access to real services or personal information is made.

Verification Status: Verified against official documentation and HTML/JavaScript from a fixed GitHub commit on October 30, 2026. Actual browser interaction, CDN fetching, rendering, and audio output have not been executed; the results in the text represent expected values from the code.

ItemDescription
Target AudienceModern browsers such as Chrome, Edge, and Firefox (device compatibility unverified)
Libraries UsedD3.js (tutorial version: 7.9.0)
CostNo paid APIs required for the demo source. Data rates and usage terms depend on your environment
DataMock data within the page. No authentication, location, or corporate data required
Learning ActionUpdate the circle size and vote count each time a vote is cast for an animal
  1. Why Try This Technology?
  2. First to try: Live demo and expected results
    1. Things to check before operation
    2. Overview of the mechanism
    3. Local verification when the public demo is unavailable
  3. D3's select targets DOM elements, and data binds each element to data. join handles creating, updating, and deleting elements collectively when the number of items to display changes. Because SVG is a vector format that can be embedded in HTML, it can hold circles and text as separate elements. The radius of the circles in this implementation is converted to a square root scale using scaleSqrt rather than directly multiplying the vote count. This is because the area of a circle is proportional to the square of its radius, and making the radius directly proportional to the numerical value would exaggerate differences in quantities.
    1. The above is an excerpt highlighting the main points of the API. It is not a complete, standalone executable file.
  4. Even if you change the colors for each animal, display the names rather than relying solely on color. If you are adding a bar chart to SVG, you can use the same data array to create multiple display formats. Setting the transition duration to 0 updates the view instantly, but the magnitudes of the values themselves do not change. To avoid altering data processing when changing presentation styles, separate the value update functions from the rendering functions.
  5. If there are too many circles, the labels will overlap and become unreadable. Also, even with properly adjusted circle areas, scattered circles alone can make it difficult to accurately compare rankings. If order is important, a bar chart may be more suitable. Furthermore, you must verify rendering consistency under the assumption that multiple updates may occur mid-transition. Because this demo does not persist votes, reloading resets them to the initial values.
  6. Application to business and learning
    1. Decisions to make before implementation
  7. Comparison with alternative methods
  8. GitHub repository
  9. Official information and primary sources
  10. Additional notes on the verification scope

Why Try This Technology?

While there are many charting libraries available, D3.js offers a high degree of freedom to construct custom visual expressions manually. This topic features a mock animal popularity vote, displaying the vote counts for pandas, cats, and owls as circles. Pressing the vote button enlarges the circle and updates the vote count text. This educational material goes beyond simply resizing circles to observe how value changes bind to DOM elements. Before choosing a charting library, consider whether standard bar charts suffice or if custom visual representations are required.

When creating a working sample, rather than stopping at the mere fact that the interface responds visually, you need to distinguish which input modifies which variable and which process updates the rendering. In this learning material, those changes are explicitly indicated on the screen. When integrating into an actual service, design authentication and persistence processes separately.

First to try: Live demo and expected results

Initially, there are fictional values of 3 votes for the panda, 2 votes for the cat, and 1 vote for the owl. Cast a vote for the cat and observe whether the circle radii become equal when it ties with the panda. Next, reset all animals to 0 votes and verify that the names of each animal and 0 votes remain even if the circles disappear. The total vote count is shown in text at the bottom of the screen. Since it is difficult to read the exact vote count from an image of circles alone, a key point is to always display the numerical text alongside it.

Things to check before operation

  1. Verify that your PC can execute JavaScript. Administrator privileges are not required.

  2. Open the browser's developer tools and prepare to check the Console for errors and the Network tab for CDN fetch failures.

  3. If the demo is not actually published, save the Daily Codeindex.htmlandapp.jsin the same folder and open them using a local HTTP server. When using modules, direct execution via file:// is not guaranteed to work.

  4. Compare the results before and after the operation. If they differ from the expected values, first record what failed to display.

Overview of the mechanism

flowchart LR
    A["入力やクリック"] --> B["イベントを受ける"]
    B --> C["D3.js のAPI"]
    C --> D["状態と描画を更新"]
    D --> E["見た目と文字で確認"]

This diagram is a conceptual illustration for learning purposes and does not represent the internal implementation of the browser or the details of network communication. Regardless of the library used, tracking which operations reach which variables is consistent.

Local verification when the public demo is unavailable

From the Raw view on GitHub, download the fixed commit'sHTML bodyandJavaScript bodyrespectivelyindex.htmlandapp.jsSave to the same new folder as . The README alone will not work. On Windows, open PowerShell in that folderpy -3 -m http.server 8000 --bind 127.0.0.1, and on Linux/macOSpython3 -m http.server 8000 --bind 127.0.0.1, then open on the same PC. To exit, use in the terminalhttp://127.0.0.1:8000/. Because the browser fetches the library itself from an external CDN, if a connection cannot be established, check the Console and Network errors. This procedure is a reproduction guide, not an actual browser measurement report for this article.Ctrl+CHow it works: Deciphering the API

D3's select targets DOM elements, and data binds each element to data. join handles creating, updating, and deleting elements collectively when the number of items to display changes. Because SVG is a vector format that can be embedded in HTML, it can hold circles and text as separate elements. The radius of the circles in this implementation is converted to a square root scale using scaleSqrt rather than directly multiplying the vote count. This is because the area of a circle is proportional to the square of its radius, and making the radius directly proportional to the numerical value would exaggerate differences in quantities.

How to read the minimal code

The above is an excerpt highlighting the main points of the API. It is not a complete, standalone executable file.

const scale = d3.scaleSqrt().domain([0, 30]).range([0, 75]);
svg.selectAll("circle").data(votes, d => d.name).join("circle")
  .attr("r", d => scale(d.count));

Please check the README and demo files on the Daily Code side for the complete HTML and implementation required to run it. Trace which functions select HTML elements and which lines update numerical values, and test with known fictitious values.Changing only one condition and comparing

Even if you change the colors for each animal, display the names rather than relying solely on color. If you are adding a bar chart to SVG, you can use the same data array to create multiple display formats. Setting the transition duration to 0 updates the view instantly, but the magnitudes of the values themselves do not change. To avoid altering data processing when changing presentation styles, separate the value update functions from the rendering functions.

The procedure for comparison is to record the initial values, change only one location, and verify whether the result appears in the expected area. Changing multiple inputs at once makes it impossible to determine what caused an effect. Validate the process including the operation to revert to the pre-change state.

Where to look when something goes wrong

If there are too many circles, the labels will overlap and become unreadable. Also, even with properly adjusted circle areas, scattered circles alone can make it difficult to accurately compare rankings. If order is important, a bar chart may be more suitable. Furthermore, you must verify rendering consistency under the assumption that multiple updates may occur mid-transition. Because this demo does not persist votes, reloading resets them to the initial values.

Observed state

Points to isolateExample responseExample response
The screen remains in its initial state.Script acquisition, initialization, and event registrationCheck Console, Network, and script tags
The display changes, but the meaning is incorrect.Input values, arrays, units, and update targetsFix the values and verify one condition at a time.
The button cannot be clicked.Selectors and DOM generation orderCheck the HTML to ensure the IDs match.
It fails to work on certain devices only.Browser features, permissions, CDN, and performanceRecord the device type, version, and steps to reproduce.

Errors within the browser and failures on a public web server are different. The former is investigated via developer tool error details, while the latter is checked through HTTP responses and asset delivery conditions. Refraining from describing unknown failures as successes enhances the reliability of technical notes.

Application to business and learning

It can be used for survey results, category structures, educational materials, exhibits, and more. For use cases like actual elections or official counting, pre-display vote aggregation, auditing, signatures, and anti-tampering measures must be implemented separately. D3 is a presentation library and does not guarantee voting fairness.

Decisions to make before implementation

When publishing to readers, determine where the displayed data comes from, who can modify it, the types of information remaining on the screen, and the verification items when updating the library. This demo includes neither login nor server storage. Therefore, before adding operational features, we recommend first distinguishing between the 'minimum portion that displays as expected' and the 'portion requiring operational reliability, permissions, and backups.' Because third-party CDNs involve external communication, you must verify in advance whether they are permitted on corporate networks.

Comparison with alternative methods

MethodSuitable scenariosPoints to note
D3.jsScenarios matching the objective, such as changing the circle size and vote count every time a vote is cast for an animalRequires updating dependency libraries and managing usage conditions
Browser standard APIsBuilding small features in-houseVerifying specifications and compatibility independently
Static images and tablesExplanations that do not require user interactionInability to experience state changes dynamically in real time

Libraries are tools to be chosen when needed. Compare them by weighing your goals against the learning curve. Avoiding making 'installing a library' the primary objective makes small-scale pages easier to maintain.

GitHub repository

The blog text focuses on background and concepts, while the Daily Code provides code for execution and modification, separating their roles. APIs for posting and saving to external services are not included.

Official information and primary sources

Reference verification scope:Refer to the official documentation as of the edit date October 27, 2026. This does not guarantee future changes to the linked destinations or all CDN asset responses.

Additional notes on the verification scope

The fixed source stored on GitHub was cross-checked with the official API documentation. Browser operations, CDN loading, and results on various operating systems have not been verified. During actual operation checks, inspect the Console and Network, and do not conclude that all conditions succeeded based solely on the SUCCESS display on the screen.

Document information

Article title
Visualizing an Animal Popularity Poll with D3.js: Exploring SVG and Square Root Scales
Published
Updated
Source
https://papanda925.com/?p=18298&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL