Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <p>I still remember picking up Edward Tufte's book, "The Visual Display of Quantitative Information", for the first time. Its pages oversized and crisp, I flipped through and studied each chart in meticulous detail. Sure, Tufte's appeal to minimal "paint", clean lines and clear labels was a rewarding educational experience.
	But I also enjoyed some of the <i>stranger</i> charts that were mentioned in that book; most notably, sparklines. </p>

<p>Sparklines are a simple idea (in hindsight) but they felt revolutionary to me at the time. They are just miniature charts, embedded in the text of a paragraph. If a journalist were to write about a stock, say, and had limited space in which to write her words, she could throw in a sparkline to show AAPL's stock over time, and only occupy about 1/4 of a line of text. Sparklines are a way to show information quickly, in a compartmentalized manner, and save text. I suppose that I'm drawn to sparklines because they feel like worthy companions for a journalist who wants to quickly convey a point at a deeper level of detail than the space requirements of a typical newspaper might allow.</p>

<p>The purpose of this blog is simple: Make a few sparklines, and embed them in the words on this page. For this post, I learned about Sparklines from <a href="https://www.essycode.com/posts/create-sparkline-charts-d3/" target="_blank">this article</a>, adapted the code, and reconstructed them with D3.js.
	All of the sparklines on this page were built with version 6 of the D3 library, so the code is up-to-date. All of the code that was used to generate this blog post can also be <a href="https://codepen.io/nikomccarty/pen/OJRzxrM" target="_blank">viewed on my CodePen</a>. </p>

<p>Let's start with the simplest sparkline: an inline line chart. This chart <span id="sparklines-line" class="sparklines"></span> is embedded right in the text, like magic. Beautiful! Notice, too, that this sparkline doesn't push the surrounding lines of text up or down; it's height exactly matches that of the paragraph's spacing. I went into the CSS for this blog page, noticed that the line spacing is set to 25px, and so set the height of this sparkline to 20px + 5px margin on the top. The second quirk, to get it to display properly, is to set its display property to inline-block.</p>

<p>On to the next one: a simple bar chart. <span id="sparklines-bars" class="sparklines"></span> The approach to make this follows the same logic as the line chart. The only difference, in this case, is that I'm using real data; namely, the frequency with which each letter in the English alphabet is used. You can view a bigger version of this chart on my <a href="https://observablehq.com/@nikomccarty/30-days-of-d3-day-4-bar-chart?collection=@nikomccarty/30-days-of-d3" target="_blank">Observable</a> page.</p>

<p>Okay, let's do one more chart; a bar chart, again, but with both positive and negative values. <span id="sparklines-bars2" class="sparklines"></span>You could use this type of chart to show gains or losses of a stock over time, for example. </p>
<p>Hope you enjoyed this post!</p>
              
            
!

CSS

              
                .sparklines {
	display: inline-block;
}

              
            
!

JS

              
                async function sparklinesLine() {
	const width = 150;
	const height = 20;
	const margin = { top: 5, right: 2, bottom: 0, left: 2 };
	const boundedwidth = width - margin.left - margin.right;
	const boundedheight = height - margin.top - margin.bottom;

	// Generate random data for a line chart.
	const data = d3.range(50).map((d) => Math.random());

	const xScale = d3
		.scaleLinear()
		.domain([0, data.length])
		.range([0, boundedwidth]);
	const yScale = d3
		.scaleLinear()
		.domain([0, d3.max(data)])
		.range([boundedheight, 0]);

	const svg = d3
		.select("#sparklines-line")
		.append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

	const line = d3
		.line()
		.x((d, i) => xScale(i))
		.y((d) => yScale(d));

	svg
		.append("path")
		.datum(data)
		.attr("fill", "none")
		.attr("stroke", "#bbb")
		.attr("stroke-width", 1)
		.attr("d", line);

	svg
		.append("circle")
		.attr("r", 2)
		.attr("cx", xScale(0))
		.attr("cy", yScale(data[0]))
		.attr("fill", "steelblue");

	svg
		.append("circle")
		.attr("r", 2)
		.attr("cx", xScale(data.length - 1))
		.attr("cy", yScale(data[data.length - 1]))
		.attr("fill", "tomato");
}
sparklinesLine();

async function sparklinesBars() {
	const width = 150;
	const height = 20;
	const margin = { top: 5, right: 2, bottom: 0, left: 2 };
	const boundedwidth = width - margin.left - margin.right;
	const boundedheight = height - margin.top - margin.bottom;

	// Generate random data for a line chart.
	const data = await d3.csv(
		"https://assets.codepen.io/4506684/alphabet.csv",
		d3.autoType
	);
	const yAccessor = (d) => d.frequency;

	const xScale = d3
		.scaleBand()
		.domain(d3.range(data.length))
		.range([0, boundedwidth]);

	const yScale = d3
		.scaleLinear()
		.domain(d3.extent(data, yAccessor))
		.range([boundedheight, 0])
		.nice();

	const svg = d3
		.select("#sparklines-bars")
		.append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

	const bars = svg
		.selectAll("rect")
		.data(data)
		.join("rect")
		.attr("x", (d, i) => xScale(i))
		.attr("y", (d) => yScale(yAccessor(d)))
		.attr("height", (d) => yScale(0) - yScale(yAccessor(d)))
		.attr("width", xScale.bandwidth())
		.attr("fill", "steelblue");
}
sparklinesBars();

async function sparklinesBars2() {
	const width = 150;
	const height = 20;
	const maxdata = 50;
	const mindata = -50;
	const margin = 2;

	const data = d3
		.range(50)
		.map((d) => mindata + (maxdata - mindata) * Math.random());
	console.log(data[0]);

	const bar_width = (width - data.length) / data.length;

	const xScale = d3.scaleLinear().domain([0, data.length]).range([0, width]);
	const yScale = d3.scaleLinear().domain([mindata, maxdata]).range([height, 0]);

	const svg = d3
		.select("#sparklines-bars2")
		.append("svg")
		.attr("width", width)
		.attr("height", height)
		.append("g")
		.attr("transform", `translate(${-margin},${margin})`);

	svg
		.selectAll(".bar")
		.data(data)
		.join("rect")
		.attr("class", "bar")
		.attr("x", (d, i) => xScale(i))
		.attr("y", (d) => (d > 0 ? yScale(d) : yScale(0)))
		.attr("width", bar_width)
		.attr("height", (d) => Math.abs(yScale(d) - yScale(0)))
		.attr("fill", (d) => (d > 0 ? "steelblue" : "tomato"));
}
sparklinesBars2();

              
            
!
999px

Console