
You may be familiar with the term “data visualization,” as it has become more mainstream as both a practice and career path. There’s a reason why this emerging field is well underway – it’s important that we are constantly learning more about our users, as well as showing them the data to back up our claims.
When data is presented in a clean and professional way, it makes it easy to understand and interpret. In most cases, your users are visual people, so what better way to illustrate data than with charts? D3.js, also referred to as Data-Driven Documents, is a great way to add charts to your WordPress site.

Why D3?
This library helps designers showcase data on the web. The possibilities are endless, making this a very popular library. From simple to complex to anything in between, D3 can be customized to render pretty much any type of chart. It plays nicely with standard web technologies, can manipulate the DOM, is super flexible, and the charts can be customized exactly to your liking.
By now, you’ve most likely encountered Scalable Vector Graphics, often referred to as SVGs. This is the type of format that the D3 library creates. SVGs are great because they are small in size, scalable, and resolution independent.
Just to be clear, this solution doesn’t ship with any pre-built charts out of the box – you’ll have to come up with your own! Take a look at the D3 gallery and you can see many great examples to inspire you.
As an Open Source solution, you do not have to worry about licensing and cost. Because it is Open Source, development is ongoing. To keep up to date with the latest version, you can fork D3 on Github.
Making a simple D3 chart
Now that we know how great D3 is, let’s build something. We’ll make a simple donut chart, which will cover the basic concepts of D3.

Step one: add the scripts to your site
First, you will need to add the D3 script to your WordPress site. The d3 website has it available for download or you can link directly to the latest version. You will notice that I’m using minified version for this tutorial. D3 is naturally pretty small in size, but the minified is still slightly smaller at only 148 KB.

Next, you’ll make a new JavaScript file where the custom chart script goes. Give the file a recognizable name so it will be easy to find.

It is very important that the D3 script is called before the chart-specific JavaScript. If things are not called in the right order, the charts will not render. (I know this from personal experience, and if you don’t catch it right away, you’ll likely spend a lot of time trying to fix things that aren’t broken.)
These scripts should be added to your site after the closing body tag. When inspecting the page, make sure that it looks something like this:
<script type="text/javascript" src="js/d3/d3.min.js"></script> <script type="text/javascript" src="js/charts/charts.js"></script>
Keep in mind that your file path might be different than this, depending on your file structure.
Step two: add scripts to create the chart
You will not be touching the d3.js
file at all, only working in your specific chart file. In this case, it is called charts.js
.
Let’s break things down piece by piece. First, create your variable and establish what you will need in your function. I’ll name this variable donut
.
var donut = (function(one) { })();
Inside the curly braces, you will add your sizing information.
var width = 400, height = 400, radius = 200
Next, define your colors. How about a gray and blue chart? The first color listed here is a light grey which will be the default color. The second is the blue color that will represent the data.
colors = d3.scale.ordinal() .range(['#e8e8e8', '#1dafd3']);
You will need some data to test this with, so let’s add that next. For this tutorial, the data is hardcoded in, but you can also use spreadsheet data and dynamic data with D3.
var piedata = [{ value: 50 }, { value: 30 }, ]
Now you can add more details that help define how the chart is rendered.
The arc defines the inner radius. Picture the outer radius of the chart – you’ll want it to be fairly thick, so subtracting 100 should be sufficient.
var arc = d3.svg.arc() .innerRadius(radius - 100) .outerRadius(radius)
This creates the SVG container and the #donut
is what you will be targeting on your page to actually render the chart. This is where you will start to see your colors from the above step.
var donutChart = d3.select('#donut').append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + (width - radius) + ',' + (height - radius) + ')') .selectAll('path').data(pie(piedata)) .enter().append('g') .attr('class', 'slice') var slices1 = d3.selectAll('g.slice') .append('path') .attr('fill', function(d, range) { return colors(range); }) .attr('d', arc)
Finished code
Just in case you want to compare what you have to the sample, here is the complete code snippet.
/* start donut charts */ var donut = (function(one) { var width = 400, height = 400, radius = 200 colors = d3.scale.ordinal() .range(['#e8e8e8', '#1dafd3']); var piedata = [{ label: "One", value: 50 }, { label: "Two", value: 30 }, ] var pie = d3.layout.pie() .value(function(d) { return d.value; }) var arc = d3.svg.arc() .innerRadius(radius - 100) .outerRadius(radius) var donutChart = d3.select('#donut').append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + (width - radius) + ',' + (height - radius) + ')') .selectAll('path').data(pie(piedata)) .enter().append('g') .attr('class', 'slice') var slices1 = d3.selectAll('g.slice') .append('path') .attr('fill', function(d, range) { return colors(range); }) .attr('d', arc) })();
Seeing the chart
You will need to create a new page or post so you can “call” the donut chart to actually see it. Make sure that you are in Text edit mode.
<div> <svg id="donut" viewBox="0 0 400 400" perserveAspectRatio="xMinYMid"></svg> </div>
Viewbox and aspect ratio to size chart
There is something extra in the SVG tag, which is the viewBox
and preserveAspectRatio
. This was not generated by D3, and is totally optional. You may have another preferred method of sizing, but this tends to work well, and it helps with the responsiveness of the charts.
Especially in this case, being that we want to keep a perfectly round shape, setting an aspect ratio will ensure that the SVG scales to fit. This is where the viewBox
comes into play. The advantage to the viewBox
is that it defines how all the measurements and coordinates used inside the SVG should be scaled to fit in the available space. If you are also using 400 as a measurement, here’s a quick explanation as to how to keep the circular shape.
We have two values of 400 that are the same; the reason for this is so the image scales properly. With our viewBox="0 0 400 400"
, we are creating a coordinate system for the graphic. It is 400 units wide and 400 units high. The width and height of the SVG graphic establishes the visible area and setting a viewBox
allows you to specify that your graphics can stretch to fit a certain container (most likely the viewport by default, which is the part of the web page that the user can currently see).
There’s a little more to it because even with the viewBox
defined, it still won’t scale perfectly. It won’t be distorted, which is a good thing, but there is more to the equation. Meet the wingman, preserveAspectRatio
. It has no effect unless there is a viewBox
that defines the aspect ratio of the image. The scale will be adjusted in order to preserve the aspect ratio, so you can keep your perfectly circular chart. When including the preserveAspectRatio
, you are planning for instances when the viewBox
does not match the aspect ratio of the viewport or container that the chart is in. In most cases, by default, the image will scale until it fits both the height and width but centers itself within any extra space. We’ve included preserveAspectRatio="xMidYMid"
which is telling the browser to center the graphic within the viewport in both directions.

The most important takeaway is knowing that the graphic will not get cut off and that it is scalable. The key to really understanding this is to experiment with the values. A good way to do that is to see what happens when the values are changed and how it relates to the viewport.
Browser support and d3
Chances are that you are using a modern browser, but it is worth mentioning if you have to support older browsers. Overall, browser support is great, and you probably won’t run into any issues, but D3.js doesn’t work well with older browsers like IE8.
Creating a simple chart is a great way to be up and running with D3.js. Knowing the basics, and becoming familiar with D3 starter charts will be very helpful to you as you design your data and move onto more chart types. From simple to complex, the design options are infinite.
How’d your chart turn out? Let us know in the comments!
What’s next?

Download this ebook for a list of our most recommended plugins for developers! We’ve found all of these plugins to be straightforward to use, not too performance heavy on your site, and just downright reliable.
Ready to install your new favorite plugin? Click below!
Comments ( 12 )
convince customer
June 18, 2025
Thanks for your exciting article. One other problem is that mesothelioma cancer is generally a result of the breathing of material from asbestos fiber, which is a carcinogenic material. It is commonly viewed among employees in the construction industry with long contact with asbestos. It is also caused by living in asbestos protected buildings for years of time, Inherited genes plays a huge role, and some consumers are more vulnerable to the risk when compared with others.
https://www.magileads.com/en/how-to-convince-a-customer/
amxksqnju
June 16, 2025
Join pediascape.science wiki User:ChristenaHarold for premier betting mostbet bd com! Experience top sports events and secure wins with mostbet bd. Bet now! Discover thrilling wins and top games at Mostbet Casino! Enjoy secure betting, bonuses, and more mostbet casino. Play now! Discover thrilling wins and top games at Mostbet Casino! Enjoy secure betting, bonuses, and more mostbet casino. Play now! kişisel hesapta fırsatınız var bulmak en çok uygun optimal için TR Parabet parabet. Sonunda eğlenceli kısma geldik: oyun seçimi! Dive into the excitement with Dabet, where every bet brings you closer to big wins. Their modern platform and real-time updates keep you ahead of the game. betabuys.uk Discover thrilling wins and top games at Mostbet Casino! Enjoy secure betting, bonuses, and more mostbet casino. Play now!
http://www.servinord.com/phpBB2/profile.php?mode=viewprofile&u=710934
Zadzwoń Allbets is strictly prohibited for individuals under 18 years old. If you enjoy using our service, please recommend us to friends who might also benefit from our offerings! Ekscytująca gra Aviator od wiodącego dewelopera Spribe jest dostępna dla graczy na stronie Biamo Casino. Nowe kasyno online zostało uruchomione w 2020 roku i szybko przyciągnęło uwagę graczy. Wirtualna strona oferuje szeroki wybór gier, turniejów i promocji. Na nowych i stałych użytkowników czekają ciekawe bonusy i atrakcyjne prezenty. It might assist for many who respected them to you expected them to esteem your. You should use the personal ad paragraph and also the flag picture to publish your own mature posts on the mature listing website. Investing in a tiny quantity often produce successful leads to the fresh long run. When you’re a
jrdeloxth
June 15, 2025
Jocul Lucky Jet game 1 win — este un slot crash onest unde utilizatorii pot obține câștiguri mari în câteva minute. Jucătorii trebuie să plaseze un pariu la începutul rundei și să reușească să își retragă câștigurile înainte ca personajul Lucky Joe să dispară de pe ecran. Mai jos am subliniat principalele caracteristici ale jocului 1win Lucky Jet game. Cum se folosește Lucky Jet Cont Demo După ce ați selectat Lucky Jet mașină, primul pas este să vă conectați la sistem. 1Win Casino este o opțiune excelentă pentru cei care caută un cazinou online. Site-ul oferă o mare varietate de jocuri, inclusiv popularul joc JetX. Site-ul oferă, de asemenea, o varietate de bonusuri și promoții, ceea ce îl face o opțiune excelentă pentru cei care doresc să profite de promoția Jetx Bet 1Win.
http://www.redsea.gov.eg/taliano/Lists/Lista%20dei%20reclami/DispForm.aspx?ID=2991413
În concluzie, pentru a descărca aplicația Lucky Jet, utilizatorii de Android pot instala aplicația 1win de pe site-ul oficial, în timp ce utilizatorii de iOS ar putea fi nevoiți să urmeze instrucțiuni specifice în funcție de browserul pe care îl folosesc. De asemenea, aplicația Lucky Jet poate fi descărcată de pe platforme precum Play Market și App Store. În plus, jucătorii pot accesa jocul Lucky Jet prin intermediul browserului web al computerului lor, fără a fi nevoie de instalarea aplicației. Este important să rețineți că versiunea Demo Lucky Jet a jocului este concepută în primul rând pentru practică și pentru antrenarea abilităților. Jucătorii își pot încerca mâna și abilitățile în versiunea demo înainte de a decide să joace jocul cu bani reali. Aceasta servește ca un simulator sau mod de testare, oferind o oportunitate de a înțelege mecanica jocului, regulile și experiența generală de joc.
dcvhfpeap
June 11, 2025
O Fibonacci é um sistema de progressão negativa, semelhante ao Martingale. Ele consiste em aumentar o valor da aposta cada vez que você perde ao jogar com o Aviator. Portanto, embora o sistema de Martingale possa parecer atraente para alguns jogadores devido à promessa de lucros a longo prazo, é importante lembrar que ele é baseado em um pressuposto teórico e que a probabilidade de perder dinheiro é real. Como em qualquer jogo de azar, a sorte é o fator mais importante e o resultado final é imprevisível. A martingale é uma técnica utilizada em muitos jogos de casino grátis. O seu objetivo é sempre sair ganhando face ao acaso no longo prazo e, em teoria, com a martingale você consegue. Contudo, veremos que na prática é não é tão simples assim. Entender plenamente como funciona o sistema de apostas do JetX é essencial para maximizar as chances de sucesso. Nossa plataforma, equipada com o Pin Up JetX predictor, fornece todas as ferramentas necessárias para os jogadores gerenciarem suas apostas eficientemente, incentivando a adoção de estratégias de jogo responsáveis e bem pensadas. Este recurso ajuda na previsão e análise das tendências de jogo, aumentando suas chances de fazer apostas vencedoras.
https://fo.asso-sc.com/viewtopic.php?t=113878&sid=701a6d8d7225a07072f1883f624e6d7d
Com isso, do ponto de vista legal, entende-se que não há proibição quanto à bets de 1 real no país, portanto, desde que sejam autorizadas pelo governo brasileiro, sim, esses sites são legais. Na tabela abaixo, trazemos os mercados de bet mais populares na KTO. Segundo a pesquisa da KTO, o mercado de bet mais popular do futebol em 2024 foi o mercado 1×2, com 62,9% das apostas. Abaixo, trazemos uma pequena lista dos mercados mais populares do futebol em dezembro, mas aqui no site da KTO oferecemos uma enorme variedade de mercados para apostas em todos os esportes. O termo “bet” ou “bets”, refere-se à palavra em inglês para “aposta” ou “apostas”, na tradução literal. No Brasil, as bets são as casas de apostas esportivas, como a KTO, uma das primeiras empresas do setor a ser regularizada no país.
mkgnlafpl
June 3, 2025
Com o nosso site, a experiência de gerir e participar de grupos online é elevada a um novo patamar. Nosso compromisso com a qualidade, a inovação e o suporte ao cliente é o que nos diferencia. O que oferecemos: O que oferecemos: O que oferecemos: Com o nosso site, a experiência de gerir e participar de grupos online é elevada a um novo patamar. Nosso compromisso com a qualidade, a inovação e o suporte ao cliente é o que nos diferencia. Com o nosso site, a experiência de gerir e participar de grupos online é elevada a um novo patamar. Nosso compromisso com a qualidade, a inovação e o suporte ao cliente é o que nos diferencia. Divulgação de Slots рџЋ°рџљЂ Bet da Sorte MS Bet da Sorte MS Com o nosso site, a experiência de gerir e participar de grupos online é elevada a um novo patamar. Nosso compromisso com a qualidade, a inovação e o suporte ao cliente é o que nos diferencia.
https://service.rohinidiagnostic.com/review-onde-jogar-aviator-com-melhor-retorno-e-estabilidade-no-brasil/
As casas de apostas que aceitam 1 real são as seguintes: Superbet, Betnacional, Mr. Jack Bet, Estrela Bet e Betboo. Além disso, também é importante que os sites diversifiquem a atuação, oferecendo, por exemplo, opções de melhores odds, turbinadas ou especiais em eventos específicos, que atraem ainda mais jogadores. O Cbet Jetx é uma atração popular que oferece aos jogadores uma emocionante experiência de apostas com multiplicadores. Aqui estão algumas características e informações sobre como jogar JetX na CBET: Também há outros critérios que podem ser considerados pontos positivos, como a criptografia HTTPS nos sites ou até mesmo parcerias com entidades que ajudam a garantir um nível de segurança maior, como a eCOGRA, presente no site de apostas da Betsson.
ysfmiqick
May 31, 2025
If by December 31, 2022 Empire City is awarded a casino gaming license then MGM Resorts would pay an additional $50 million as under condition of the sale. You’ll be treated like a true emperor empress while playing at this site. Our Slots Empire online casino reviewers found that you’ll be given loads of extra ammo to play with, starting off with a massively generous welcome bonus. You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page. Usher in a year of power, success, honor, and luck as Yaamava’ Resort & Casino at San Manuel marks the Lunar New Year. Ca$h Advance™ Series consists of two markedly different base themes, Chick-A-Boom!™ and Fire Magic®, but with the same cascading reels and cash-on-reels mechanics. Chick-A-Boom! is a fun, silly chicken-themed game while Fire Magic presents a tiki fire theme that features fireball cash-on-reel symbols. Chickens and tikis above the reels can activate to enhance the reels
https://professionals.matchingyu.com/index.php/2025/05/26/step-by-step-claim-process-for-mines-bonuses-a-guide-for-pakistani-online-casino-players/
Siberian Storm is a five-reel video slot with an unconventional hexagonal shape, which means there are rows in differing sizes on the grid. It features 720 ways to win, and payouts can occur in both directions, leading to more earning potential. Whatever you're hunting for, always keep an eye out for the Tiger's Eye symbols as finding 5 of them on consecutive reels will trigger 8 free games. Multiple combos can be triggered simultaneously with up to 96 free games being initially awarded. Free games can also be retriggered during the bonus up to a maximum of 240 free games. You will get eight free spins, but because you can land stacked bonus symbols in the base game, you could start with as many as 96 free spins. Wilds and scatters will appear more often during free spins, and if you land more bonus symbols, you can retrigger the feature to up to 240 free spins.
aLVwe
April 1, 2025
199587 361929If I should say something, then nothing will stop the chatter within 800722
Renate
March 29, 2025
Hi it's me, I amm also visiting this web page on a regular basis, this website is in fact pleasant and the viewers are in fact sharing fastidious thoughts. http://boyarka-Inform.com
Robbin
March 7, 2025
Hi there! Do you use Twitter? I'd like too follow you
if that would bbe ok. I'm absolutely enjoying your blog and look
forward to new updates. http://Boyarka-Inform.com/
Robbin
March 7, 2025
Hi there! Do you use Twitter? I'd like to follow
you iif that would be ok. I'm absollutely enjoying our blog and look forward to neew updates. http://Boyarka-Inform.com/
Chelsea
February 22, 2025
Why Taya365 is the top choice for players in the Philippines
taya365 app casino - Kacey -
Uncover the world of gambling with Taya365 and experience top-notch live games.
Join today to get incredible rewards and bonuses!
Join Taya365 and unlock a world of gaming excitement.
Whether you're into slots, there's something for
everyone. Join now and claim your prizes!
taya365 app
Abraham Walker
February 13, 2019
I tried this example on my WordPress website and nothing showed up. I could see the SVG element using the developer's tool but I could not see the pie chart.
Is there any step missing from this tutorial?