Chuck Grimmett

Data and Visualization

Taxonomies

  • WordPress 6.1 Sponsored Contributor Stats

    A month ago I wrote a post about stats for WP Core releases and received some good feedback on it. Some folks also pointed out that Jb Audras writes better general stats posts for releases than what I put together, and I agree!

    One thing that I found was missing from all other sources was stats on sponsored contributors, so I’m starting to keep track of that here in this spreadsheet: 

    I’m collecting:

    • Number of sponsored contributors
    • Breakdown of the companies they are being sponsored by
    • Breakdown of listed employers, sponsored or not

    If anyone wants to help me backfill sponsorship stats for previous releases from data Jb Audras and the core release team pulls before each release, I’d be happy to collaborate!


    Stats for 6.1

    Total contributors: 798
    Sponsored: 149
    % sponsored: 18.7%

    The top sponsoring companies:

    • Automattic sponsored 63 contributors (42.28%)
    • WPDeveloper sponsored 11 contributors (7.38%)
    • Yoast sponsored 8 contributors (5.37%)
    • GoDaddy sponsored 6 contributors (4.03%)
    • Awsm Innovations sponsored 6 contributors (4.03%)
    • XWP sponsored 5 contributors (3.36%)
    • Multidots sponsored 5 contributors (3.36%)
    • Extendify sponsored 5 contributors (3.36%)
  • Some WordPress Core Contributor stats

    The Inspiration

    Earlier this week David Bisset asked:

    This got me curious. Is this data out there? How might one get it?

    I started looking at core release posts and saw that contributors are linked, which gave me the idea to scrape it and see what I could come up with.

    Caveats about this data

    1. Since this data is from the thanked contributors in core release posts, it includes more than just code contributions. It also includes documentation, testing, design, marketing, etc.
    2. I only included data from 5.0-6.0 named releases.
      • 5.0 was released in December 2018, almost 4 years ago. 4 years seemed far enough to go back.
      • I only included named core releases, as those are the larger ones that more people contribute to. The maintenance and security releases have a much smaller set of contributors.
    3. The data gets less accurate the further I go back in terms of release dates because I can only scrape their current profile, not their previous profiles. Some most likely switched employers.
    4. The data is only as accurate as the profiles on WordPress.org. Not all profiles have employers listed. There are some folks I know work for big companies in the WordPress ecosystem and contribute to core who do not have an employer listed. I did not add any that were missing, I went by what is available.
    5. I had to do a lot of manual clean up to make the data consistent, which is typical when you scrape data from the web. If I made a mistake or missed something, that mistake is mine alone.
    6. In full transparency, I work at Automattic. This exploration was not done as part of my work there, but as a curious member of the WordPress.org community. In the WordPress project, I am a part of the Photos team.
    7. There are many other ways to contribute to the WordPress ecosystem and project that are not captured in this data. I only pulled data on contributors to named core releases.
    8. It is possible I made some scraping, formula, or calculation mistakes. If you find something wrong, please let me know.

    Contributors to named core releases, grouped by company, for versions 5.0-6.0

    Note: If someone has an employer listed on their profile, that does not necessarily mean they are sponsored by that company. If you want to know about sponsored contributors, go to the Sponsored section.

    Core release6.05.95.85.75.65.55.45.35.25.15.0
    Total contributors551658560502679866592707385550477
    Company 1Automattic (77, 14%)Automattic (94, 14.3%)Automattic (88, 15.7%)Automattic (66, 13.1%)Automattic (79, 11.6%)Automattic (87, 10%)Automattic (60, 10.1%)Automattic (61, 8.6%)Automattic (42, 10.9%)Automattic (55, 10%)Automattic (62, 13%)
    Company 210up (15, 2.7%)Yoast (14, 2.1%)Yoast (12, 2.1%)10up (12, 2.4%)Yoast (14, 2.1%)10up (16, 1.8%)10up (11, 1.9%)Yoast (16, 2.3%)10up (11, 2.9%)Yoast (20, 3.6%)10up (14, 2.9%)
    Company 3Yoast (10, 1.8%)10up (11, 1.7%)10up (11, 2%)Yoast (11, 2.2%)10up (13, 1.9%)Whodunit (11, 1.3%)Yoast, Whodunit, Human Made (7, 1.2%)10up (14, 2%)Human Made (6, 1.6%)10up (16, 2.9%)Human Made (11, 2.3%)
    Company 4Multidots (9, 1.6%)Multidots (10, 1.5%)Human Made (5, 0.9%)XWP, Google (6, 1.2%)Awesome Motive (8, 1.2%)Yoast, rtCamp (9, 1%)XWP (6, 1%)Human Made (9, 1.3%)Yoast (5, 1.3%)Human Made (9, 1.6%)Yoast (10, 2.1%)
    Company 5rtCamp (6, 1.1%)XWP (6, 0.9%)XWP, rtCamp Google, Bluehost, Awesome Motive, Alley (4, 0.7%)Awesome Motive (5, 1%)XWP (6, 0.9%)XWP, WP Engine, Human Made (8, 0.9%)Multidots, Google, Bluehost (4, 0.7%)Multidots (7, 1%)Google (4, 1%)rtCamp (7, 1.3%)Bluehost (6, 1.3%)
    No company listed245 (44.5%)306 (46.5%)259 (46.3%)238 (47.4%)332 (48.9%)434 (50.1%)307 (51.9%)348 (49.2%)182 (47.3%)247 (44.9%)230 (48.2%)
    Company name (Count of employed contributors, percentage of the total number of contributors)

    Individuals who contributed to all 11 of the most recent named core releases

    49 people have contributed to all 11 releases (5.0-6.0) I pulled data for. I think these people deserve special recognition:

    The companies these awesome individuals work for:

    • Automattic (13)
    • Google (4)
    • 10up (3)
    • Alley (2)
    • XWP (2)
    • Yoast (2)
    • Accessible Web Design (1)
    • Advies en zo (1)
    • Awesome Motive (1)
    • Bluehost (1)
    • Dekode Interaktiv AS (1)
    • FlipMetrics (1)
    • GoDaddy (1)
    • Happy Prime (1)
    • Human Made (1)
    • Parship Group (1)
    • Penske Media Corporation (1)
    • SendtoNews Incorporated (1)
    • Shopify (1)
    • Whodunit (1)
    • iThemes (1)
    • required (1)

    7 of these individuals has no employer listed in their wordpress.org profile.

    27 of these individuals have the Sponsored tag on their profile.

    These are the number of contributors per release that have the Sponsored tag in their profile. This is a count of sponsored contributors, not necessarily a good breakdown of the amount contributed by each.

    Core release6.05.95.85.75.65.55.45.35.25.15.0
    Total contributors551658560502679866592707385550477
    Sponsored110125103771061046772546362
    Sponsored %19.9%18.9%18.4%15.3%15.6%12%11.3%10.2%14%11.5%13%

    These are the sponsored contributors grouped by company. Includes count of sponsored contributors and the percentage of the total number of sponsored contributors for that release.

    Core release6.05.95.85.75.65.55.45.35.25.15.0
    Company 1Automattic (61, 55.5%)Automattic (65, 52%)Automattic (55, 53.4%)Automattic (32, 41.6%)Automattic (43, 40.6%)Automattic (36, 34.6%)Automattic (24, 35.8%)Automattic (23, 31.9%)Automattic (16, 29.6%)Automattic (16, 25.4%)Automattic (21, 33.9%)
    Company 2XWP (7, 6.4%)Yoast (10, 8%)Yoast (7, 6.8%)Yoast (8, 10.4%)Yoast (11, 10.4%)Whodunit (7, 6.7%)Yoast (6, 9%)Yoast (10, 13.9%)Yoast (5, 9.3%)Yoast (11, 17.5%)Yoast, XWP (6, 9.7%)
    Company 3Yoast (6, 5.5%)Multidots (6, 4.8%)XWP (5, 4.9%)XWP (5, 6.5%)XWP, 10up (5, 4.7%)Yoast, XWP, WP Engine (6, 5.8%)Whodunit (5, 7.5%)Whodunit, Google (4, 5.6%)Google (4, 7.4%)XWP, Human Made, Google (4, 6.3%)Google (4, 6.5%)
    Company 4Google, GoDaddy, Extendify (4, 3.6%)XWP (5, 4%)Google, 10up (4, 3.9%)Google, 10up (4, 5.2%)WP Engine, Google, Awesome Motive (4, 3.8%)Human Made, Google, Awesome Motive (4, 3.8%)Google (4, 6%)XWP, Human Made (3, 4.2%)XWP, Human Made, Bluehost, 10up (3, 5.6%)10up (3, 4.8%)Human Made, Bluehost, 10up (3, 4.8%)
    Company 5Multidots, Human Made, Awesome Motive (3, 2.7%)Google, Bluehost (4, 3.2%)GoDaddy, Awesome Motive (3, 2.9%)WP Engine, Whodunit, Required, Human Made, GoDaddy, Bluehost, Awesome Motive (2, 2.6%)Human Made, Extendify, Bluehost (3, 2.8%)GoDaddy, Bluehost, 10up (3, 2.9%)XWP, Human Made, 10up (3, 4.5%)WP Engine, rtCamp, Required, Bluehost, Awesome Motive, 10up (2, 2.8%)WP Engine, WebDevStudios, Awesome Motive (2, 3.7%)WPMUDEV, Whodunit, WebDevStudios, Required, Bluehost, Awesome Motive (2, 3.2%)WebDevStudios Required (2, 3.2%)
    Company name (Count of sponsored contributors, percentage of the total number of sponsored contributors)

    How I gathered and analyzed this data

    1. For each named core release (I.e. 6.0 “Arturo”, 5.9 “Josephine”, etc) I used the free version of Data Miner to pull the list of thanked contributors in the release post.
      • You could do this with a script too, but I already had Data Miner installed and knew how to use it, so it was the fastest way to get what I needed.
      • The element I targeted: p.is-style-wporg-props-long a
      • I saved the href attribute for each result in a text file.
    2. I looped through each text file of contributor URLs with a bash script and pulled in two fields from their wordpress.org profiles: Employer and Contributions.
      • I used curl, tr, awk, and pup to transform the data into something useable.
    // Assumes an input file named 5-1.txt with a list of profile URLs
    // requires pup https://github.com/ericchiang/pup
    for url in $(head -n800 5-1.txt); do
        employer="$(curl -s $url | pup -p 'li#user-company text{}' | awk '{sub(/Employer:/,"")} 1' | tr -d '\n' | tr -d '\t')"
        contributions="$(curl -s $url | pup -p 'div.item-meta-contribution text{}' | tr -d '\n' | tr -d '\t')"
        echo "$url | $employer | $contributions" >> 5-1_contributors.txt
    done
    1. I first started exploring the data in Google Sheets and made pivot tables for each named release.
      • This took a lot of data clean up to make the data more consistent. Since the Employer field is open text, there were lots of different versions of the same company (Company, Company Inc, Company PVT LTD, etc). I cleaned it up the best I could in the time I wanted to spend on it, but there are still probably some duplicates.
      • This gave me the table of stats for the companies represented in each named release.
      • I used regex to find which company sponsors a contributor based on their Contributions section on their profile and made a pivot table of this information.
    2. I used Datasette to explore a CSV of all contributors and which version they contributed to. This gave me the list of 49 people who contributed to all 11 versions I checked and which companies they work for.

    Data sources

    Want to take a look at this data?

    More areas for exploration

    1. Code contributions from SVN?
      • Number of lines changed by contributor and also grouped by employer
    2. Finding more accurate data?
      • If there were snapshots of this data from each release, it would be nice to use those instead. I could only pull data from current profiles, and users may have switched employers. For example, up until recently mkaz worked at Automattic, but since he no longer does, his previous contributions are not grouped under Automattic.
      • Not all profiles have employers listed. There are some folks I know work for big companies in the WordPress ecosystem and contribute to core who do not have an employer listed.
    3. Graphing different facets of this data to see how it changes over time.
  • Free Charting Tools for Your Next Article

    Free Charting Tools for Your Next Article

    A Praxis participant emailed me last week asking for recommendations on free embeddable charting tools for an article he is writing. I thought that the information would be useful for everyone, so I wrote an article with examples! https://discoverpraxis.com/free-charting-tools-next-article/Archived Link

  • Documenting the Process of Data Visualizations

    The DataSketch.es project has awesome process documentation for how Nadieh and Shirley go about making their incredible visualizations each month. This is a treasure trove of valuable insights for how they approach projects, how the projects evolve, and how they overcome issues they run in to.

  • Our Inflated Thanksgiving, 2016 Edition

    Our Inflated Thanksgiving, 2016 Edition

    It’s not just the balloons at the Macy’s Thanksgiving Day Parade that are inflated.

    Each year the American Farm Bureau Federation collects an informal price survey for a typical Thanksgiving dinner. The shopping list has remained the same for the past 31 years: turkey, bread stuffing, sweet potatoes, rolls with butter, peas, cranberries, a veggie tray, pumpkin pie with whipped cream, and coffee and milk, all to feed a family of 10.

    At first glance, it seems like the price of food has trended upward since 1986. Once you adjust for inflation, however, you get a different story. The inflation-adjusted price has stayed relatively flat over time with minor fluctuations. The purchasing power of our currency in circulation has gone down over time, driving up the price of goods.

    As Mark Perry points out, this is no reason for despair. The average hourly wage of the American worker has increased steadily, making Thanksgiving more affordable than ever. That is something to be thankful for this year.

    The data for this chart was collected by the American Farm Bureau Federation. I adjusted this price data for inflation using the BLS’s CPI Inflation Calculator. The chart was built using Chart.js.

    I retooled my original 2014 version. I paid closer attention to colors and made this one responsive. I think it is a big improvement!

    This was also published over at FEE’s Anything Peaceful blog.

  • Praxis Data Workshop – Telling a Stronger Story with Data Visualization

    Praxis Data Workshop – Telling a Stronger Story with Data Visualization

    On October 13 I ran a data-related workshop for the Praxis community.

    I split the talk up into two parts:

    1. How you can apply the basic concepts of data analysis to your career, whether it be sales, marketing, shipping, coaching, cooking, management, etc. These techniques will help you tell a better story, be more convincing, and become more effective at your job.
    2. An introduction to visualizing data and information, including some tools, resources, and inspiration to get you started. If you are interested in data visualization, think of this as a jumping-off point.

    The Slides

    Praxis Data Workshop - Telling a Stronger Story with Data Visualization

    Download my slides without my talking notes ↓

    Download my slides with my talking notes ↓

    The Video

    Thanks to TK Coleman for asking me to do the worksop and for recording the video!

    Examples mentioned

    Resources mentioned

    Books Mentioned

    Tools

    • Excel – Basic, but a great first stop for exploring and sorting your data set.
    • Vega, Lyra, and Voyager – Open source data tools for exploration and visualization
    • Tableau Public – Free version of Tableau, one of the top, easy-to-use visualization software on the market
    • RAW – Makes using complex D3 chart types easy to use.
    • Carto – Free maps without needing coding knowledge!
    • Chart.js – Easy, pre-packaged interactive chart types. Need to know some JavaScript.
    • D3.js – One of the top DOM manipulation/data visualization libraries
    • Paper.js – An open source vector graphics scripting framework
    • R – Popular data science language
    • Python’s Pandas – Popular data science library for Python
    • Matplotlib – Popular graphing library for Python
    • Reporter app – Personal data collection app

    PDP ideas

    Here are a few ideas on how Praxis participants can incorporate data analysis and visualization into their PDPs (personal development plans):

    1. Read How To Measure Anything, Lean Analytics, or How to Lie with Statistics and write a review on both Amazon and your blog.
    2. Pick 1-2 metrics in your personal life and collect data on them for two weeks. After two weeks, write a blog post explaining some trends you see, explaining the outliers, and visualizing the data in at least two ways. A few ideas: Sleep time and quality, caffeine intake and focus, time spent on social media, counts of something you produce at work, pages of books read, how many times you say “thank you” to someone, how many blog posts you write, etc. Check Dear Data for ideas. Reporter app is useful for collection.
    3. Pick 1-2 metrics that your business partner is currently tracking. Analyze them and write up the results. Make a presentation for your managers.
    4. Find a data set of any size and write a blog post framing it in three different ways.
    5. Get sales or marketing data (or something that includes location data related to your business) from your business partner and map it with Carto. Make it private so you aren’t sharing private data. Write a blog post about what you found.
    6. Research 3 different chart types and write explanatory blog posts on how they are used and give some examples of what to visualize with them.
    7. Identify something you wanted to track but didn’t and find a proxy for it.
    8. Pick something that interests you and build a small visualization with Chart.js or D3.js. Write a blog post explaining what is interesting. Guide us through it.
    9. Dig in to an open data set, find some outliers, and frame some comparisons. Write it up in a blog post.
    10. Dig in to an open data set and make a visualization for a small, interesting facet of it. Write it up in a blog post.
    11. For sales people: Does one region do spectacularly well or spectacularly poorly? Dig in to why and write it up.
    12. For marketers: Are certain channels performing better than others? Dig in to why and write it up.
    13. Look into your business partner’s revenue over time. Do you find any interesting trends? Do some research and write them up.
    14. Come up with an idea on what your team can track over the next few months to improve your efficiency/deliverables. Pitch the team on what to do, why they need to do it, and how you will use the data at the end of the quarter.
  • Using Word Frequency Charts for Better Word Clouds

    Using Word Frequency Charts for Better Word Clouds

    Word clouds

    Data scientists notoriously hate word clouds. Besides for figuring out what the top 2-3 words are (because they are the biggest), it is difficult to see how much one word is used relative to another. Unfortunately, clients and non-data people love word clouds and sometimes insist on them. What is a self-respecting data nerd to do?

    Pair it a word frequency chart!

    The easiest way to do this is by using Python’s counter:

    Counter(words).most_common()

    Then you can use your favorite charting tool to make a bar chart of the results. I prefer D3.js.

    Results

    Word Frequency Chart

    Word Cloud

    If you see both together, you get a better understanding of the words being used. Of course, a single word doesn’t always capture sentiment. They can be helpful in smaller data sets, but sometimes common phrases are more helpful in larger data sets. For common phrases, use n-gram analysis.

    For more on visualizing text, check out episode 62 of the Data Stories podcast and the Text Visualization Browser.

  • Photo Metadata Analysis Project

    Photo Metadata Analysis Project

    I’m working my way through some data science and visualization books right now. I found that I learn better by doing small projects than I do by copying examples in books, so I designed a little project to apply some of what I learned and to learn some new skills along the way.

    My goal was to make a project where I do everything from start to finish: Create my own data set, format it, analyze it, then visualize it. I also wanted to make it fairly common and as automated as possible so it could be repeated by others.

    Here is what I came up with: Extracting metadata from my iPhone photos, analyzing it in different ways (days, months, hours, seasons), and visualizing it. I used free tools to do the extraction, formatting, and visualization, then scripted everything with AppleScript and Python to automate it.

    Technical Details

    You can find the full repository on GitHub. If you have a recent Mac with Photos.app and TextWrangler, you can run the scripts and produce your own charts!

    • I used AppleScript to loop through photo metadata in Photos.app and write it out to a CSV files that it creates in the same directory as the scripts.
    • I used TextWrangler’s grep functionality via AppleScript to break apart the date strings into days of the week, dates, and times, and to remove bad or null location strings (lat,long). I know I could have written this in Python, but I didn’t want to reinvent the wheel. TextWrangler’s AppleScript library is very powerful and easy to use.
    • Python was my tool of choice for analyzing the CSV files in various ways and visualizing the results with one of its plotting libraries, matplotlib.
    • The map of where photos were taken in the US was generated with D3.js.
    • Once everything has been generated and saved, AppleScript opens the images in Preview and launches a simple Python webserver to show the map.

    The Results

    Photos by hour block

    AM vs PM percentage

    Months count breakdown

    Seasons count breakdown

    Seasons percentages

    Weekday count breakdown

    Weekday percentages

    Photo Map

    Lessons

    • I really beefed up my understanding of basic Python (with help from Eric Davis!)
    • I dusted off my AppleScript knowledge and gave it a workout. I learned that AppleScript has a concept of lists that you can pass into and out of programs. This was the key to launching all of the charts in a single preview window.
    • This was a great exercise in UX. How can this be both easy to use and easy to interpret?
    • This was an exercise in thinking programatically. How can this be built in a way that makes it reusable?
    • I learned how to project location information onto a map with D3.js. I’ve used D3.js for charts before, so this was a good way to expand my skills.
    • This was a good way to practice my git skills and think through how to structure a project and make executable code.
    • There is a lot more I can add to this (more mapping options, more ways to count the photos, outputting the photos in a calendar heatmap), but I feel comfortable stopping and moving on because I learned what I wanted to from it and I’m ready to start a new project. I might come back to this in the future and I might not, but either way I’m happy with this.

    Cavaets

    • This analysis is not scientific, it was for fun. Since my photos were taken with different cell phones across non-controlled time periods, I can’t use this analysis to say things like, “I’m more likely to take photos in the spring than the fall.” The truth is that there are photos in here from three springs but only two falls.
    • I can’t guarantee that my code will work for everyone. It is still a little buggy and hasn’t been tested for all scenarios. I know this and know how I would test it, but this project isn’t big enough to warrant it.
    • The color palettes I used aren’t bulletproof. If you use F.lux or Night Shift the yellows will blend in to the screen, and if you have visual impairments you might not be able to distinguish between the greens and blues.

    Try it for yourself

    You can download the repository from GitHub and run it against your Photos.app library. The requirements and instructions are in the README. Let me know if you have any issues and I’ll do my best to help you out.

  • 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);
          }
        }
      });
    }

  • Steph Curry’s Advantage (Or How to Become a Leader in the NBA)

    Steph Curry’s Advantage (Or How to Become a Leader in the NBA)

    I don’t really follow basketball. But since I’ve been hearing a lot about this Steph Curry guy in the news, on Facebook, and on podcasts, I decided to look into his stats. And since I’m trying to teach myself about data science and visualization, I thought I’d visualize some of his stats to see what I could learn.

    From what I could tell Steph Curry had a decent start to his career, but while his was above-average, he didn’t seem to be a star. Then after he got injured during the 2011-12 season, he must have had a revelation because he came back the next season and made a name for himself.

    The next season he started taking radically more three point shots and it paid off for him. His overall points went up as he made more three point attempts:

    Here are the number of three point attempts vs three point shots made by season with the circles scaled by the number of overall points he made that season:

    Even though he took more shots, his overall shooting percentage and percentage on three-pointers has increased recently, but not dramatically. It has fluctuated over his career:

    Many current players have him beat on overall shooting percentage and a few guys are rivaling him on three point percentage (Jason Kapono, Steve Novak, Kyle Korver.)

    So if you can’t stand out by being more accurate than everyone else, what can you do? In a game that is driven by the final overall score instead of percentages, being about as accurate as everyone else but willing to shoot more pays off. Curry is willing to take more long shots than anyone else in the league, by far.

    Here are Curry’s 3 point attempts vs 3 point shots made compared with the other top shooters in the league for the past four years:

    Here is the same data visualized as a bump chart. You can see the other top shooters jostling positions, but Curry has been king for the past four years:

    I realize that there is more to the game than just taking more shots. You need incredible talent and skill to keep up a percentage like Curry’s from anywhere on the court. Given his success, I’m willing to bet that we’ll see more players trying to emulate his approach next season.


    Side note: James Harden seems to be using the same strategy, except with two point shots and free throws. It is paying off for him, too. He is currently the number two leader in the NBA, right behind Steph Curry.

    Sources:

    Tools:

  • Spotlight on Speech Codes 2015 Animated Web Infographic

    Spotlight on Speech Codes 2015 Animated Web Infographic

    I took a static infographic made by a client in Illustrator and applied some web magic to make it animated and interactive. Along the way I developed stronger JavaScript, jQuery, and CSS animation skills.

    Note: I made this for a client of eResources, my current employer.

    Project and Challenges:

    • A client came to us with a pre-designed infographic made in Illustrator. They wanted it to be interactive, sharable, and viewable on the web.
    • We had a limited number of hours we could use. This didn’t include enough time for making the infographic fully responsive, so we needed to get creative with how it would work on mobile.

    What I learned:

    • Structuring code in a clean, readable way
    • Pre-development sketching of outlines
    • CSS animation with keyframes
    • Nuances of layering containers and using selectors in CSS.
    • Giving content sections a parallax effect
    • Positioning elements by the page’s scroll position
    • jQuery for clicking and toggling actions
    • Open Graph and Twitter Card metadata
    • Making custom share URLs with encoded pre-populated data
    • Using Javascript to check User Agents to determine whether or not Skrollr should fire (it doesn’t play well with iOS)

    View the finished product in action! →

    Third-party tools used

    • Skrollr to drive parallax and positioning elements by the page’s scroll position
    • Wow.js for triggering CSS animations
    • Animate.css so I didn’t have to write all of the CSS animations from scratch
    • Chart.js for rendering the pie charts and making them interactive
    • jQuery for clicking and toggling actions

    In-Progress Photos

    I first sketched the infographic out on an IKEA drawing paper roll to plan out where elements should go and how to structure the code overall.

    Sketching it out

    As I wrote the code, I previewed and tested it in real-time with Coda’s AirPreview.

    Live Preview

    View the finished product in action! →

    Original image:

    Spotlight 2015 Static Image
  • Our Inflated Thanksgiving

    For the past 29 years, the American Farm Bureau Federation has conducted an informal survey of the price of a classic Thanksgiving dinner for 10 people. At first glance, it looks like the price of food has been steadily rising. But when you adjust the numbers for inflation, you get a different story. It isn’t the cost of our food that has been rising, but the amount of US currency in circulation.

    This year, we’re thankful for technologies like bitcoin breaking the Federal Reserve’s grip on money.

    Happy Thanksgiving!

    The individual prices of a traditional Thanksgiving dinner this year: