Chuck Grimmett

April 2016

Index

  • Responsive D3.js bar chart with labels

    Responsive D3.js bar chart with labels

    Today I learned some cool stuff with D3.js!

    Here is a minimalist responsive bar chart with quantity labels at the top of each bar and text wrapping of the food labels. It is actually responsive, it doesn’t merely scale the SVG proportionally, it keeps a fixed height and dynamically changes the width.

    For simplicity I took the left scale off. All bars are proportional and are labeled anyway.

    Go ahead and resize your window! This has a minimum width of about 530px because of the text labels. Any smaller than that and they are very difficult to read.

    The basic HTML

    <div id ="chartID"></div>
    <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>

    The Styles

    You’ll see that the axis is actually there but it is white. I found it useful to learn to draw it, but I didn’t want it so I am keeping it hidden.

    .axis path, .axis line {
        fill: none;
        stroke: #fff;
      }
    .axis text {
      	font-size: 13px;
      }
    .bar {
        fill: #8CD3DD;
      }
    .bar:hover {
        fill: #F56C4E;
      }
    svg text.label {
      fill:white;
      font: 15px;  
      font-weight: 400;
      text-anchor: middle;
    }
    #chartID {
    	min-width: 531px;
    }

    The Data

    var data = [{"food":"Hotdogs","quantity":24},{"food":"Tacos","quantity":15},{"food":"Pizza","quantity":3},{"food":"Double Quarter Pounders with Cheese","quantity":2},{"food":"Omelets","quantity":30},{"food":"Falafel and Hummus","quantity":21},{"food":"Soylent","quantity":13}]

    The Javascript Heavy Lifting

    This is where D3 really comes in.

    1. Setting the margins, sizes, and figuring out the basic scale.
    2. Setting the axes
    3. Drawing the basic SVG container with the proper size and margins
    4. Scaling the axes
    5. Drawing the bars themselves
    var margin = {top:10, right:10, bottom:90, left:10};
    
    var width = 960 - margin.left - margin.right;
    
    var height = 500 - margin.top - margin.bottom;
    
    var xScale = d3.scale.ordinal().rangeRoundBands([0, width], .03)
    
    var yScale = d3.scale.linear()
          .range([height, 0]);
    
    
    var xAxis = d3.svg.axis()
    		.scale(xScale)
    		.orient("bottom");
          
          
    var yAxis = d3.svg.axis()
    		.scale(yScale)
    		.orient("left");
    
    var svgContainer = d3.select("#chartID").append("svg")
    		.attr("width", width+margin.left + margin.right)
    		.attr("height",height+margin.top + margin.bottom)
    		.append("g").attr("class", "container")
    		.attr("transform", "translate("+ margin.left +","+ margin.top +")");
    
    xScale.domain(data.map(function(d) { return d.food; }));
    yScale.domain([0, d3.max(data, function(d) { return d.quantity; })]);
    
    
    //xAxis. To put on the top, swap "(height)" with "-5" in the translate() statement. Then you'll have to change the margins above and the x,y attributes in the svgContainer.select('.x.axis') statement inside resize() below.
    var xAxis_g = svgContainer.append("g")
    		.attr("class", "x axis")
    		.attr("transform", "translate(0," + (height) + ")")
    		.call(xAxis)
    		.selectAll("text");
    			
    // Uncomment this block if you want the y axis
    /*var yAxis_g = svgContainer.append("g")
    		.attr("class", "y axis")
    		.call(yAxis)
    		.append("text")
    		.attr("transform", "rotate(-90)")
    		.attr("y", 6).attr("dy", ".71em")
    		//.style("text-anchor", "end").text("Number of Applicatons"); 
    */
    
    
    	svgContainer.selectAll(".bar")
      		.data(data)
      		.enter()
      		.append("rect")
      		.attr("class", "bar")
      		.attr("x", function(d) { return xScale(d.food); })
      		.attr("width", xScale.rangeBand())
      		.attr("y", function(d) { return yScale(d.quantity); })
      		.attr("height", function(d) { return height - yScale(d.quantity); });

    Adding the quantity labels to the top of each bar

    This took me a while to figure out because I was originally appending to the rect element. According to the SVG specs this is illegal, so I moved on to appending them after everything else to they’d show on top. The positioning is tricky, too. I eventually found the correct variables to position it close to center. Then text-anchor: middle; sealed the deal.

    // Controls the text labels at the top of each bar. Partially repeated in the resize() function below for responsiveness.
    	svgContainer.selectAll(".text")  		
    	  .data(data)
    	  .enter()
    	  .append("text")
    	  .attr("class","label")
    	  .attr("x", (function(d) { return xScale(d.food) + xScale.rangeBand() / 2 ; }  ))
    	  .attr("y", function(d) { return yScale(d.quantity) + 1; })
    	  .attr("dy", ".75em")
    	  .text(function(d) { return d.quantity; });   	  
    

    Responsiveness

    The general method for making D3 charts responsive is to scale the SVG down proportionally as the window gets smaller by manipulating the viewBox and preserveAspectRatio attributes. But after digging around on Github for a while, I found a fancier solution that preserves the height and redraws the SVG as the width shrinks.

    document.addEventListener("DOMContentLoaded", resize);
    d3.select(window).on('resize', resize); 
    
    function resize() {
    	console.log('----resize function----');
      // update width
      width = parseInt(d3.select('#chartID').style('width'), 10);
      width = width - margin.left - margin.right;
    
      height = parseInt(d3.select("#chartID").style("height"));
      height = height - margin.top - margin.bottom;
    	console.log('----resiz width----'+width);
    	console.log('----resiz height----'+height);
      // resize the chart
      
        xScale.range([0, width]);
        xScale.rangeRoundBands([0, width], .03);
        yScale.range([height, 0]);
    
        yAxis.ticks(Math.max(height/50, 2));
        xAxis.ticks(Math.max(width/50, 2));
    
        d3.select(svgContainer.node().parentNode)
            .style('width', (width + margin.left + margin.right) + 'px');
    
        svgContainer.selectAll('.bar')
        	.attr("x", function(d) { return xScale(d.food); })
          .attr("width", xScale.rangeBand());
          
       svgContainer.selectAll("text")  		
    	 // .attr("x", function(d) { return xScale(d.food); })
    	 .attr("x", (function(d) { return xScale(d.food	) + xScale.rangeBand() / 2 ; }  ))
          .attr("y", function(d) { return yScale(d.quantity) + 1; })
          .attr("dy", ".75em");   	      
    
        svgContainer.select('.x.axis').call(xAxis.orient('bottom')).selectAll("text").attr("y",10).call(wrap, xScale.rangeBand());
        // Swap the version below for the one above to disable rotating the titles
        // svgContainer.select('.x.axis').call(xAxis.orient('top')).selectAll("text").attr("x",55).attr("y",-25);
        	
       
    }

    Wrapping text labels

    Wrapping text labels is tricky. The best solution I found is the one Mike Bostock (D3’s creator) describes. I modified it slightly to work with my chart, but the overall solution is the same.

    function wrap(text, width) {
      text.each(function() {
        var text = d3.select(this),
            words = text.text().split(/\s+/).reverse(),
            word,
            line = [],
            lineNumber = 0,
            lineHeight = 1.1, // ems
            y = text.attr("y"),
            dy = parseFloat(text.attr("dy")),
            tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
        while (word = words.pop()) {
          line.push(word);
          tspan.text(line.join(" "));
          if (tspan.node().getComputedTextLength() > width) {
            line.pop();
            tspan.text(line.join(" "));
            line = [word];
            tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
          }
        }
      });
    }

  • Strange issues with stacking on iOS Safari

    Strange issues with stacking on iOS Safari

    I was asked to help out with some CSS animation. I thought it would be no problem. A few hours at most. Boy was I wrong.

    The biggest issue I ran into was that an element that came in from the right (outside the boundaries was hidden by overflow) functioned just fine on desktop Safari and Chrome, but did not appear on iOS unless I ran the debugger and toggled overflow or display properties during the transition. position and z-index made no difference.

    I came across this article while researching solutions. The ending shed some light for me:

    ensure you don’t have a CSS property such as transform on the root element. It’s more than likely that this is creating a new stacking context for the enclosed elements.

    Whelp, that sucks. CSS animations rely almost solely on the transform property to operate. I played around a few more hours trying different techniques with containers and positioning. The only thing that sort of worked was using translate3d() and keeping the element active and in view the entire time. Then and only then did it work the same on iOS and desktop. If it paused or was hidden even for a moment, I couldn’t get it to come back.

    Safari on iOS is doing something funky with stacking when the transform property is involved and I couldn’t find any solid documentation on what is happening in order to come up with a good solution.

    If anyone has faced this beast and won, please drop me a line! I can’t post the specific elements here because it was client work, but I’m happy to discuss it one-on-one.


    Side note: Webkit is finally moving off of prefixes!

  • Having trouble accessing your website from Google’s public DNS? Check your DNSSEC.

    Having trouble accessing your website from Google’s public DNS? Check your DNSSEC.

    I encountered a strange problem today. Someone could access their website from their cell phone but not their laptop and said a friend a few states away also couldn’t reach it. But I could reach it just fine.

    When we started digging into what was going on, I found that he was using Google’s public DNS. When I switched to Google’s DNS, I couldn’t reach the site either.

    So what is going on here? Apparently Google checks DNSSEC and a lot of other DNS resolvers do not. If it is misconfigured the site won’t resolve.

    Here is where you can check your domain’s DNSSEC.

    Need a fast and easy way to enable DNSSEC if your registrar doesn’t provide it? Check out Cloudflare.

  • Web crawlers, Regex for Markdown URLs, and Removing your site from Google search results

    Web crawlers, Regex for Markdown URLs, and Removing your site from Google search results

    Today I learned:

    Web Crawlers

    Need a web crawler but don’t want to write one?


    Getting pages removed from Google cache

    Have an old site that you need to keep live but don’t want the results to show on Google searches? Here are a few things you need to do:

    1. Change the robots.txt or password protect your site to prevent search engines from indexing.
    2. Log in to Google Webmaster Tools and submit the site to the URL Removal tool.
    3. Finish what you need the site up for ASAP and take it offline.

    This matches the links above:

    • Search: ([wS]*[mo7b/])$
    • Replace: [1](1)
  • Circular Progress Bar Count Up with Javascript

    Circular Progress Bar Count Up with Javascript

    I took the Javascript date difference counter from a few weeks ago and added a circular progress bar to it with ProgressBar.js.

    In the days.animate section, I make sure to prevent the circle from ever reaching 100%. It will get extremely close as the years pass and the numerator comes closer and closer to the denominator, but the denominator will always be slightly larger. Thanks to Eric Davis for helping me come up with the solution.

    Javascript Counter with circular progress

    The results:

    The javascript, which counts the time since a certain date:

     var elements = document.getElementById('s'); var elementm = document.getElementById('m'); var elementh = document.getElementById('h'); var elementd = document.getElementById('d');  var seconds = new ProgressBar.Circle(elements, { duration: 200, color: "#DC242F", trailColor: "#ddd", strokeWidth: 5, trailWidth: 3 }); var minutes = new ProgressBar.Circle(elementm, { duration: 200, color: "#7FD0E5", trailColor: "#ddd", strokeWidth: 5, trailWidth: 3 }); var hours = new ProgressBar.Circle(elementh, { duration: 200, color: "#F5BB6A", trailColor: "#ddd", strokeWidth: 5, trailWidth: 3 }); var days = new ProgressBar.Circle(elementd, { duration: 200, color: "#4598C9", trailColor: "#ddd", strokeWidth: 5, trailWidth: 3 });  shortcode_date = '2016-04-11T11:00:00'  setInterval(function() { now = new Date(); countTo = new Date(shortcode_date); difference = (now-countTo); var second = Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1); seconds.animate(second / 60, function() { seconds.setText(""number">" + second + "" + ""label">Seconds"); }); }, 1000); setInterval(function() { now = new Date(); countTo = new Date(shortcode_date); difference = (now-countTo); var minute = Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1); minutes.animate(minute / 60, function() { minutes.setText(""number">" + minute + "" + ""label">Minutes"); }); }, 1000); setInterval(function() { now = new Date(); countTo = new Date(shortcode_date); difference = (now-countTo); var hour = Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1); hours.animate(hour / 24, function() { hours.setText(""number">" + hour + "" + ""label">Hours"); }); }, 1000); setInterval(function() { now = new Date(); countTo = new Date(shortcode_date); difference = (now-countTo); var day = Math.floor(difference/(60*60*1000*24)*1); days.animate(day / (day + 5), function() { days.setText(""number">" + day + "" + ""label">Days"); }); }, 1000); 

    The elements it targets:

     id="countup"> 	 class="part"> id="d">
class="part"> id="h">
class="part"> id="m"> class="part"> id="s">

And the styles to display it:

 #countup { margin-left: auto; margin-right: auto; text-align: center; font-family: "Lato",Helvetica,Arial,sans-serif; } #countup span.number { display: block; padding: 0px; margin: 0; font-size:70px; line-height: 75px; text-align: center; } #countup span.label { display: block; font-size:25px; line-height: 30px; }  #countup .part { display: inline-block; text-align: center; width: 22%; padding: 1%; }  @media only screen and (max-width: 1200px) { #countup span.number { font-size:60px; line-height: 65px; text-align: center; } #countup span.label { display: block; font-size: 20px; line-height: 25px; }  }  @media only screen and (max-width: 820px) { #countup span.number { display: block; padding: 0px; margin: 0; font-size:40px; line-height: 45px; text-align: center; } #countup span.label { display: block; font-size:15px; line-height: 15px; }  }  @media only screen and (max-width: 600px) { #countup span.number { display: block; padding: 0px; margin: 0; font-size:30px; line-height: 35px; text-align: center; } #countup span.label { display: block; font-size:12px; line-height: 12px; } } 

Next steps: Registering this with a WordPress shortcode.

  • Converting an Aperture Library to Lightroom

    Converting an Aperture Library to Lightroom

    I have multiple old Aperture photo libraries that I can’t really use anymore. Aperture doesn’t run on El Capitan and I don’t have any system that it can run on. I’ve been using Adobe Lightroom for the past four years anyway. So I did some research into options into how I can retrieve my photos.

    Opening the package

    The great thing about Aperture was that it always kept the master images and applied edits on the fly. So I knew that I could get the master images out of Aperture. The way you can get to them is right-clicking on the library file and selecting “Show Package Contents.” Then you can take the masters folder and copy it out of the library.

    Plugin from Adobe

    Adobe also has a plugin to copy over images and metadataArchived Link.

    Preserving your edits?

    Unfortunately I haven’t found a way to also preserve/move/translate edits made in Aperture to Lightroom. If you know a way, let me know!

  • Snack Time Episode 2 – Our Biggest Pfand

    Snack Time Episode 2 – Our Biggest Pfand
  • Amending Commits, Matplotlib, and More Python

    Amending Commits, Matplotlib, and More Python

    I’ve been on vacation and spend the last two days catching up and not doing a lot of learning, so I’ve been lazy in putting up TIL posts. That is over. (I did, however, push some updates to my Apple Photos Analysis project.) Here is a small collection of things I learned in the last week.


    Amending commits

    Say you forgot to add a file to your last commit or you made a typo in your commit message. You can amend it!

    Make the necessary changes, then do this:

    git commit --amend -m "Commit message here"

    If you’ve already pushed it to an external repository, you’ll need to force the push since the external repo will look like it is ahead. If branch protection is turned on, you’ll need to make a new commit. Make sure you aren’t overwriting anything important!

    git push origin master --force

    Here are the docs.


    Adding data labels to the top of bar charts in Matplotlib

    Matplotlib is a great plotting library for Python.

    def autolabel(rects):     # attach some text labels     for rect in rects:         height = rect.get_height()         plt.text(rect.get_x() + rect.get_width()/2., 5+height,                 '%d' % int(height),                 ha='center', va='bottom') rect = plt.bar(xs, counted_hours, color=color)  # To use: autolabel(rect)

    Saving images in matplotlib

    plt.savefig('directory/filename.png')

    Counting items that match a regex pattern

    def hour_finder(regex,lines): 	time_counter = 0 	for l in lines: 		if re.match(regex, l): 			time_counter = time_counter + 1 	return time_counter 	 # To use hour_finder('^8:[0-9]{2,}:[0-9]{2,}sPM',time_csv)

    Splitting!

    Splitting by a space ' ' and choose the item after the split ([1] because counting starts at 0)

    list = [i.split(' ')[1] for i in time_csv]