mathematics-in-real-life
How to Visualize Data With Bar Charts and Pie Charts
Table of Contents
Why Visualize Data with Bar and Pie Charts?
Data visualization is the bridge between raw numbers and actionable insights. Among the many chart types available, bar charts and pie charts remain the most accessible and widely used. They appear in quarterly business reviews, survey analysis dashboards, and even social media infographics. Their popularity stems from simplicity: a well‑designed bar or pie chart communicates comparisons, rankings, or proportions in a single glance. For teams using Directus as their backend, these charts become even more powerful because data can be managed, filtered, and served via a flexible API. This article dives deep into both chart types—covering best practices, common mistakes, and practical implementation with Directus—to help you build visualizations that truly inform.
Understanding Bar Charts
A bar chart uses rectangular bars to represent values. The length (vertical or horizontal) of each bar corresponds to the quantity it measures. Bar charts excel at comparing discrete categories: sales by region, employee count by department, website visits by channel. They are also effective for showing changes over time when the time intervals are treated as categories.
When to Use Bar Charts
- Comparing quantities across multiple unrelated categories (e.g., revenue per product line).
- Ranking items—bars sorted from highest to lowest instantly reveal top performers.
- Tracking performance when time is categorical (monthly, quarterly).
- Showing part‑to‑whole relationships with stacked or 100% stacked variants.
Types of Bar Charts
- Vertical bar chart (column chart)—the default format. Categories run along the x‑axis, values on the y‑axis. Best for most comparisons.
- Horizontal bar chart—ideal when category labels are long (e.g., full product names) or when you have many categories. The y‑axis becomes the value axis.
- Grouped (clustered) bar chart—side‑by‑side bars for each category allow direct comparison of multiple series (e.g., Q1 sales for three products).
- Stacked bar chart—each bar represents a category’s total, with segments showing sub‑group contributions. Use cautiously because comparing individual segment sizes across bars is difficult.
- 100% stacked bar chart—normalizes each bar to 100%, emphasizing the relative proportion of sub‑groups rather than absolute values. Excellent for showing percentage breakdowns over time.
Best Practices for Bar Charts
- Always start the y‑axis at zero. Truncating the axis exaggerates differences and can mislead.
- Sort bars meaningfully. Use ascending/descending by value or a natural order (e.g., chronological). Unsorted bars add cognitive load.
- Apply consistent colors. Each series or category should have a distinct hue. Avoid red‑green pairs for accessibility.
- Label directly when possible. Place value labels above or inside bars to speed up interpretation. If space is tight, use clear axis ticks and a legend.
- Avoid 3D effects and shadows. They distort perception of bar length and serve no informational purpose.
Creating Bar Charts with Directus
Directus provides a headless backend that stores your data in a relational database (PostgreSQL, MySQL, SQLite, etc.) and exposes it through REST and GraphQL APIs. To render a bar chart on any frontend, follow this standard workflow:
- Define a Directus collection—for example,
monthly_sales—with fields likemonth(string or date) andrevenue(decimal). - Insert data via the Directus App, CSV import, or automated integration.
- Fetch the data using the Directus SDK or a simple fetch call. You can add filters, aggregations, and sorting directly in the API request.
- Pass the data to a charting library such as Chart.js, D3.js, or Vega‑Lite.
Here’s a minimal example using the Directus SDK and Chart.js in a static site:
import { Directus } from '@directus/sdk';
const directus = new Directus('https://your-instance.directus.app');
async function getSalesData() {
const response = await directus.items('monthly_sales').readByQuery({
sort: 'month',
limit: 12
});
const labels = response.data.map(item => item.month);
const values = response.data.map(item => item.revenue);
// Now create a Chart.js bar chart with these arrays
}
This pattern keeps your chart data synchronized with the Directus backend. Any update to the monthly_sales collection—whether manual or through a webhook—immediately refreshes your visualization when the page reloads or when you re‑fetch the API.
Advanced Bar Chart Aggregations
Directus allows you to compute aggregates on the server side using query parameters like aggregate[count]=* or groupBy[]. For instance, if you store individual transactions, you can group them by region and sum the totals without transferring every transaction to the client:
GET /items/transactions?groupBy[]=region&aggregate[sum]=amount
This returns aggregated data ready for a bar chart, reducing payload size and client‑side processing.
Understanding Pie Charts
A pie chart represents data as slices of a circle, where the angle (and area) of each slice is proportional to its value. Pie charts are most effective for showing how a total is divided into a few parts—for example, market share of three competitors or budget allocation by department. Their simplicity is also their greatest weakness; misinterpretation is common when slices are numerous or similar in size.
When to Use Pie Charts
- You have 2–5 categories that sum to a meaningful whole.
- You want to emphasize relative size—especially highlighting a dominant slice (e.g., “over 60% of users prefer X”).
- The audience is already familiar with the data and only needs a quick compositional snapshot.
- Showing percentages rather than absolute numbers is the primary goal.
Limitations of Pie Charts
- Humans struggle to compare angular areas. Judging the difference between a 22° slice and a 28° slice is far harder than comparing bar lengths.
- Too many slices create clutter. A pie chart with 8+ categories becomes a rainbow of thin wedges that are impossible to read accurately. The same data would be clearer in a bar chart.
- 3D and exploded pies distort proportions. Pulling a slice out away from the center makes it appear larger than it is. Avoid these effects entirely.
- Donut charts share similar weaknesses (though the empty center can help focus on the outer arc). If you must use a donut, keep the hole small and the number of categories minimal.
Alternatives to Pie Charts
When a pie chart isn’t right, consider these proven alternatives:
- Bar chart—the best all‑purpose replacement. It supports many categories, allows precise comparisons, and can be stacked to show composition.
- Stacked bar chart (100%)—excellent for showing proportions over time or across groups.
- Treemap—uses nested rectangles to display hierarchical proportions. Works well for categories with sub‑categories (e.g., product line → product).
- Waffle chart—a grid of 100 squares, each representing one percentage point. Intuitive and often used in infographics.
Creating Pie Charts with Directus
The same Directus workflow applies to pie charts. You define a collection with a category field and a numeric value, then retrieve the data. With Chart.js, a pie chart is straightforward:
const ctx = document.getElementById('pieChart').getContext('2d');
new Chart(ctx, {
type: 'pie',
data: {
labels: ['Product A', 'Product B', 'Product C'],
datasets: [{
data: [120, 80, 50],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: function(ctx) {
return ctx.label + ': ' + ctx.parsed + ' units (' +
(ctx.parsed / ctx.dataset.data.reduce((a,b)=>a+b,0) * 100).toFixed(1) + '%)';
}
}
}
}
}
});
Using Directus, you can enrich your pie charts with computed fields. For example, add a field that calculates the percentage value directly in the database using a formula. Or you can use Directus’s Presets and Roles to control which users see which slices—perfect for internal dashboards that need to show department‑specific views.
Bar Charts vs. Pie Charts: Making the Right Choice
The decision between bar and pie charts should always be driven by your data and the message you want to convey. Here is a concise guide:
- Comparing individual values → bar chart (always). Even with two categories, a bar chart allows easier comparison than a pie.
- Showing parts of a whole with few categories (2–5) → pie chart can work, but a 100% stacked bar is often clearer.
- Showing parts of a whole with many categories → bar chart or treemap. Pie charts become unreadable.
- Highlighting a dominant category → pie chart (e.g., “80% of revenue comes from one product”) can be effective, but include the exact percentage in a label.
- Displaying small differences between slices → bar chart. Humans perceive length differences far better than angle differences.
When in doubt, default to a bar chart. Empirical research consistently shows that bar charts enable faster and more accurate comparisons. Use pie charts only when the relationship is truly compositional, the number of categories is small, and your audience does not need to compare precise values between slices.
Using Directus for Data Visualization
Directus is more than a simple data storage layer. Its ecosystem supports end‑to‑end data visualization workflows:
Data Studio: Built‑in Dashboard Builder
Directus Data Studio lets you create interactive dashboards directly within the App—no coding required. You can add bar charts, pie charts, gauges, and tables. Data Studio automatically updates when underlying data changes. To create a chart:
- Navigate to Data Studio in the Directus App.
- Add a new panel and select your collection.
- Choose the chart type (bar, pie, line, etc.).
- Specify the label field and value field (you can also aggregate data like sum or count).
- Apply filters and sort order. Save the dashboard.
Data Studio respects Directus permissions, so each user sees only the data they are allowed to view. This makes it easy to share role‑based dashboards without duplicating work.
REST & GraphQL APIs for Custom Frontends
If you need more control, Directus APIs give you access to raw data with powerful query parameters. You can filter by date range, aggregate values, group by multiple fields, and even join related collections. Combined with any charting library, you can build bespoke visualizations that precisely match your design system.
Flows & Webhooks
Directus Flows allow you to automate chart updates. For example, you can trigger a flow when a new transaction is added—the flow could recalculate aggregated values and push the result to a database table optimized for charting. Webhooks can send data to external analytics platforms like Google Data Studio or Tableau for more advanced processing.
Extensions
The Directus extension system lets you build custom interfaces and modules. You could create a custom chart panel that uses D3.js with custom interactions, then embed it inside a Data Studio dashboard. This flexibility makes Directus a central hub for all your data visualization needs.
For a complete walkthrough, see the Data Studio documentation and browse the Directus blog for real‑world visualization examples.
Top Tips for Effective Data Visualization
Creating a chart is only half the work. Make your visualizations truly communication tools with these principles:
- Declutter. Remove unnecessary gridlines, borders, and tick marks. Every non‑data element should serve a purpose.
- Use color intentionally. Assign distinct colors to categories, but avoid more than 7–10 hues in one chart. Consider colorblind‑friendly palettes (e.g., ColorBrewer).
- Provide context. Always include a descriptive title, clear axis labels, and a legend. Annotations such as “% change” or “record high” help viewers focus on key insights.
- Validate your data. For pie charts, ensure slices sum to 100% (within rounding). For bar charts, watch for outliers that compress the scale. Directus validation rules can enforce data quality at the collection level.
- Design for responsive screens. Test your charts on mobile. Chart.js and Vega‑Lite both support responsive configuration. On small screens, consider switching from a vertical bar to a horizontal bar to avoid label truncation.
- Test with real users. Show a draft chart to a colleague who is unfamiliar with the data. If they misinterpret the chart or take too long to understand it, redesign.
Conclusion
Bar charts and pie charts remain essential tools in the data storyteller’s toolkit. Bar charts offer clarity and precision for comparisons and rankings, while pie charts can effectively communicate simple proportions when used sparingly. By coupling these chart types with Directus, you gain a robust, API‑driven backend that keeps your visualizations fresh and your data centralized.
Start small: pick a dataset in Directus, build a bar chart in Data Studio or your frontend, and then experiment with grouping and filtering. As you grow more confident, explore stacked charts, aggregates, and custom extensions. The goal is always the same—help your audience understand the story your data tells. With Directus and sound design principles, you will create visualizations that drive informed decisions.