<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zvonimir Boban on Medium]]></title>
        <description><![CDATA[Stories by Zvonimir Boban on Medium]]></description>
        <link>https://medium.com/@zvonimir.boban.mef?source=rss-e31978768a4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tU10Q2sKfWqce1ScSVNB6g.jpeg</url>
            <title>Stories by Zvonimir Boban on Medium</title>
            <link>https://medium.com/@zvonimir.boban.mef?source=rss-e31978768a4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:25:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zvonimir.boban.mef/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Make an Advanced Spider Chart in Python]]></title>
            <link>https://medium.com/data-science/how-to-make-an-advanced-spider-chart-in-python-adbdb6c24a66?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbdb6c24a66</guid>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 17:14:15 GMT</pubDate>
            <atom:updated>2024-09-05T19:58:42.644Z</atom:updated>
            <content:encoded><![CDATA[<h4>Step-by-step explanation with an easy to use function at the end</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vkVeVZgRIskvbGxLfFGUQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lincon_street?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Divyadarshi Acharya</a> on <a href="https://unsplash.com/photos/selective-focus-photography-of-spider-on-web-Qbs6liSxjr8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>💡The Motivation</h3><p>There are multiple Python libraries which can be used to make classic spider/radar charts. One thing all those libraries have in common is that they only offer spider charts with a single scaled axis, usually displaying a scale ranging from 0 to 100.</p><p>Of course, rescaling feature values to a common scale is necessary in order to be able to compare them, but it leaves out crucial information on the absolute range of values of each feature. Since this information cannot be obtained from the graph, we have to dig back into the data. In the best case, this is time consuming and tedious, and in the worst, we do not have access to the original data, which means we don’t have acces to crucial context needed to adequately understand the comparisons.</p><p>A logical step-up would be to make a spider chart with an axis displaying absolute values for each displayed feature — a chart known as a <strong>multiaxis spider chart</strong>. You might expect that this chart would also be offered by many libraries, but searching for them left me empty handed. Motivated by this lack of results, I decided to make my own solution and offer my approach to you in this step-by-step guide with an easy to use function provided at the end.</p><h3>🕸️ The Chart</h3><p>To demonstrate how to make a multiaxis spider chart, I will be using a small part of the well known mtcars dataset. The dataset is derived from the 1974 Motor Trend magazine and was first published in a study Henderson and Velleman 1981 [1]. Let’s load the data and the required libraries.</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import MinMaxScaler<br>from plotnine import *<br><br>mtcars_values = {<br>    &#39;mpg&#39;: [19.7, 15, 21.4],<br>    &#39;cyl&#39;: [6, 8, 4],<br>    &#39;disp&#39;: [145, 301, 121],<br>    &#39;hp&#39;: [175, 335, 109],<br>    &#39;drat&#39;: [3.62, 3.54, 4.11],<br>    &#39;wt&#39;: [2.77, 3.57, 2.78],<br>    &#39;qsec&#39;: [15.5, 14.6, 18.6],<br>    &#39;vs&#39;: [0, 0, 1],py<br>    &#39;am&#39;: [1, 1, 1],<br>    &#39;gear&#39;: [5, 5, 4],<br>    &#39;carb&#39;: [6, 8, 2],<br>    &#39;wtdip&#39;: [401.65, 1074.57, 336.38]<br>}<br><br>mtcars = pd.DataFrame(mtcars_values, <br>index=[&quot;Ferrari Dino&quot;, &quot;Maserati Bora&quot;, &quot;Volvo 142E&quot;])<br><br># Select and rename columns<br>p_data = mtcars.reset_index().rename(columns={&#39;index&#39;: &#39;group&#39;})[[&#39;group&#39;, &#39;mpg&#39;, &#39;cyl&#39;, &#39;hp&#39;, &#39;wt&#39;, &#39;qsec&#39;]]<br>p_data.columns = [&#39;group&#39;, &#39;Miles per Gallon&#39;, &#39;Cylinders&#39;, <br>&#39;Horsepower&#39;, &#39;Weight&#39;, &#39;Quarter mile\ntime&#39;]</pre><p>As you can see, I will be using the plotnine library to create the chart. Inspired by ggplot2, the plotnine library is also based on the concept of grammar of graphics, allowing for creation of graphs by stacking multiple layers on top of one another. This powerful concept lets us create essentially any visualizationwe can think up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clsdr-vj1YoArpt_-lr5_g.png" /><figcaption>The grammar of graphics approach to chart construction. Image by Author</figcaption></figure><p>The layered approach calls for separate construction of different aspects of the graph. First we will create the chart outline. Since spider charts deal with polar coordinates, I made a function which calculates the coordinates of the polygon tips depending on the number of variables in the dataset.</p><pre># Calculate the coordinates of polygon tips<br>def circle_coords(r, n_axis=len(p_data.columns) - 1):<br>    fi = np.linspace(0, 2*np.pi, n_axis+1) + np.pi/2<br>    x = r * np.cos(fi)<br>    y = r * np.sin(fi)<br>    return pd.DataFrame({&#39;x&#39;: x, &#39;y&#39;: y, &#39;r&#39;: r})<br><br>central_distance = 0.2<br>axis_name_offset = 0.2<br><br>circle_df = pd.concat([circle_coords(r) for r in np.arange(0, 1.25, 0.25) + central_distance])<br><br>step_1 = (ggplot(circle_df, aes(&#39;x&#39;, &#39;y&#39;)) +<br>  geom_polygon(data=circle_coords(1 + central_distance, p_data.shape[1] - 1), alpha=1, fill=&#39;beige&#39;) +<br>  geom_path(aes(group=&#39;r&#39;), linetype=&#39;dashed&#39;, alpha=0.5) +<br>  theme_void() +<br>  theme(legend_title=element_blank(),<br>        legend_direction=&#39;horizontal&#39;,<br>        legend_position=&#39;bottom&#39;,<br>        legend_box_spacing=0))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASHM9pMVg3wfhpuJ2KkT2g.png" /><figcaption>Step 1: Creating the background for the chart. Image by Author</figcaption></figure><p>Next, we have to calculate the coordinates for the axes and add them to the chart.</p><pre># Calculate the coordinates for the axis lines<br>def axis_coords(n_axis):<br>    fi = np.linspace(0, 2*np.pi*(1-1/n_axis), n_axis) + np.pi/2<br>    x1 = central_distance * np.cos(fi)<br>    y1 = central_distance * np.sin(fi)<br>    x2 = (1 + central_distance) * np.cos(fi)<br>    y2 = (1 + central_distance) * np.sin(fi)<br>    return pd.DataFrame({&#39;x&#39;: np.concatenate([x1, x2]), <br>                         &#39;y&#39;: np.concatenate([y1, y2]), <br>                         &#39;id&#39;: np.tile(np.arange(1, n_axis + 1), 2)})<br><br>step_2 = (step_1 + geom_line(data=axis_coords(p_data.shape[1] - 1), mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, group=&#39;id&#39;), alpha=0.3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DF9HtkHK3ajIzWwXm5d1zQ.png" /><figcaption>Addition of axes for each of the variables in the dataset. Image by Author</figcaption></figure><p>Now we can overlay the rescaled data points.</p><pre># Calculate the rescaled coordinates for each point<br><br>n_axis = len(p_data.columns) - 1  # Subtract 1 to exclude the group column<br><br>scaler = MinMaxScaler()<br><br>rescaled_data = p_data.copy()<br>rescaled_data.iloc[:, 1:] = scaler.fit_transform(rescaled_data.iloc[:, 1:])<br>rescaled_data[&#39;copy&#39;] = rescaled_data.iloc[:, 1]<br><br>melted_data = rescaled_data.melt(id_vars=[&#39;group&#39;], var_name=&#39;parameter&#39;, value_name=&#39;value&#39;, ignore_index=False)<br><br>melted_data[&#39;parameter&#39;] = pd.Categorical(melted_data[&#39;parameter&#39;], categories=np.array(rescaled_data.columns[1:]), ordered=True)<br>melted_data = melted_data.sort_values(by = [&#39;group&#39;, &#39;parameter&#39;])<br>melted_data[&#39;fi&#39;] = np.tile(np.linspace(0, 2 * np.pi, num=n_axis+1) + np.pi / 2, p_data.shape[0])<br>melted_data[&#39;x&#39;] = (melted_data[&#39;value&#39;] + central_distance)*np.cos(melted_data[&#39;fi&#39;])<br>melted_data[&#39;y&#39;] = (melted_data[&#39;value&#39;] + central_distance)*np.sin(melted_data[&#39;fi&#39;])<br><br>rescaled_coords_data = melted_data<br><br>step_3 = (step_2 +<br>geom_point(data=rescaled_coords_data, mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, group=&#39;group&#39;, color=&#39;group&#39;), size=3) +<br>        geom_path(data=rescaled_coords_data, mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, group=&#39;group&#39;, color=&#39;group&#39;), size=1) +<br>        geom_polygon(data=rescaled_coords_data, mapping=aes(&#39;x&#39;, &#39;y&#39;, group = &#39;group&#39;, color = &#39;group&#39;, fill = &#39;group&#39;), size = 1, alpha = 0.05, show_legend = False))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVAfC-_G-q8Rf-pbRyeMpg.png" /><figcaption>Overlaying the chart with the data points. Image by Author</figcaption></figure><p>The only thing left to do is to add the textual labels and names of the axes.</p><pre># Radius and corresponding feature value for each feature<br>text_data = pd.DataFrame({col: np.linspace(p_data[col].min(), p_data[col].max(), 5) <br>                          for col in p_data.columns if col != &#39;group&#39;})<br>text_data[&#39;r&#39;] = np.arange(0, 1.25, 0.25)<br>text_data = text_data.melt(id_vars=[&#39;r&#39;], var_name=&#39;parameter&#39;, value_name=&#39;value&#39;)<br>text_data[&#39;parameter&#39;] = pd.Categorical(text_data[&#39;parameter&#39;], categories=np.array(p_data.columns[1:]), ordered=True)<br>text_data = text_data.sort_values(by = [&#39;r&#39;, &#39;parameter&#39;])<br><br>def text_coords(r, n_axis=len(p_data.columns) - 1):<br>    fi = np.linspace(0, 2*np.pi*(1-1/n_axis), n_axis) + np.pi/2 + 0.01*2*np.pi/r<br>    x = r * np.cos(fi)<br>    y = r * np.sin(fi)<br>    return pd.DataFrame({&#39;x&#39;: x, &#39;y&#39;: y, &#39;r&#39;: r - central_distance})<br><br># Coordinates for the axis labels<br>labels_data = pd.concat([text_coords(r) for r in np.arange(0, 1.25, 0.25) + central_distance])<br><br># Combine with text_data<br>labels_data = pd.concat([labels_data.reset_index(drop=True), <br>                         text_data.drop(&#39;r&#39;, axis=1).reset_index(drop=True)], <br>                        axis=1)<br>                        <br>labels_data[&#39;value&#39;]=labels_data[&#39;value&#39;].round(2) <br><br>step_4 = (step_3 +<br>        geom_text(data=labels_data, mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, label=&#39;value&#39;), alpha=0.65, size=8, <br>         color=&#39;#303030&#39;) +<br>        geom_text(data=text_coords(1 + central_distance + axis_name_offset, p_data.shape[1] - 1),<br>         mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;), <br>         label=[param for param in p_data.columns[1:]],<br>         size=9) +<br>        labs(color=&#39;&#39;, title = &#39;Comparison of car properties&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKUfV4baeGntPDNtN3ErGQ.png" /><figcaption>Addition of axes names and labels. Image by Author</figcaption></figure><p>And some final aesthetic touches…</p><pre>#Final aesthetic touches<br>step_5 = (step_4 +<br>          labs(color=&#39;&#39;, title=&#39;Comparison of car properties&#39;) +<br>             theme(legend_position=&#39;bottom&#39;,<br>                   legend_text=element_text(size=7, face=&#39;bold&#39;),<br>                   legend_box_margin=0,<br>                   legend_margin=-20,<br>                   plot_title=element_text(size=10, margin={&#39;b&#39;: -30}, face=&#39;bold&#39;)) +<br>             lims(x=(-1.75, 1.75), y=(-1.5, 1.8)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WV5VtOzkgHzqC3_46qF9eA.png" /><figcaption>The final chart. Image by Author</figcaption></figure><p>Let’s just take a moment more to comment on the numbers displayed. Even froma regular spidr chart, it would be obvious that the Volvo is the slowest car by far. However, here we can also see the exact absolute difference — The Volvo took 18.6 seconds to cover a quarter of a mile, while the Maserati, the fastest of the three, took four whole seconds less. Of course, expectedly, this also means that the Volvo is most economical in terms of fuel consumption covering 6 more miles per gallon than the Maserati Bora. Being sports cars, both Maserati Bora and Ferrari Dino also feature more cylinders and hirsepowers and weigh more than the Volvo.</p><h3>Other examples</h3><p>Here is another example of a spider chart but using the Titanic dataset and a customized font.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlsJQvAcRz_qlSWLC5dOPA.png" /><figcaption>Anotehr example using the Titanic dataset. Image by Author</figcaption></figure><p>This chart clearly shows that the 1st class passengers were the oldest and the wealthiest of the three. The 3rd class passengers had the highest number of both male and female passengers and were the youngest group — probably mostly young people and families in search for better life abroad. However, the 1st class passengers had the highest survival rate, and the 3rd the lowest. This is probably partly due to the 1st class quarters being closer to the boat deck and partly due to the higher proportion of women in that class (since woman and children were rescued first).</p><h3>➕The Function</h3><p>As promised, here is the function wrapping all the above code. The first argument is the data frame fromatted so that the first column contains the group ids, and the other columns are group features to be plotted. The two additional arguments determine the radius of the inner empty polygon and the offset of axis titles from the chart.</p><pre># Wrapping the above code into an easy-to-use function<br>def multiaxis_radar(p_data, central_distance=0.2, axis_name_offset=0.2):<br>    def circle_coords(r, n_axis=len(p_data.columns) - 1):<br>        fi = np.linspace(0, 2*np.pi, n_axis+1) + np.pi/2<br>        x = r * np.cos(fi)<br>        y = r * np.sin(fi)<br>        return pd.DataFrame({&#39;x&#39;: x, &#39;y&#39;: y, &#39;r&#39;: r})<br><br>    circle_df = pd.concat([circle_coords(r) for r in np.arange(0, 1.25, 0.25) + central_distance])<br><br>    def axis_coords(n_axis):<br>        fi = np.linspace(0, 2*np.pi*(1-1/n_axis), n_axis) + np.pi/2<br>        x1 = central_distance * np.cos(fi)<br>        y1 = central_distance * np.sin(fi)<br>        x2 = (1 + central_distance) * np.cos(fi)<br>        y2 = (1 + central_distance) * np.sin(fi)<br>        return pd.DataFrame({&#39;x&#39;: np.concatenate([x1, x2]), <br>                             &#39;y&#39;: np.concatenate([y1, y2]), <br>                             &#39;id&#39;: np.tile(np.arange(1, n_axis + 1), 2)})<br><br>    n_axis = len(p_data.columns) - 1<br><br>    scaler = MinMaxScaler()<br>    rescaled_data = p_data.copy()<br>    rescaled_data.iloc[:, 1:] = scaler.fit_transform(rescaled_data.iloc[:, 1:])<br>    rescaled_data[&#39;copy&#39;] = rescaled_data.iloc[:, 1]<br><br>    melted_data = rescaled_data.melt(id_vars=[&#39;group&#39;], var_name=&#39;parameter&#39;, value_name=&#39;value&#39;, ignore_index=False)<br>    melted_data[&#39;parameter&#39;] = pd.Categorical(melted_data[&#39;parameter&#39;], categories=np.array(rescaled_data.columns[1:]), ordered=True)<br>    melted_data = melted_data.sort_values(by=[&#39;group&#39;, &#39;parameter&#39;])<br>    melted_data[&#39;fi&#39;] = np.tile(np.linspace(0, 2 * np.pi, num=n_axis+1) + np.pi / 2, p_data.shape[0])<br>    melted_data[&#39;x&#39;] = (melted_data[&#39;value&#39;] + central_distance)*np.cos(melted_data[&#39;fi&#39;])<br>    melted_data[&#39;y&#39;] = (melted_data[&#39;value&#39;] + central_distance)*np.sin(melted_data[&#39;fi&#39;])<br><br>    rescaled_coords_data = melted_data<br><br>    text_data = pd.DataFrame({col: np.linspace(p_data[col].min(), p_data[col].max(), 5) <br>                              for col in p_data.columns if col != &#39;group&#39;})<br>    text_data[&#39;r&#39;] = np.arange(0, 1.25, 0.25)<br>    text_data = text_data.melt(id_vars=[&#39;r&#39;], var_name=&#39;parameter&#39;, value_name=&#39;value&#39;)<br>    text_data[&#39;parameter&#39;] = pd.Categorical(text_data[&#39;parameter&#39;], categories=np.array(p_data.columns[1:]), ordered=True)<br>    text_data = text_data.sort_values(by=[&#39;r&#39;, &#39;parameter&#39;])<br><br>    def text_coords(r, n_axis=len(p_data.columns) - 1):<br>        fi = np.linspace(0, 2*np.pi*(1-1/n_axis), n_axis) + np.pi/2 + 0.01*2*np.pi/r<br>        x = r * np.cos(fi)<br>        y = r * np.sin(fi)<br>        return pd.DataFrame({&#39;x&#39;: x, &#39;y&#39;: y, &#39;r&#39;: r - central_distance})<br><br>    labels_data = pd.concat([text_coords(r) for r in np.arange(0, 1.25, 0.25) + central_distance])<br>    labels_data = pd.concat([labels_data.reset_index(drop=True), <br>                             text_data.drop(&#39;r&#39;, axis=1).reset_index(drop=True)], <br>                            axis=1)<br>    labels_data[&#39;value&#39;] = labels_data[&#39;value&#39;].round(2)<br><br>    plot = (ggplot(circle_df, aes(&#39;x&#39;, &#39;y&#39;)) +<br>            geom_polygon(data=circle_coords(1 + central_distance, p_data.shape[1] - 1), alpha=1, fill=&#39;beige&#39;) +<br>            geom_path(aes(group=&#39;r&#39;), linetype=&#39;dashed&#39;, alpha=0.5) +<br>            theme_void() +<br>            theme(legend_title=element_blank(),<br>            legend_direction=&#39;horizontal&#39;,<br>            legend_position=&#39;bottom&#39;,<br>            legend_box_spacing=0) +<br>            geom_line(data=axis_coords(p_data.shape[1] - 1), mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, group=&#39;id&#39;), alpha=0.3) +<br>            geom_point(data=rescaled_coords_data, mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, group=&#39;group&#39;, color=&#39;group&#39;), size=3) +<br>            geom_path(data=rescaled_coords_data, mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, group=&#39;group&#39;, color=&#39;group&#39;), size=1) +<br>            geom_polygon(data=rescaled_coords_data, mapping=aes(&#39;x&#39;, &#39;y&#39;, group=&#39;group&#39;, color=&#39;group&#39;, fill=&#39;group&#39;), size=1, alpha=0.05, show_legend=False) +<br>            geom_text(data=labels_data, mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;, label=&#39;value&#39;), alpha=0.65, size=8, <br>             color=&#39;#303030&#39;) +<br>            geom_text(data=text_coords(1 + central_distance + axis_name_offset, p_data.shape[1] - 1),<br>             mapping=aes(x=&#39;x&#39;, y=&#39;y&#39;), <br>             label=[param for param in p_data.columns[1:]],<br>             size=9) +<br>             labs(color=&#39;&#39;, title=&#39;Comparison of car properties&#39;) +<br>             theme(legend_position=&#39;bottom&#39;,<br>                   legend_text=element_text(size=7, face=&#39;bold&#39;),<br>                   legend_box_margin=0,<br>                   legend_margin=-20,<br>                   plot_title=element_text(size=10, margin={&#39;b&#39;: -30}, face=&#39;bold&#39;)) +<br>             lims(x=(-1.75, 1.75), y=(-1.5, 1.8)))<br><br>    return plot<br><br># Use the function to recreate the above plot<br>multiaxis_radar(p_data, central_distance=0.2, axis_name_offset=0.25)</pre><h3>🏁 The Conclusion</h3><p>This article shows how to construct an advanced multiaxis spider chart from scratch in Python. Although no Python package I know of currently supports this kind of chart, utilizing the layered grammar of graphics approach from the plotnine package provided me with the tools to create one myself. Of course, there is still room for progress, as the final function can be customized further by adding more arguments and options to control various aspects of the chart such as the line and backgorund color, font size, …, but I leave that to the reader for now 😉.</p><p>That’s all folks. I hope you found the article useful and will use it to make many more neat spider charts in the future. Enjoy!</p><h3>References</h3><p>[1] Henderson, H. V., &amp; Velleman, P. F. (1981). Building multiple regression models interactively. Biometrics, 37, 391–411.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbdb6c24a66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-make-an-advanced-spider-chart-in-python-adbdb6c24a66">How to Make an Advanced Spider Chart in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Alternative Approach to Visualizing Feature Relationships in Large Datasets]]></title>
            <link>https://medium.com/data-science/an-alternative-approach-to-visualizing-feature-relationships-in-large-datasets-925ab257d772?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/925ab257d772</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[progamming]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 18:04:14 GMT</pubDate>
            <atom:updated>2023-09-28T18:04:14.027Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to make those crowded scatterplots more informative</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ec9ZtGyVfPmHXu6Ns8qhnA.png" /><figcaption>Image by Author</figcaption></figure><p>The easiest way to understand relationships between data features is by visualizing them. In the case of numeric features, this usually means producing a scatterplot.</p><p>This is fine if the number of points is small, but for large datasets, the problem of overlapping observations appears. This can be partially mitigated for medium-sized datasets by making the points semi-transparent, but for very large datasets, even this doesn’t help.</p><p>What to do then? I will show you an alternative approach using the publicly available <a href="https://www.kaggle.com/datasets/maharshipandya/-spotify-tracks-dataset">Spotify dataset from Kaggle</a>.</p><p>The dataset contains audio features of 114000 Spotify tracks, such as danceability, tempo, duration, speechiness, … As an example for this post, I will examine the relationship between danceability and all other features.</p><p>Let’s first import the dataset and tidy it up a bit.</p><pre>#load the required packages<br>library(dplyr)<br>library(tidyr)<br>library(ggplot2)<br>library(ggthemes)<br>library(readr)<br>library(stringr)<br><br>#load and tidy the data<br>spotify &lt;- readr::read_csv(&#39;spotify_songs.csv&#39;) %&gt;% <br>  select(-1) %&gt;%<br>  mutate(duration_min = duration_ms/60000, <br>         track_genre = as.factor(track_genre)) %&gt;%<br>  mutate(across(c(2:4, 20), toupper)) %&gt;%<br>  relocate(duration_min, .before = duration_ms) %&gt;%<br>  select(-duration_ms)</pre><h3>❔The issue</h3><p>As I mentioned previously, the simplest way to visualize two-variable relationships is by drawing scatterplots with each point representing a single song. The first four columns contain track id information, so I left them out. I also renamed the features so that the first letter is uppercase and then reshape the data to prepare it for plotting.</p><pre>spotify %&gt;%<br>  select(5:19) %&gt;%<br>  mutate(across(everything(), as.numeric)) %&gt;%<br>  rename_with(str_to_title) %&gt;% #capitalize first letters of feature names<br>  rename(&quot;Duration (min)&quot; = Duration_min,<br>         &quot;Loudness (dB)&quot; = Loudness,<br>         &quot;Time Signature&quot; = Time_signature) %&gt;%<br>  pivot_longer(-Danceability, names_to = &quot;parameter&quot;, values_to = &quot;value&quot;) %&gt;%<br>  ggplot(aes(value, Danceability)) +<br>  geom_point(col = &quot;#00BFC4&quot;, alpha = 0.5) + #reduce point opacity with the alpha argument<br>  facet_wrap(~ parameter, scales = &quot;free_x&quot;) +<br>  labs(x = &quot;&quot;, y = &quot;Danceability&quot;) +<br>  theme_few() +<br>  theme(text = element_text(size = 20))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpLL9v8CoochN_83k4_wYA.png" /><figcaption>Image by Author</figcaption></figure><p>Even though a decreased point opacity was used (alpha = 0.5 as opposed to the default value of 1), the overlap is still too high. Although we can detect some general trends, the charts aren’t that informative since there are too many overlapping points.</p><p>We can try pushing this further by reducing the opacity to alpha = 0.05.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSsd3PyJDXcxCOp8c-ZKTA.png" /><figcaption>Image by Author</figcaption></figure><p>This improved things, and some might advocate that the chart is informative enough now. However, I disagree as I still have to focus too much to extract the trend and value distribution information.</p><h3>💡 The alternative</h3><p>We can see from the above scatterplots that the dataset contains both ordinal (Explicit, Mode, Key, Time Signature) and numeric features. In the case of categorical features, the simplifying solution is obvious — we can just use a summary plot such as a boxplot.</p><p>But what about the numeric ones? Well, the idea is to group the points into multiple equally wide bins, effectively turning them into ordinal features, and enabling the use of the approach described above.</p><p>Although boxplots are the most commonly used summary plots, I will also add violin plots in the background. This way, aside from summary stats of the binned points provided by the boxplot (median, interquartile range), we can also easily see the distribution of values within a specific binned range.</p><p>This powerful combo reduces chart clutter and enables much easier identification of trends.</p><p>Let’s try this out for the Acousticness-Danceability plot and then visualize all the features at once afterwards.</p><pre>#turn numeric features into ordinal by binning with the cut function<br>spotify_plot &lt;- spotify %&gt;%<br>  mutate(time_signature = as.numeric(as.character(time_signature))) %&gt;%<br>  mutate(across(-c(1:4, 7, 8, 10, 12, 19, 20), ~ cut(., breaks = 15))) %&gt;%<br>  mutate(across(c(7, 10, 12, 19), as.factor)) %&gt;% #turn thr existing ordinal variables to factors<br>  select(-c(1:4, 20)) #remove unnecessary track id columns<br><br>spotify_plot %&gt;%<br>    select(danceability, acousticness) %&gt;%<br>    ggplot(aes(acousticness, danceability)) +<br>    geom_violin(fill = &quot;#00BFC4&quot;, alpha = 0.5) +<br>    geom_boxplot() +<br>    labs(x = &quot;&quot;, y = &quot;Danceability&quot;) +<br>    theme_few() +<br>    theme(text = element_text(size = 20), <br>    #tilt the axis labels to prevent overlap<br>    axis.text.x = element_text(angle = -45, hjust = 0, vjust = 1)) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ec9ZtGyVfPmHXu6Ns8qhnA.png" /><figcaption><em>Image by Author</em></figcaption></figure><p>Much better! The decreasing trend in song danceability with an increase in acousticeness is now much more easily visible. We can also see that danceability is pretty normally distributed due to the addition of violin plots in the background, and the zero danceability outliers are identified by the boxplot function and thus plotted as separate points .</p><p>Let’s extrapolate our solution to all other features and create a complete feature relationship panel.</p><pre>spotify_plot %&gt;%<br>                   rename_with(str_to_title) %&gt;%<br>                   rename(&quot;Duration (min)&quot; = Duration_min,<br>                          &quot;Loudness (dB)&quot; = Loudness,<br>                          &quot;Time Signature&quot; = Time_signature) %&gt;%<br>                   pivot_longer(-Danceability, names_to = &quot;parameter&quot;, values_to = &quot;value&quot;) %&gt;%<br>                   arrange(parameter, value) %&gt;%<br>                   ggplot(aes(value, Danceability)) +<br>                   geom_violin(fill = &quot;#00BFC4&quot;, alpha = 0.5) +<br>                   geom_boxplot() +<br>                   facet_wrap(~ parameter, scales = &quot;free_x&quot;) +<br>                   labs(x = &quot;&quot;, y = &quot;Danceability&quot;) +<br>                   theme_few() +<br>                   theme(axis.text.x = element_blank(),<br>                         text = element_text(size = 20))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IqkUpyTR72utlJrJxF_zA.png" /><figcaption>Image by Author</figcaption></figure><p>Although we lost some detail compared to the original scatterplot panel, it is much easier to detect the underlying trends. Notice that, unlike with the single chart above, I removed the bin ranges on the x-axis in order to reduce clutter when visualizing all the features at once.</p><p>Considering these visualizations, the most impactful features should be Duration, Energy, Loudness, Tempo, Time Signature and Valence. Acousticness, Explicitness, Liveness, Popularity and Speechines show some effect, but not as much as the formerly mentioned ones. There seems to be no strong effect of Key, Instrumentalness and Mode features on the danceability rating.</p><h3>🗒️Conclusion</h3><p>That’s all for this post. I’ve shown how to bypass the clutter of overlapping points when analyzing large datasets. I hope you will find the proposed solution useful whenever you encounter large datasets and wish to easily identify the trends in the feature relationships. If you have any comments, questions, suggestions, or requests for other custom plots, please let me know in the comments.</p><p>And, of course if you liked the post, follow me for more similar content😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=925ab257d772" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-alternative-approach-to-visualizing-feature-relationships-in-large-datasets-925ab257d772">An Alternative Approach to Visualizing Feature Relationships in Large Datasets</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spider and Parallel Charts in R with the ggvanced Package]]></title>
            <link>https://medium.com/data-science/ggvanced-a-package-for-generating-advanced-data-visualizations-on-top-of-the-ggplot2-package-2a935763a4b?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a935763a4b</guid>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 14:10:30 GMT</pubDate>
            <atom:updated>2023-06-20T16:42:51.656Z</atom:updated>
            <content:encoded><![CDATA[<h4>An R package for effective visualization of multiple variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*4LZteqAKyLzmqJdRpzT4VA.png" /><figcaption>A pretty spider chart. Image by Author.</figcaption></figure><h3>Motivation</h3><p>During one of my data analysis projects, I found myself in need of an effective way to compare groups across several variables at once. Of course, bar charts came to mind first, but I wanted something more eye-catching, something more interesting. After browsing the web a bit, I settled on two prime candidates — a spider chart and a parallel chart.</p><p>After this, I usually just find a dedicated R package producing the needed visualizations, but this time, this approach left me empty-handed.</p><p>A LIE — more experienced R users might say! Such visualizations can already be obtained using packages such as fsmb and ggradar for radar charts and ggally for parallel plots.</p><p>However, aside from just performing the ranked comparison of groups across variables, I also wanted to simultaneously display the range of values for each variable. And, you guess it, none of the aforementioned packages offered this. So, I decided to build my own :)</p><h3>The ggvanced package</h3><p>ggvanced is an R package for creating advanced multivariable plots such as spider/radar charts and parallel plots. The visualizations are created on top of the ggplot2 package. The beauty of the ggplot2 package is the underlying grammar of graphics, allowing for creation of graphs by stacking multiple layers on top of one another. This powerful concept lets us create essentially any visualization, as long as we know how to code it.</p><figure><img alt="A schamatic depiction of how ggplot2 charts are made. Image by
Zvonimir Boban." src="https://cdn-images-1.medium.com/proxy/1*vx_6huki18dHAnSnPWlCYQ.png" /><figcaption>Creating visualizations using the grammar of graphics approach. Image by Author.</figcaption></figure><p>The package is currently <a href="https://github.com/Ringomed/ggvanced">available on GitHub</a> and can be installed by typing the devtools::install_github(&quot;Ringomed/ggvanced&quot;) command in R and calling library(ggvanced) afterwards.</p><p>If you are interested in the details of chart construction, in a recent post I showed the logic behind constructing a spider chart from scratch, so check out the story below or the detailed documentation on GitHub.</p><p><a href="https://towardsdatascience.com/how-to-make-a-spider-chart-in-r-using-ggplot2-85a4f1898cab">How to Make a Spider Chart in R Using ggplot2</a></p><p>For the rest of you, below are some examples detailing what the package functions can do.</p><h3>Spider charts with ggspider()</h3><p>The ggspider() function creates spider charts which either a single shared axis scaled to a [0,1] range, or a separate axis with real values displayed for every displayed category. Let’s test the function on a couple of examples. First, we have to format the data so that the first column contains the group identifier, and other columns the descriptory variables. We will use the built-in mtcars and iris datasets.</p><pre>library(tidyverse)<br><br>mtcars_summary &lt;- mtcars %&gt;% <br>  tibble::rownames_to_column(var = &quot;group&quot;) %&gt;%  <br>  tibble::as_tibble() %&gt;% <br>  tail(3)<br><br>iris_summary &lt;- iris %&gt;% <br>  dplyr::group_by(Species) %&gt;% <br>  dplyr::summarise(across(everything(), mean))<br>library(ggvanced)</pre><h4>Comparing car properties</h4><pre>ggspider(mtcars_summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*EwTsGEODBtOt6S9b.png" /><figcaption>Image by Author.</figcaption></figure><p>The key differences between the cars immediately stand out. As expected, compared to racing cars such as the Ferrari and Maserati, the Volvo has much less horsepowers (hp) and takes much longer to cover a quarter of a mile (qsec), but is also much more economical in terms of miles per gallon (mpg).</p><h4>Visualizing differences bettween the Iris species</h4><pre>ggspider(iris_summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*SJ2OA2M2177yEZH6.png" /><figcaption>Image by Author.</figcaption></figure><p>Just like with the cars example, the spider chart is very effective for determining the differences between the iris species. We can immediately see that the Versicolor and Virginica species are much more similar, having essentailly the same ratios of petal and sepal lengths and widths and only differing in the total flower size. Conversely, the Setosa species has a much larger sepal width.</p><h4>Radar charts</h4><p>The function also allows for creation of traditional radar charts with a single common scaled axis by specifying the argument scaled = TRUE and switching to a round shape using polygon = FALSE.</p><pre>ggspider(iris_summary, scaled = TRUE, polygon = FALSE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*_oNUK-teIgO0S5coCP2bvQ.png" /></figure><p>The other function arguments are more aesthetic in nature, and cover aspects such as font size, position of the labels and so on. For more details, refer to the function documentation.</p><h3>Parallel charts with ggparallel()</h3><p>Although I prefer spider charts from an aesthetic viewpoint, parallel charts can make it easier to spot trends across variables. This is especially true when there are many variables or observations in the dataset.</p><pre>ggparallel(mtcars_summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*H3JQGTGnr9L8C-ZA.png" /><figcaption>Image by Author.</figcaption></figure><pre>ggparallel(iris_summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*UpPCWMbD0RB2agt-.png" /><figcaption>Image by Author.</figcaption></figure><h3>Playing with the aestehtics</h3><p>The above charts are just barebone version. Of course, they can be “pimped up” just like any other ggplot2 chart. Below is an example of a ggvanced spider chart after a couple of alterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*4LZteqAKyLzmqJdRpzT4VA.png" /><figcaption>Image by Author.</figcaption></figure><p>And of course, the accompanying code. Enjoy! :)</p><pre>library(tidyverse)<br>library(ggvanced)<br>library(sysfonts)<br>library(showtext)<br><br>sysfonts::font_add_google(&quot;Roboto Condensed&quot;)<br>showtext_auto()<br><br>mtcars_gr &lt;- mtcars %&gt;%<br>  tibble::rownames_to_column(var = &quot;group&quot;) %&gt;%<br>  tibble::as_tibble() %&gt;%<br>  tail(3) %&gt;%<br>  rename(&quot;Miles per Gallon&quot; = mpg, &quot;Cylinders&quot; = cyl,<br>         &quot;Displacement&quot; = disp, &quot;Horsepower&quot; = hp,<br>         &quot;Rear axle\n ratio&quot; = drat, &quot;Weight&quot; = wt) %&gt;%<br>  dplyr::select(1:7)<br><br>ggspider(mtcars_gr, axis_name_offset = 0.15, background_color = &quot;beige&quot;, fill_opacity = 0.15) +<br>  labs(col = &quot;Car name&quot;, title = &quot;Comparing Car Properties&quot;) +<br>  theme(plot.title = element_text(hjust = 0.475, face = &quot;bold&quot;),<br>        legend.title = element_text(face = &quot;bold&quot;),<br>        text = element_text(family = &quot;Roboto Condensed&quot;, face = &quot;bold&quot;))</pre><h3>Conclusion</h3><p>In this post, I covered key functions and options of ggvanced — a package I made in response to a need for more advanced spider and parallel charts in R.</p><p>The text goes through a couple of examples for each function and then show how the final result can look like after some additional customization.</p><p>I hope that the package will be useful to you as it is to me. If you have requests for any more custom visualizations to be implemented in R, please drop a comment, and I will do my best to create a separate function for it. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a935763a4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ggvanced-a-package-for-generating-advanced-data-visualizations-on-top-of-the-ggplot2-package-2a935763a4b">Spider and Parallel Charts in R with the ggvanced Package</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Is It Wrong to Use Bar Charts?]]></title>
            <link>https://medium.com/data-science/when-is-it-wrong-to-use-bar-charts-70f55a3fb1a2?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/70f55a3fb1a2</guid>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Wed, 31 May 2023 03:52:01 GMT</pubDate>
            <atom:updated>2023-06-21T23:53:06.576Z</atom:updated>
            <content:encoded><![CDATA[<h4>…and possible ways to fix it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GNIMwtKxgTVPazh8Q17iA.png" /><figcaption>Image generated by Canva text to image tool</figcaption></figure><p>Don’t get me wrong, bar charts can be a great tool for data visualization, especially when used for displaying counts, totals or proportions. However, using them in the wrong way can lead to unintentional (or even worse, intentional) data misinterpretation. The particular issue I will be talking about today is using bar charts to present aggregated summary statistics such as means or medians.</p><p>The biggest problem here is the loss of detail as bar charts can oversimplify, leaving out important information such as variance, distribution, outliers, and trends. In this post I will illustrate this problem using a series of examples and propose potential solutions. In order to not interfere with the flow of the post, the code for the charts will be specified at the end for those who are interested :)</p><h4>The wine quality dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irOPNanOFdd0gw-QAhZQiA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kymellis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kym Ellis</a> on <a href="https://unsplash.com/s/photos/wine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>For this post, I will be using the wine quality dataset¹, available through the <a href="https://archive.ics.uci.edu/ml/datasets/wine+quality">UCI ML repository</a>. Although the dataset contains many wine properties, we will focus on the total sulfur dioxide measurements.</p><p>Sulfur, commonly added to wine as sulfur dioxide, plays a crucial role in winemaking due to its preservative qualities. Acting as an antioxidant, it helps prevent the wine’s oxidation, safeguarding it from discoloration and undesired flavor alterations. Its antimicrobial characteristics also protect the wine against spoilage from bacteria and yeasts, preserving the intended taste and quality.</p><h3>The problem</h3><p>Let’s illustrate the issue by plotting a simple bar chart comparing total sulfur dioxide levels between red and white wines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjhmJc7eCoPawTZpzOx0Sw.png" /><figcaption>Image by Author</figcaption></figure><p>Ok, maybe it isn’t fair to bash on bar charts using the above example since the basic chart looks so ugly, it is off-putting without any further argument needed. Let’s first make it a bit prettier by tweaking some aesthetic properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRk-IeURus_SZnIAc-km7Q.png" /><figcaption>Image by Author</figcaption></figure><p>Much better. Now, back to the issue a hand. What does the chart tell us? Well, obviously, the sulfur levels seem to be much higher for white wines. This was to be expected due to the differences in the winemaking process between red and white wines.</p><p>Red wines are fermented with their skins, providing natural antioxidants that help protect the wine from oxidation. In contrast, white wines are typically made by pressing the grapes and removing the skins prior to fermentation. This leaves them more susceptible to oxidation, requiring additional protection in the form of sulfur dioxide.</p><p>Although the average effect is discernible, the bar chart gives us no information about the distribution of values in each group, or the number of observations per each group.</p><p>This can partially be addressed by adding the number of observations above the bars and adding errorbars to show the standard deviations of each group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWpswxiaC2Z3mC79zPMm7A.png" /><figcaption>Image by Author</figcaption></figure><p>This can be enough if the underlying distribution of values is symmetrical, but that doesn’t have to be the case, making standard deviation a poor choice as a dispersion statistic. Nothing more can be added to bar charts to fix this without making it closer to a completely different type of chart. This indicates that bar charts are not ideal for presenting this type of data.</p><p>So, what are the possible alternatives? I’ll go through a couple in the remainder of the post.</p><h3>The fix</h3><p>Here I offer four possible alternatives I think are a better and more transparent solution.</p><h4>1. Jittered points</h4><p>The first possibility is to add the actual individual observations to the chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dOaJm82Isf6CKUQ_z0RXg.png" /><figcaption>Image by Author</figcaption></figure><p>This can be a great alternative if the number of observations is relatively small. However, in this specific case, it feels quite cumbersome by itself due to a very large number of wines in the dataset.</p><h4>2. Boxplots with specified means</h4><p>The second alternative is using boxplots with an added twist of specifying the means as well as medians (which are displayed by a flat line in the central box by default). Although boxplots give us an idea of the underlying distribution by specifying quartiles, I like the additional information which the mean offers. This is because a large and easily visible difference between the mean and the median immediately tells us whether the distribution is skewed and in which direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gPN8Jxrhe62Ph0yjNT4gw.png" /><figcaption>Image by Author</figcaption></figure><h4>3. Violin plots with medians</h4><p>Violin plots are great because they let us in on the shape of the underlying distributions, making it possible to easily detect anomalies such as bimodalities or data skewness. One might argue that boxplots do this implicitly as well. Although I agree to a certain point, we also have to take into account that a person has to be taught how to read a boxplot, whereas that’s not the case with violin plots.</p><p>I also like to add the information on the median since the violins leave a lot of unused space, so why not :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2cZpP8hzn-ujEzjOvjlkw.png" /><figcaption>Image by Author</figcaption></figure><h4>4. Violin plots with jittered points</h4><p>Ok, this one isn’t really a standalone option, but rather a combination of options 1 and 3. For our specific case, this would be my pick, but that doesn’t mean it would be ideal for all possible scenarios, as that depends on specifics of the problem such as the number of groups for comparison, total number of points, group dispersions, …</p><p>Notice that I didn’t try to combine boxplots with specific points. This is intentional, as I feel that such a combination would defeat the purpose of the boxplot. Namely, the boxplot charts display specific points only if they are 1.5 interquartile ranges above the upper border of the central box. This can be used as a simple method for outlier detection, and would be obscured by adding too many other points as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BhkwXLtPPq_U8YcFyPQpg.png" /><figcaption>Image by Author</figcaption></figure><h3>Conclusion</h3><p>This post talks about a specific issue of using bar charts to present aggregate group statistics using a wine quality dataset to provide hand-on examples. After illustrating the issue, four possible alternatives are presented and their advantages and disadvantages are discussed.</p><p>Finally, remember, the primary goal of any data visualization is to accurately and effectively convey information. Always choose the type of visualization that best suits the data and the message you want to communicate.</p><p>I hope you will find the post useful. If you have any comments, feel free to leave a reply to the post. And, of course, if you liked what you read, please clap and follow me for more similar content.</p><h4>Footnotes</h4><p>¹P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.<br>Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547–553, 2009. (CC BY 4.0)</p><h4>Code for generating the charts</h4><pre>library(tidyverse)<br><br>wine &lt;- read_delim(&quot;winequality-red.csv&quot;, <br>                    delim = &quot;;&quot;, escape_double = FALSE, trim_ws = TRUE) %&gt;%<br>  mutate(Type = &quot;Red&quot;) %&gt;%<br>  bind_rows(read_delim(&quot;winequality-white.csv&quot;, <br>                        delim = &quot;;&quot;, escape_double = FALSE, trim_ws = TRUE) %&gt;%<br>              mutate(Type = &quot;White&quot;)) %&gt;%<br>  mutate(Type = factor(Type)) %&gt;%<br>  pivot_longer(`fixed acidity`:`quality`, <br>                names_to = &quot;Parameter&quot;, values_to = &quot;Value&quot;) %&gt;%<br>  filter(Parameter == &quot;total sulfur dioxide&quot;) %&gt;%<br>  select(-Parameter)<br><br>wine_summary &lt;- wine %&gt;%<br>  group_by(Type) %&gt;%<br>  summarise(Median = median(Value), Mean = mean(Value), <br>            SD = sd(Value), N = n())<br>#basic bar chart<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Mean)) +<br>  geom_col() +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;)<br><br>#aesthetically pleasing bar chart<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Mean)) +<br>  geom_col(aes(fill = Type), width = 0.8) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  scale_fill_manual(values = c(&quot;#b11226&quot;, &quot;#F4E076&quot;)) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  theme_bw() +<br>  theme(legend.position = &quot;none&quot;)<br><br>#bar chart with errorbars and specified number of observations per group<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Mean)) +<br>  geom_col(aes(fill = Type), width = 0.8) +<br>  geom_errorbar(aes(ymin = Mean - SD, ymax = Mean + SD), width = 0.15) +<br>  geom_label(aes(y = 200, label = N), fill = &quot;gray97&quot;) +<br>  scale_fill_manual(values = c(&quot;#b11226&quot;, &quot;#F4E076&quot;)) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  theme_bw() +<br>  theme(legend.position = &quot;none&quot;)<br><br>#jittered points chart<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Mean)) +<br>  geom_jitter(data = wine, aes(x = Type, y = Value, col = Type), alpha = 0.4) +<br>  geom_errorbar(aes(ymin = Mean - SD, ymax = Mean + SD), width = 0.15) +<br>  geom_point(shape = 4, size = 2, stroke = 2) +<br>  geom_label(aes(y = 450, label = N), fill = &quot;gray97&quot;) +<br>  scale_color_manual(values = c(&quot;#b11226&quot;, &quot;#F4E076&quot;)) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  theme_bw() +<br>  theme(legend.position = &quot;none&quot;)<br><br>#boxplot with added information about the mean<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Mean)) +<br>  geom_boxplot(data = wine, aes(x = Type, y = Value, col = Type)) +<br>  geom_point(shape = 4, size = 2, stroke = 2) +<br>  geom_label(aes(y = 450, label = N), fill = &quot;gray97&quot;) +<br>  scale_color_manual(values = c(&quot;#b11226&quot;, &quot;#F4E076&quot;)) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  theme_bw() +<br>  theme(legend.position = &quot;none&quot;)<br><br>#violin plot with information about the median<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Median)) +<br>  geom_violin(data = wine, aes(x = Type, y = Value, col = Type)) +<br>  geom_point(shape = 4, size = 2, stroke = 2) +<br>  geom_label(aes(y = 450, label = N), fill = &quot;gray97&quot;) +<br>  scale_color_manual(values = c(&quot;#b11226&quot;, &quot;#F4E076&quot;)) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  theme_bw() +<br>  theme(legend.position = &quot;none&quot;)<br><br>#violin plot with added jittered points<br>wine_summary %&gt;%<br>  ggplot(aes(Type, Median)) +<br>  geom_violin(data = wine, aes(x = Type, y = Value), fill = &quot;gray92&quot;) +<br>  geom_jitter(data = wine, aes(x = Type, y = Value, col = Type), alpha = 0.1) +<br>  geom_point(shape = 4, size = 2, stroke = 2) +<br>  geom_label(aes(y = 450, label = N), fill = &quot;gray97&quot;) +<br>  scale_color_manual(values = c(&quot;#b11226&quot;, &quot;#F4E076&quot;)) +<br>  labs(x = &quot;Wine type&quot;, y = &quot;Total sulfur levels&quot;) +<br>  theme_bw() +<br>  theme(legend.position = &quot;none&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70f55a3fb1a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/when-is-it-wrong-to-use-bar-charts-70f55a3fb1a2">When Is It Wrong to Use Bar Charts?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tabyl — a frequency table for the modern R user]]></title>
            <link>https://medium.com/data-science/tabyl-a-frequency-table-for-the-modern-r-user-e061cd48baef?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e061cd48baef</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dplyr]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Sat, 20 May 2023 13:14:31 GMT</pubDate>
            <atom:updated>2023-05-20T15:04:58.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tabyl: A Frequency Table for the Modern R User</h3><h4>Out with the old, in with the new!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*9YsNMVd4lDiWQDUg7qHLNQ.png" /><figcaption>Image created using Canva Image Generator</figcaption></figure><p>Anyone who has worked with categorical data eventually came across a need to calculate the absolute number and proportion of a certain class. This article introduces the tabyl function for creating frequency tables through a series of hands-on examples.</p><h4>What does tabyl bring to the table (no pun intended :D)?</h4><p>The tabyl function is a feature of the janitor package in R. It’s a very convenient tool for creating contingency tables, otherwise known as frequency tables or cross-tabulations. Here are some of the benefits of using tabyl:</p><p>1. Easy syntax: tabyl has an easy-to-use syntax. It can take one, two, or three variables, and it automatically returns a data frame that includes counts and proportions.</p><p>2. Flexibility: tabyl can generate one-way (single variable), two-way (two variables), and three-way (three variables) contingency tables. This flexibility makes it suitable for a wide range of applications.</p><p>3. Automatic calculation of proportions: tabyl automatically calculates the proportions (percentages) for one-way contingency tables. For two and three-way tables, the same result can be accomplished in combination with the adorn_percentages function from the same package.</p><p>4. Compatibility with dplyr: The output of tabyl is a data frame (or tibble), which makes it fully compatible with dply functions and the tidyverse ecosystem. This means you can easily pipe %&gt;% the output into further data wrangling or visualization functions.</p><p>5. Neat and informative output: tabyl provides neat and informative output, which includes the variable names as row names and column names, making it easier to interpret the results.</p><p>For all these reasons, tabyl is a great choice when you want to create frequency tables in R. It simplifies many steps and integrates well with the tidyverse approach to data analysis.</p><h4>The dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GihDecsnhidJp96SAnPrQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hans_veth?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hans Veth</a> on <a href="https://unsplash.com/s/photos/mushroom?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This post will demonstrate the benefits of the tabyl function from the janitor package using the data on the edibility of different types of mushrooms depending on their odor. Here, I will be using a tidied dataset under the name mushrooms, but you can access the <a href="https://www.kaggle.com/datasets/uciml/mushroom-classification?resource=download">original data</a> on Kaggle. Below is the code used for cleaning the data.</p><pre>library(tidyverse)<br>library(janitor)<br><br>mushrooms &lt;- read_csv(&quot;mushrooms.csv&quot;) %&gt;%<br>  select(class, odor) %&gt;%<br>  mutate(<br>    class = case_when(<br>      class == &quot;p&quot; ~ &quot;poisonous&quot;,<br>      class == &quot;e&quot; ~ &quot;edible&quot;<br>    ),<br>    odor = case_when(<br>      odor == &quot;a&quot; ~ &quot;almond&quot;,<br>      odor == &quot;l&quot; ~ &quot;anise&quot;,<br>      odor == &quot;c&quot; ~ &quot;creosote&quot;,<br>      odor == &quot;y&quot; ~ &quot;fishy&quot;,<br>      odor == &quot;f&quot; ~ &quot;foul&quot;,<br>      odor == &quot;m&quot; ~ &quot;musty&quot;,<br>      odor == &quot;n&quot; ~ &quot;none&quot;,<br>      odor == &quot;p&quot; ~ &quot;pungent&quot;,<br>      odor == &quot;s&quot; ~ &quot;spicy&quot;<br>    )<br>  )</pre><p>If you are unfamiliar with the above syntax, please check out a hands-on guide to using the tidyverse in one of my earlier articles.</p><p><a href="https://towardsdatascience.com/diving-into-the-tidyverse-using-the-titanic-data-83f54295d5df">Diving into the tidyverse using the Titanic data</a></p><h4>The old</h4><p>In order to better understand which advantages tabyl offers, let’s first make a frequency table using the base R table function.</p><pre>table(mushrooms$class)<br><br>   edible poisonous <br>     4208      3916 </pre><pre>table(mushrooms$odor, mushrooms$class)<br><br>            edible poisonous<br>  almond      400         0<br>  anise       400         0<br>  creosote      0       192<br>  fishy         0       576<br>  foul          0      2160<br>  musty         0        36<br>  none       3408       120<br>  pungent       0       256<br>  spicy         0       576</pre><p>Unsurprisingly, it turns out that odor is a great predictor of mushroom edibility, with anything “funny-smelling” probably being poisonous. Thank you evolution! Also, there seem to be many more poisonous mushrooms, so it’s always important to be cautious when picking mushrooms on your own.</p><p>If we want to be able to use the variable names directly without specifying the $ operator, we would need to use the with command to make the dataset available to the table function.</p><pre>mush_table &lt;- with(mushrooms, table(odor, class))</pre><p>Unfortunately, if we want to upgrade to proportions instead of absolute numbers, we can not use the same function but another one instead — prop.table .</p><pre>prop.table(mush_table)<br><br>class<br>odor            edible   poisonous<br>  almond   0.049236829 0.000000000<br>  anise    0.049236829 0.000000000<br>  creosote 0.000000000 0.023633678<br>  fishy    0.000000000 0.070901034<br>  foul     0.000000000 0.265878877<br>  musty    0.000000000 0.004431315<br>  none     0.419497784 0.014771049<br>  pungent  0.000000000 0.031511571<br>  spicy    0.000000000 0.070901034</pre><p>By default, this gives us a column-wise proportion table. If we want row-wise proportions, we can specify the margin argument (1 for row-wise and 2 for column-wise).</p><pre>prop.table(mush_table, margin = 1)<br><br>class<br>odor           edible  poisonous<br>  almond   1.00000000 0.00000000<br>  anise    1.00000000 0.00000000<br>  creosote 0.00000000 1.00000000<br>  fishy    0.00000000 1.00000000<br>  foul     0.00000000 1.00000000<br>  musty    0.00000000 1.00000000<br>  none     0.96598639 0.03401361<br>  pungent  0.00000000 1.00000000<br>  spicy    0.00000000 1.00000000</pre><p>All these special functions can feel cumbersome and hard to remember, so a single function which contains all the above funcionality would be nice to have.</p><p>Additionally, if we check the type of the created object using the class(mush_table) command, we see that it is of a class table.</p><p>This creates a compatibility problem, since nowadays R users are mostly using the tidyverse ecosystem which is centered around applying functions to data.frame type objects and stringing the results together using the pipe (%&gt;%) operator.</p><h4>The new</h4><p>Let’s do the same things with the tabyl function.</p><pre>tabyl(mushrooms, class)<br><br>     class    n   percent<br>    edible 4208 0.5179714<br> poisonous 3916 0.4820286</pre><pre>mush_tabyl &lt;- tabyl(mushrooms, odor, class)<br>mush_tabyl<br><br>     odor edible poisonous<br>   almond    400         0<br>    anise    400         0<br> creosote      0       192<br>    fishy      0       576<br>     foul      0      2160<br>    musty      0        36<br>     none   3408       120<br>  pungent      0       256<br>    spicy      0       576</pre><p>Compared to the corresponding table output, the resulting tables aretidier using the tabyl function, with variable names (class) being explicitly stated. Moreover, for the one-way table, aside from numbers, the percentages are automatically generated as well.</p><p>We can also notice that we didn’t have to use the which functio to be able to specify the variable names directly. Additionally, running class(mush_tabyl) tells us that the resulting object is of a data.frame class which ensures tidyverse compatibility!</p><h4>The adorned janitor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*NAOieK3aqP2B9Pp_IItN3g.png" /><figcaption>Image created using Canva Image Generator</figcaption></figure><p>For additional tabyl functionalities, the janitor package also contains a series of adorn functions. To get the percentages, we simply pipe the resulting frequency table to the adorn_percentages function.</p><pre>mush_tabyl %&gt;% adorn_percentages()<br><br>odor    edible  poisonous<br>   almond 1.0000000 0.00000000<br>    anise 1.0000000 0.00000000<br> creosote 0.0000000 1.00000000<br>    fishy 0.0000000 1.00000000<br>     foul 0.0000000 1.00000000<br>    musty 0.0000000 1.00000000<br>     none 0.9659864 0.03401361<br>  pungent 0.0000000 1.00000000<br>    spicy 0.0000000 1.00000000</pre><p>If we want the column-wise percentages, we can specify the denominator argument as “col”.</p><pre>mush_tabyl %&gt;% adorn_percentages(denominator = &quot;col&quot;)<br><br>     odor     edible   poisonous<br>   almond 0.09505703 0.000000000<br>    anise 0.09505703 0.000000000<br> creosote 0.00000000 0.049029622<br>    fishy 0.00000000 0.147088866<br>     foul 0.00000000 0.551583248<br>    musty 0.00000000 0.009193054<br>     none 0.80988593 0.030643514<br>  pungent 0.00000000 0.065372829<br>    spicy 0.00000000 0.147088866</pre><p>The tabyl — adorn combo even enables us to easily combine both the number and percentage in a same table cell…</p><pre>mush_tabyl %&gt;% adorn_percentages %&gt;% adorn_ns<br><br>     odor           edible         poisonous<br>   almond 1.0000000  (400) 0.00000000    (0)<br>    anise 1.0000000  (400) 0.00000000    (0)<br> creosote 0.0000000    (0) 1.00000000  (192)<br>    fishy 0.0000000    (0) 1.00000000  (576)<br>     foul 0.0000000    (0) 1.00000000 (2160)<br>    musty 0.0000000    (0) 1.00000000   (36)<br>     none 0.9659864 (3408) 0.03401361  (120)<br>  pungent 0.0000000    (0) 1.00000000  (256)<br>    spicy 0.0000000    (0) 1.00000000  (576)</pre><p>… or add the totals to the rows and columns.</p><pre>mush_tabyl %&gt;% adorn_totals(c(&quot;row&quot;, &quot;col&quot;))<br><br>odor edible poisonous Total<br>   almond    400         0   400<br>    anise    400         0   400<br> creosote      0       192   192<br>    fishy      0       576   576<br>     foul      0      2160  2160<br>    musty      0        36    36<br>     none   3408       120  3528<br>  pungent      0       256   256<br>    spicy      0       576   576<br>    Total   4208      3916  8124</pre><h4>Conclusion</h4><p>The tabyl() function from the janitor package in R offers a user-friendly and flexible solution for creating one-way, two-way, or three-way contingency tables. It excels in automatically computing proportions and producing tidy data frames that integrate seamlessly with the tidyverse ecosystem, especially dplyr. Its outputs are well-structured and easy to interpret, and it can be further enhanced with adorn functions, simplifying the overall process of generating informative frequency tables. This makes tabyl() a highly beneficial tool in data analysis in R.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e061cd48baef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tabyl-a-frequency-table-for-the-modern-r-user-e061cd48baef">Tabyl — a frequency table for the modern R user</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make a Spider Chart in R Using ggplot2]]></title>
            <link>https://medium.com/data-science/how-to-make-a-spider-chart-in-r-using-ggplot2-85a4f1898cab?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/85a4f1898cab</guid>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 15:52:11 GMT</pubDate>
            <atom:updated>2023-08-02T12:35:10.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step construction of a spider/radar chart</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pq6gbSZ9a79-bXltsZMnaA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lincon_street?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Divyadarshi Acharya</a> on <a href="https://unsplash.com/photos/Qbs6liSxjr8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Knowing that a radar chart can make for a compelling visualization, I tried finding a suitable R library. I was surprised when my search yielded practically no results <strong>(EDIT: Shortly after writing this post, I created the </strong><strong>ggvanced package with the </strong><strong>ggspider function dealing with this issue. You can read more about it in a </strong><a href="https://medium.com/towards-data-science/ggvanced-a-package-for-generating-advanced-data-visualizations-on-top-of-the-ggplot2-package-2a935763a4b"><strong>separate post</strong></a><strong>).</strong> The only package I found was ggradar which is not on CRAN, but can only be installed from GitHub.</p><p>I decided to give it a try using the data on the Titanic crash from the titanic package. In order to calculate the data summaries I wanted and get the data to the shape needed for plotting, I used the dplyr , tidyr, tibble, purr and scales packages. If you are unfamiliar with these, check out my earlier article on data wrangling with R.</p><p><a href="https://towardsdatascience.com/diving-into-the-tidyverse-using-the-titanic-data-83f54295d5df">Diving into the tidyverse using the Titanic data</a></p><pre>library(dplyr)<br>library(tidyr)<br>library(tibble)<br>library(purrr)<br><br><br>Titanic &lt;- titanic_train<br><br>Titanic_gr1 &lt;-<br>  Titanic %&gt;%<br>  select(Survived:Fare) %&gt;%<br>  group_by(Pclass) %&gt;%<br>  summarise(across(c(Age, Fare), mean, na.rm = TRUE))<br><br>Titanic_gr2 &lt;-<br>  Titanic %&gt;%<br>  select(Survived:Fare) %&gt;%<br>  group_by(Pclass, Survived) %&gt;%<br>  summarise(N = n()) %&gt;%<br>  pivot_wider(names_from = Survived, values_from = N) %&gt;%<br>  mutate(&quot;Survived (%)&quot; = `1`/(`0` + `1`)) %&gt;%<br>  select(1,4)<br><br>Titanic_gr3 &lt;-<br>  Titanic %&gt;%<br>  select(Survived:Fare) %&gt;%<br>  group_by(Pclass, Sex) %&gt;%<br>  summarise(N = n()) %&gt;%<br>  pivot_wider(names_from = Sex, values_from = N)<br><br>Titanic_gr &lt;- reduce(list(Titanic_gr1, <br>                          Titanic_gr2, <br>                          Titanic_gr3), left_join) %&gt;%<br>  rename(Male = &quot;male&quot;, Female = &quot;female&quot;)</pre><pre>Titanic_gr<br><br># A tibble: 3 × 6<br>  Pclass   Age  Fare `Survived (%)` Female  Male<br>   &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt;          &lt;dbl&gt;  &lt;int&gt; &lt;int&gt;<br>1      1  38.2  84.2          0.630     94   122<br>2      2  29.9  20.7          0.473     76   108<br>3      3  25.1  13.7          0.242    144   347</pre><p>After installing and loading the ggradarpackage and rescaling the data to a (0, 1) interval, we can create the radar chart by invoking the ggradar function.</p><pre>library(ggplot2)<br>library(scales)<br>library(devtools)<br>install_github(&quot;ricardo-bion/ggradar&quot;, dependencies=TRUE)<br>library(ggradar)<br><br>Titanic_gr %&gt;%<br>  mutate(across(-Pclass, normiranje)) %&gt;%<br>  ggradar(legend.title = &quot;Passenger class&quot;) +<br>  theme(legend.position = &quot;bottom&quot;, legend.title = element_text(size = 17))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*iKjBPVP-DPU0ake9gdL0Kg.png" /><figcaption>A radar chart made using the ggradar package. Image by Author</figcaption></figure><p>Even though the obtained chart was neat and visually appealing, I wanted to have separate axis for each of the variables. Although radar and spider chart names are used as synonyms, I think a spider chart is more appropriate for the latter situation in which every variable has its own axis, and radar chart for the former like in the above image. Unfortunately, as I was more interested in creating a spider chart, and no such option was available using this package, I was left to my own devices.</p><h3>Enter ggplot2</h3><p>The beauty of ggplot2 is the underlying grammar of graphics, allowing for creation of graphs by stacking multiple layers on top of one another. This powerful concept lets us create essentially any visualization, as long as we know how to code it. I’ll be using it to construct a spider chart from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLtv6_Z-eCQqkuJ8nH49HA.png" /><figcaption>The philosophy behind chart construction with the ggplot2 package. Image by Author</figcaption></figure><p>The layered approach calls for separate construction of different aspects of the graph. First we will create the chart outline. Since spider charts deal with polar coordinates, I made a function which calculates the coordinates of the polygon tips depending on the number of variables in the dataset.</p><pre>library(dplyr)<br>library(tidyr)<br>library(tibble)<br>library(purrr)<br>library(scales)<br>library(ggplot2)<br><br>p_data &lt;- Titanic_gr %&gt;% rename(group = &quot;Pclass&quot;)<br><br>circle_coords &lt;- function(r, n_axis = ncol(p_data) - 1){<br>  fi &lt;- seq(0, 2*pi, (1/n_axis)*2*pi) + pi/2<br>  x &lt;- r*cos(fi)<br>  y &lt;- r*sin(fi)<br>  <br>  tibble(x, y, r)<br>}<br><br>central_distance &lt;- 0.2<br><br>step_1 &lt;- map_df(seq(0, 1, 0.25) + central_distance, circle_coords) %&gt;%<br>    ggplot(aes(x, y)) +<br>    geom_polygon(data = circle_coords(1 + central_distance), <br>                 alpha = 1, fill = &quot;gray97&quot;) +<br>    geom_path(aes(group = r), lty = 2, alpha = 0.5) +<br>    theme_void()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*73UzhPLaDU_R286dCk78ew.png" /><figcaption>Step 1: Creating the background for the chart. Image by Author</figcaption></figure><p>Next, we have to calculate the coordinates for the axes and add them to the chart.</p><pre>axis_coords &lt;- function(n_axis){<br>  fi &lt;- seq(0, (1 - 1/n_axis)*2*pi, (1/n_axis)*2*pi) + pi/2<br>  x1 &lt;- central_distance*cos(fi)<br>  y1 &lt;- central_distance*sin(fi)<br>  x2 &lt;- (1 + central_distance)*cos(fi)<br>  y2 &lt;- (1 + central_distance)*sin(fi)<br>  <br>  tibble(x = c(x1, x2), y = c(y1, y2), id = rep(1:n_axis, 2))<br>}<br><br>step_2 &lt;- step_1 + geom_line(data = axis_coords(ncol(p_data) - 1), <br>aes(x, y, group = id), alpha = 0.3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*JLE6r0cmMeRmUDcjzZa1Gw.png" /><figcaption>Addition of axes for each of the variables in the dataset. Image by Author</figcaption></figure><p>Now we can add the textual labels and names of the axes.</p><pre>text_data &lt;- p_data %&gt;%<br>  select(-group) %&gt;%<br>  map_df(~ min(.) + (max(.) - min(.)) * seq(0, 1, 0.25)) %&gt;%<br>  mutate(r = seq(0, 1, 0.25)) %&gt;%<br>  pivot_longer(-r, names_to = &quot;parameter&quot;, values_to = &quot;value&quot;)<br><br>text_coords &lt;- function(r, n_axis = ncol(p_data) - 1){<br>  fi &lt;- seq(0, (1 - 1/n_axis)*2*pi, (1/n_axis)*2*pi) + pi/2 + 0.01*2*pi/r<br>  x &lt;- r*cos(fi)<br>  y &lt;- r*sin(fi)<br>  <br>  tibble(x, y, r = r - central_distance)<br>}<br><br>labels_data &lt;- map_df(seq(0, 1, 0.25) + central_distance, text_coords) %&gt;%<br>  bind_cols(text_data %&gt;% select(-r))<br><br>step_3 &lt;- step_2 + <br>    geom_text(data = labels_data, aes(x, y, label = value), alpha = 0.65) +<br>    geom_text(data = text_coords(1 + central_distance + 0.2), <br>              aes(x, y), label = labels_data$parameter[1:(ncol(p_data)-1)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*sqSG_D8nRhFWCqP3SKEZSA.png" /><figcaption>Addition of axes names and labels. Image by Author</figcaption></figure><p>The only thing left to do is overlaying of the data points.</p><pre>rescaled_coords &lt;- function(r, n_axis){<br>  fi &lt;- seq(0, 2*pi, (1/n_axis)*2*pi) + pi/2<br>  tibble(r, fi) %&gt;% mutate(x = r*cos(fi), y = r*sin(fi)) %&gt;% select(-fi)<br>}<br><br>rescaled_data &lt;- p_data %&gt;% <br>  mutate(across(-group, rescale)) %&gt;%<br>  mutate(copy = pull(., 2)) %&gt;% <br>  pivot_longer(-group, names_to = &quot;parameter&quot;, values_to = &quot;value&quot;) %&gt;%<br>  group_by(group) %&gt;%<br>  mutate(coords = rescaled_coords(value + central_distance, ncol(p_data) - 1)) %&gt;%<br>  unnest<br><br>step_4 &lt;- step_3 + <br>    geom_point(data = rescaled_data, <br>               aes(x, y, group = group, col = group), <br>               size = 3) +<br>    geom_path(data = rescaled_data, <br>              aes(x, y, group = group, col = group), <br>              size = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*CmxawoNZ0sT5eTcEyEXQeQ.png" /><figcaption>Overlaying the chart with the data points. Image by Author</figcaption></figure><p>And some final aesthetic touches…</p><pre>step_5 &lt;- step_4 + <br>    labs(col = &quot;Passenger class&quot;) +<br>    theme(legend.position = &quot;bottom&quot;,<br>          legend.text = element_text(size = 12),<br>          legend.title = element_text(size = 12))<br>  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*iHyksiNVIW3FJb3EHhsibQ.png" /><figcaption>The final spider chart. Image by Author</figcaption></figure><p>Ta-daa, our work here is done. Let’s just take a moment more to comment on the numbers displayed. The 1st class passengers were the oldest and the wealthiest of the three. The 3rd class passengers had the highest number of both male and female passengers and were the youngest group — probably mostly young people and families in search for better life abroad. However, the 1st class passengers had the highest survival rate, and the 3rd the lowest. This is probably partly due to the 1st class quarters being closer to the boat deck and partly due to the higher proportion of women in that class (since woman and children were rescued first).</p><h3>Bonus points</h3><p>To make the plots easier to reproduce, I made a function from the above code.</p><pre>library(dplyr)<br>library(tidyr)<br>library(tibble)<br>library(purrr)<br>library(scales)<br>library(ggplot2)<br><br>ggspider &lt;- function(p_data, <br>legend_title = &quot;Group&quot;, <br>background_color = &quot;gray97&quot;, <br>area_fill = TRUE, <br>central_distance = 0.2, <br>axis_name_offset = 0.2){<br><br>circle_coords &lt;- function(r, n_axis = ncol(p_data) - 1){<br>  fi &lt;- seq(0, 2*pi, (1/n_axis)*2*pi) + pi/2<br>  x &lt;- r*cos(fi)<br>  y &lt;- r*sin(fi)<br>  <br>  tibble(x, y, r)<br>}<br><br>(step_1 &lt;- map_df(seq(0, 1, 0.25) + central_distance, circle_coords) %&gt;%<br>    ggplot(aes(x, y)) +<br>    geom_polygon(data = circle_coords(1 + central_distance), alpha = 1, fill = background_color) +<br>    geom_path(aes(group = r), lty = 2, alpha = 0.5) +<br>    theme_void())<br><br><br>axis_coords &lt;- function(n_axis){<br>  fi &lt;- seq(0, (1 - 1/n_axis)*2*pi, (1/n_axis)*2*pi) + pi/2<br>  x1 &lt;- central_distance*cos(fi)<br>  y1 &lt;- central_distance*sin(fi)<br>  x2 &lt;- (1 + central_distance)*cos(fi)<br>  y2 &lt;- (1 + central_distance)*sin(fi)<br>  <br>  tibble(x = c(x1, x2), y = c(y1, y2), id = rep(1:n_axis, 2))<br>}<br><br>text_data &lt;- p_data %&gt;%<br>  select(-group) %&gt;%<br>  map_df(~ min(.) + (max(.) - min(.)) * seq(0, 1, 0.25)) %&gt;%<br>  mutate(r = seq(0, 1, 0.25)) %&gt;%<br>  pivot_longer(-r, names_to = &quot;parameter&quot;, values_to = &quot;value&quot;)<br><br>text_coords &lt;- function(r, n_axis = ncol(p_data) - 1){<br>  fi &lt;- seq(0, (1 - 1/n_axis)*2*pi, (1/n_axis)*2*pi) + pi/2 + 0.01*2*pi/r<br>  x &lt;- r*cos(fi)<br>  y &lt;- r*sin(fi)<br>  <br>  tibble(x, y, r = r - central_distance)<br>}<br><br>labels_data &lt;- map_df(seq(0, 1, 0.25) + central_distance, text_coords) %&gt;%<br>  bind_cols(text_data %&gt;% select(-r))<br><br><br>rescaled_coords &lt;- function(r, n_axis){<br>  fi &lt;- seq(0, 2*pi, (1/n_axis)*2*pi) + pi/2<br>  tibble(r, fi) %&gt;% mutate(x = r*cos(fi), y = r*sin(fi)) %&gt;% select(-fi)<br>}<br><br>rescaled_data &lt;- p_data %&gt;% <br>  mutate(across(-group, rescale)) %&gt;%<br>  mutate(copy = pull(., 2)) %&gt;%<br>  pivot_longer(-group, names_to = &quot;parameter&quot;, values_to = &quot;value&quot;) %&gt;%<br>  group_by(group) %&gt;%<br>  mutate(coords = rescaled_coords(value + central_distance, ncol(p_data) - 1)) %&gt;%<br>  unnest<br>    <br>  step_1 + <br>    geom_line(data = axis_coords(ncol(p_data) - 1), <br>              aes(x, y, group = id), alpha = 0.3) +<br>    geom_point(data = rescaled_data, <br>              aes(x, y, group = group, col = group), size = 3) +<br>    geom_path(data = rescaled_data, <br>              aes(x, y, group = group, col = group), size = 1) +<br>    {if(area_fill == TRUE) geom_polygon(data = rescaled_data, <br>                            aes(x, y, group = group, <br>                                col = group, fill = group), <br>                                size = 1, alpha = 0.05, show.legend = FALSE)} +<br>    geom_text(data = labels_data, <br>                     aes(x, y, label = value), alpha = 0.65) +<br>    geom_text(data = text_coords(1 + central_distance + axis_name_offset), <br>              aes(x, y), label = labels_data$parameter[1:(ncol(p_data)-1)]) +<br>    labs(col = legend_title) +<br>    theme(legend.position = &quot;bottom&quot;,<br>          legend.text = element_text(size = 12),<br>          legend.title = element_text(size = 12))<br>}</pre><p>Now, we can easily test the function on some different data, such as the mtcars dataset built into R.</p><pre>p_data &lt;- mtcars %&gt;%<br>  rownames_to_column(var = &quot;group&quot;) %&gt;%<br>  as_tibble() %&gt;%<br>  tail(3) %&gt;%<br>  select(1:7)<br><br>ggspider(p_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*LZVo1oRPGd2QyUV-3yYFaQ.png" /><figcaption>Spider chart of the mtcars dataset. Image by Author</figcaption></figure><h3>Conclusion</h3><p>This article shows how to construct a spider chart from scratch in R. Although no R package I know of currently supports this kind of chart, utilizing the layered grammar of graphics approach from the ggplot2 package provided me with the tools to create one myself. Of course, there is still room for progress, especially with regard to the aesthetical aspect of the chart, but that is a topic for some other article.</p><p>That’s all folks. I hope you found the article useful and will use it to make many more neat spider charts in the future. Enjoy!</p><p>P.S. If you liked the post, please clap and follow for more similar content in the future. Also, feel free to make suggestions about other interesting visualizations you think deserve to be implemented in R.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85a4f1898cab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-make-a-spider-chart-in-r-using-ggplot2-85a4f1898cab">How to Make a Spider Chart in R Using ggplot2</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Homo sapiens — the KNN classifier]]></title>
            <link>https://medium.com/data-science/homo-sapiens-the-knn-classifier-92261023249a?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/92261023249a</guid>
            <category><![CDATA[human-behavior]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 18:30:01 GMT</pubDate>
            <atom:updated>2022-09-07T18:30:01.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>Homo sapiens — the KNN classifier</h3><h4>How our decisions are governed by the KNN approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lz33l6WpIv_3SqHSnvNeQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fathomfilms?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sylas Boesten</a> on <a href="https://unsplash.com/s/photos/human?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The K-nearest neighbours (KNN) method is probably the most intuitive classifier algorithm, and all of us actually use it on a daily basis. In short, it can be described by well known proverbs such as</p><blockquote>Birds of a feather flock together</blockquote><p>or</p><blockquote>You are who you associate with</blockquote><p>This post will briefly outline how the KNN classifier work, and why I feel like it is a good depiction of certain human behaviours?</p><h4>The technical aspect of the KNN classifier</h4><p>The KNN algorithm assigns classes to data points based on their surroundings (their “nearest neighbours”). The figure below schematically illustrates its working principle using three simple geometrical shapes. If a decision is made based on the three nearest neighbours (the inside of the full circle), the X point is classified as a triangle. However, extending the model to five nearest neighbours (the insides of the dotted circle) yields a square as an estimate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*pxNNomMGuzzTbtBQ23wuBg.png" /><figcaption>How the KNN classifier works? Image by Author.</figcaption></figure><p>If you are interested in more technical details and how to implement the algorithm in R, please check out my earlier post. If not, just read on, since this simple explanation is all we need to know in order to understand how the KNN algorithm relates to people.</p><p><a href="https://medium.com/@zvonimir.boban.mef/birds-of-a-feather-flock-together-the-story-of-the-knn-classifier-d62b31eb58fa">“Birds of a feather flock together” — the story of the KNN classifier</a></p><h4>Train, validate, test, go!</h4><p>In order to understand the following discussion, I will first briefly go through definitions of the <strong>training</strong>, <strong>validation</strong> and <strong>test</strong> datasets. The training set is used to fit our model, the validation set to tune the model hyperparameters, and the test set to see how well it does on some previously unseen data. In the case of the KNN classifier, no actual training occurs — the model just contains the raw data from the training set which is used later to find the optimal hyperparameter values.</p><p>What is a hyperparameter in the case of KNN classifier? It is K, the number of neighbours. We use the validation set in order to find the optimal number of neighbours which yield the best possible classification results. Following that, unknown data from the test set is used to provide a measure of how well our model works in a previously unknown environment. If we are satisfied with the result, our model is ready to go!</p><h4>How are people similar to KNN classifiers?</h4><p>Now we can move on to the actual comparison. The training set is provided to us during our upbringing. Each time we meet someone new, we use our senses to collect their features and then assign them to a certain class. Once we are old enough, we use this data in order to set ourselves up in the world. Of course there is a lot of trial and error in this process. This is because, in the language of machine learning, we are tuning our hyperparameters. For example, we might start with a very high or very low K, i.e. we will compare the features of the newly met person to either the features of many similar people from the past or just the most similar (K = 1). There can be no a priori best value since, the best solution will highly depend on the complexity of the social structure. To sum up, we are meeting a lot of new people and trying to classify them based on our previous experience. In this way we are using them as a validation set in order to choose the optimal K for our surroundings.</p><p>Once we have confidence in our model, our goal is to go out and try to classify people into certain groups without having the ability to verify whether it is correct or not. If our model is well tuned, it can be a great tool as it allows us to rapidly assess a person and decide on the next course of action. However, this approach will naturally also lead to some errors as well.</p><h4>Pride and prejudice</h4><p>We have stated before that the KNN model doesn’t actually do any work during training, since it only stores the data points. This is why it is often referred to as a <strong>lazy</strong> model. This transfers really well to humans, since we are often equally lazy when judging a person. Instead of giving a person time to get to know them, we often judge them on the spot and, if we don’t like what we see, we simply move on. There is no second guesses with the KNN classifier. You either belong to a certain category or not. While the evolutionary advantage of such a simple and rapid approach is clear, it can lead to misjudgments as well. In my opinion, this similarity to the KNN classifier is at the core of why we humans are so prone to prejudicial reasoning.</p><p>Another potential pitfall can arise if the training set stops being representative of the test set. This can occur for any number of reasons, such as moving to another city/country, or changing our job. When this happens, our model’s accuracy will greatly decrease. If we are too proud and refuse to abandon the old model and create a new one, we will come into conflict with the people from our surroundings very quickly.</p><h4>Final remarks</h4><p>This short opinion is just that, my opinion. Of course, things are never this simple, and while there are many differences, I think the KNN algorithm describes our primal reflexes quite well. I thought the similarities were tantalizing and decided to write this post as it opened up a different perspective for me. I hope you find it equally interesting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92261023249a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/homo-sapiens-the-knn-classifier-92261023249a">Homo sapiens — the KNN classifier</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bringing order into bar chart chaos]]></title>
            <link>https://medium.com/data-science/bringing-order-into-bar-chart-chaos-f271ab91a6ee?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f271ab91a6ee</guid>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bar-chart]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 05:22:16 GMT</pubDate>
            <atom:updated>2023-07-11T08:00:14.612Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to reorder faceted bar charts?</h3><h4>Ordering the bars in a single and faceted ggplot2 bar chart</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIrtjMVSjiFGLccRykJY6g.jpeg" /><figcaption>Image by Author</figcaption></figure><p>We all like order (or at least most of us). It helps us organize our thoughts and gives us a sense of peace. The same principle applies to data visualizations. We like them neat and ordered as it looks more aesthetically pleasing and facilitates comparisons. The bar chart is a visualization in which this is most obvious. Most of you are probably familiar with reordering bars when working with a single chart. However, I bet most of you would have problems doing it on a faceted chart. In the following text, I will show how to solve this issue for both scenarios using the information on the Gross Domestic Product (GDP) from the <a href="https://data.worldbank.org/indicator/NY.GDP.MKTP.CD">World Data Bank</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b4bcd26f9966dbb344748b1df1bac63/href">https://medium.com/media/7b4bcd26f9966dbb344748b1df1bac63/href</a></iframe><h4>Ordering a single bar chart</h4><p>Let’s filter only the top seven world economies in a span of four decades:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc0c2e06b0a31ac660228e7ff230c834/href">https://medium.com/media/cc0c2e06b0a31ac660228e7ff230c834/href</a></iframe><p>Now, we can use a bar chart to compare their GDPs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad2b4adabac85869606c9b340a517767/href">https://medium.com/media/ad2b4adabac85869606c9b340a517767/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EyFquAsGkygYgJDyzLTZSQ.png" /></figure><p>It is a bit hard to conpare countries due to the country labels not being ordered by their GDPs. We can solve this by using the reorder function to order the countries descendingly by their 2020 GDPs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eedee34caa50d1a39542db584698a15b/href">https://medium.com/media/eedee34caa50d1a39542db584698a15b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VFQ7zHg1D7EtzWgDOCcyxQ.png" /></figure><p>Great! We have obtained a usable plot. However, this is a chart only for the year 2020. The next section will show how to order the bars when simultaneously displaying multiple bar charts for different years.</p><h4>Multiple charts — faceting the bar chart</h4><p>In order to simultaneously illustrate the GDP comparison of countries at different times, we can use the facet_wrap function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35b299d86fa3b5fc03eef1e139b41fee/href">https://medium.com/media/35b299d86fa3b5fc03eef1e139b41fee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*PCANN94NgcRZYM0eAvKtPw.png" /></figure><p>We can observe the same problem as before — the bars are not ordered. Let’s try using the same recipe to solve this issue as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f524118c928ee1e0c4a8c8705f27ce59/href">https://medium.com/media/f524118c928ee1e0c4a8c8705f27ce59/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*j4Us-7AV96tGWkgTKR_ysQ.png" /></figure><p>The problem persists! You might think that this might just be an artifact of this facet layout, as using the same horizontal axis labels across the whole column automatically forces the same bar ordering. If that was the case, the problem could be remedied by allowing each facet to have its own set of horizontal axis labels. We can do this by setting the scales argument of the facet_wrap function to “free_x”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34e4816ce2983bdfbc765b448d81e2f7/href">https://medium.com/media/34e4816ce2983bdfbc765b448d81e2f7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Fz_CJR0K8EK1X4WhZqet1g.png" /></figure><p>This didn’t solve the problem either because the ordering is again done globally. The next section will show how to bypass this issue using the tidytext package.</p><h4>Ordering the facets</h4><p>As its name suggests, the tidytext package is created to facilitate the conversion of text to a tidy format. Here, we will focus on the reorder_within function which allows us to reorder bars within a facet. Besides swapping the reorder function with reorder_within, we also have to add a call to the scale_x_reordered function from the same package in order to make this work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d5775917c1d743230b87908ae1a537/href">https://medium.com/media/a1d5775917c1d743230b87908ae1a537/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Us0pNdO09kOpI464l6Q-Fw.png" /></figure><p>That’s it! We can see that the US has managed to stay in 1st place throughout the last four decades. However, China has the fastest growth rate, and seems to be closing in. Japan and Germany have managed to retain their positions behind the leading two, but other major European economies, such as France and the United Kingdom, seem to be lagging behind, making way for India.</p><h4>Conclusions</h4><p>This post shows how to order single and faceted bar charts. The final ordered faceted chart enabled us to more easily make comparisons between the world’s most significant economies. So, the next time you want to make comparisons between faceted bar charts, you should know what to do. For any questions or remarks, please feel free to drop a comment.</p><p>P.S. For those of you who couldn’t stop thinking about those unordered brick columns, here’s a scratch to your itch :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrazp62c2yIGsi8EYfPdeg.jpeg" /><figcaption>Image by Author</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f271ab91a6ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/bringing-order-into-bar-chart-chaos-f271ab91a6ee">Bringing order into bar chart chaos</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into the tidyverse using the Titanic data]]></title>
            <link>https://medium.com/data-science/diving-into-the-tidyverse-using-the-titanic-data-83f54295d5df?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f54295d5df</guid>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[tidyr]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dplyr]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 22:13:34 GMT</pubDate>
            <atom:updated>2022-08-30T22:13:34.796Z</atom:updated>
            <content:encoded><![CDATA[<h3>Diving into the tidyverse Using Titanic Data</h3><h4>Extracting insights using R’s dplyr and tidyr packages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rb0hwiSKTBMnTsne4ctogA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@maxvdo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Max van den Oetelaar</a> on <a href="https://unsplash.com/s/photos/organized?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Data is more available today than ever before. We can easily find out what we are interested in through many resources on the Internet. However, when trying to draw conclusions from the data, we quickly realize that the data, although easily found, is not in a format that can be readily used for a more detailed analysis. The same problem arises when several people try to collaborate on some research. If they have not previously agreed on how to label and enter data, everyone will most likely come up with their own system. This ultimately results in confusion when sharing and analyzing data. These issues create the need for a unique data organization system.</p><p>In his work Anna Karenina, Leo Tolstoy expressed the thought:</p><blockquote>All happy families are alike; each unhappy family is unhappy in its own way.</blockquote><p>Alluding to that quote, one of the visionaries of programming in R, Hadley Wickham, addressed the problem of data organization with the following words:</p><blockquote>Tidy datasets are all alike but every messy dataset is messy in its own way.</blockquote><p>With tidy data, each row is an observation and each column is a variable. Let’s say we list the types of cars by their horsepower and weight. Data organized in a tidy way would then contain three columns: the type of car, horsepower and mass. Consequently, by looking at one row of the data, we would get all the information about one type of car. Focusing on one data column would provide information about a single property (eg. mass) for all types of cars.</p><p>In an effort to translate the data into a tidy format, Hadley Wickham developed the tidyverse - a suite of packages that includes the following packages: dplyr, tidyr, ggplot2, purrr, readr and tibble. In the following text, we will focus on the subset of these packages used for data wrangling - dplyr, tidyr and tibble.</p><p>Although tidyverse presents a set of consistent and effective methods for transforming and visualizing data, it is important to emphasize two things:</p><ul><li>results obtained using the tidyverse functions can be obtained (albeit usually in a more complicated/less intuitive way) using the basic R functions</li><li>R is a programming language, and tidyverse is a set of packages aimed at facilitating data transformations and visualizations. In other words, the tidyverse packages can not solve all the problems we may encounter, so it is important to know the basics of R programming as well.</li></ul><h3>Titanic dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HReEYmYgfmOy3HwFe4rk1w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@noaa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NOAA</a> on <a href="https://unsplash.com/s/photos/titanic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the following text, I will cover the most important functions of the dplyr, tidyr and tibble packages. I will showcase how these functions can be used to perform various common tasks involved in data cleaning and exploratory data analysis. I will use the data about the passengers of one of the most famous ships - the Titanic.</p><p>As a first step, we have to load the necessary packages and study the structure of the data we will use. Aside from the data wrangling packages, we have to load the titanic package which contains the needed data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3c2a8bd8852c51b76e0f7e4b3cc2676/href">https://medium.com/media/c3c2a8bd8852c51b76e0f7e4b3cc2676/href</a></iframe><p>The Titanic dataset is a data.frame type object. Consequently, if we printed the Titanic dataset, the whole 891 rows would be returned. Since such a layout is clumsy and cumbersome, I printed only the first ten rows using the base R head function. In order to bypass this issue, the tibble package introduces a tibble data type. This type improves on the data.frame class by only printing the first ten rows when showing a dataset. It also prints out the number of rows and columns of a dataset and the data type of each column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e79b87d97b57c0c78682e48d0731c8b/href">https://medium.com/media/6e79b87d97b57c0c78682e48d0731c8b/href</a></iframe><p>Even the head function can be improved upon as it does not indicate the column data type, and when there are many variables (many columns), it does not show them all, but only as many as can fit on the screen. Instead, we can use the glimpse command which shows a transposed version of the printout to get a more complete overview of the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e2799b3e181f19a114c61fae70840ef/href">https://medium.com/media/4e2799b3e181f19a114c61fae70840ef/href</a></iframe><p>We can see that the data contains 12 variables: passenger serial number (PassengerId), binary passenger survival variable(Survived), passenger class (Pclass), name (Name), sex (Sex), age (Age), number of siblings and spouses on board (Sibsp), number of children/parents on board (Parch), ticket number (Ticket), fare paid (Fare), cabin number (Cabin) and the passenger’s boarding location (Embarked).</p><h3>The pipe %&gt;% operator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZZKFiX5zRv17D34muiGfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sigmund</a> on <a href="https://unsplash.com/s/photos/pipe?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Before moving forward with the analysis, I would like to introduce the pipe operator. The advantage of the pipe operator is the ability to bind functions. More precisely, it passes the result of one function as the first argument to the next function in the sequence. This may not seem very useful at first, but it greatly increases the clarity of the code when using a composition of many functions. Let’s look at an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fabefc68295f008260cafedbf9355241/href">https://medium.com/media/fabefc68295f008260cafedbf9355241/href</a></iframe><p>The pipe operator enables us to read the composition from left to right, as if we were reading a book! Once you get used to using it, I guarantee you will never look back. This is why, even though all R functions can be used without it, I will use the pipe in the rest of this post.</p><h3>Extracting information using the dplyr package</h3><p>The dplyr package contains functions to facilitate data manipulation to extract meaningful insights. It is partly inspired by SQL (Structured Query Language), so those of you with background in SQL will probably find them quite intuitive.</p><h4>Rename columns</h4><p>We will start by renaming the columns using rename in order to make them more understandable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e12138fa1806b2443171acbe3813e112/href">https://medium.com/media/e12138fa1806b2443171acbe3813e112/href</a></iframe><p>Renaming can also be performed by applying a function to multiple columns using the rename_with function. For example, we might prefer a convention where all variable names are written in lowercase:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70563208f6ae9dcdf30f40d2478a7f0b/href">https://medium.com/media/70563208f6ae9dcdf30f40d2478a7f0b/href</a></iframe><h4>Select columns based on their names</h4><p>We are often not interested in all of the dataset variables. The select function allows us to subset the columns of interest.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a0da8814cab3edea8fc950101c26e1/href">https://medium.com/media/29a0da8814cab3edea8fc950101c26e1/href</a></iframe><p>If the desired columns are positioned adjacently in the initial data frame, there is also a shorter way to select them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f739a9a52b6ded70a183faa3c559aa43/href">https://medium.com/media/f739a9a52b6ded70a183faa3c559aa43/href</a></iframe><p>What if we want to select only the name and the variable associated with the number of relatives on board? Of course, we can again use the technique from the first example. However, select can also be combined with a plethora of helper functions which make such tasks faster and easier to perform. For example, the contains helper allows us to search by parts of column names. We can use this if we notice that both variables associated with the number of relatives contain the underscore symbol .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45734a53a2c1c28d53a268de05482bbf/href">https://medium.com/media/45734a53a2c1c28d53a268de05482bbf/href</a></iframe><p>Similarly to the contains function, we can also use the starts_with and ends_with functions. For a list and explanation of all helper functions, you can consult the help files by typing ?select in the R console.</p><p>Column selection can also be performed by specifying the columns we want to remove from the data. This is done by placing a minus sign in front of the names of unwanted columns.</p><p>Let’s simplify our dataset by removing the ticket, cabin number and the columns related to the number of relatives/spouses on board:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ef939c8ac9add7d9d6d91bac142fc8/href">https://medium.com/media/d3ef939c8ac9add7d9d6d91bac142fc8/href</a></iframe><h4>Value based column selection</h4><p>What if we were interested only in columns containing numeric values? We could look up the variable types manually and then follow the procedure from the previous subsection.</p><p>Luckily, this tedious task can be automated since column selection can also be performed based on the values stored within them by teaming up the select and where function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c84f4929f6478b6de0e6ff4e45164f/href">https://medium.com/media/d4c84f4929f6478b6de0e6ff4e45164f/href</a></iframe><h4>Transform existing columns or add new ones using mutate</h4><p>The mutate function allows us to transform the existing columns or create new columns using either external data, or data already present in the data frame.</p><p>R has a handy factor class built-in which should be used when a categorical variable has a limited number of possible values (levels). We can see that the Sex variable has such properties. mutate enables us to change the column data type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b97c65bb5c16a063a37f9dfb81f5db86/href">https://medium.com/media/b97c65bb5c16a063a37f9dfb81f5db86/href</a></iframe><p>Some of you might also want to abbreviate the gender values. This can be done using the case_when function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4e7d3e73171cd7a4182ef4ddeb0a70e/href">https://medium.com/media/c4e7d3e73171cd7a4182ef4ddeb0a70e/href</a></iframe><h4>Transforming multiple columns at once</h4><p>Some of you probably noticed that it wouldn’t be bad to also convert data types of Survived and Embarked columns from character to factor.</p><p>Instead of doing it by specifying the columns one by one, we can transform multiple columns at the same time by applying the mutate + across combination. The across function specifies the columns to transform and the functions to be applied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19e8f546ca68e37274edbfa4d3c3c836/href">https://medium.com/media/19e8f546ca68e37274edbfa4d3c3c836/href</a></iframe><p>The selection of columns in the across function can also be performed using the helper functions mentioned while talking about the applications of the select function.</p><h4>Filter data frame rows</h4><p>The filter function is used to subset observations from the data. As such, it can be used to answer questions about distinct groups of passengers onboard.</p><p>What percentage of passengers survived the crash?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9013205c55ba90d411ec2943eaf82983/href">https://medium.com/media/9013205c55ba90d411ec2943eaf82983/href</a></iframe><p>Only a little more than a third of passengers survived the crash. Was there a difference in survival based on passenger sex?</p><p>What is the proportion of women among passengers?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abaac3ed1cdc86c82d66d0ddbaf7ecde/href">https://medium.com/media/abaac3ed1cdc86c82d66d0ddbaf7ecde/href</a></iframe><p>What is the proportion of women passengers who survived the crash?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8151d6533d4a18322fec44f3889e609/href">https://medium.com/media/e8151d6533d4a18322fec44f3889e609/href</a></iframe><p>So, even though women represented a smaller population of passengers, their chances of survival were approximately two times higher than those of men. Of course, this was expected, since women and children are given priority in rescue missions.</p><p>Next, we will check how the survival varied based on passenger class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bff83648cd680a64f397747763c9cac3/href">https://medium.com/media/bff83648cd680a64f397747763c9cac3/href</a></iframe><p>The chances of survival were lower if you traveled in the lower classes. This could be due to the influence of richer passenger but also due to the fact that the first class was closer to the boat deck where the rescue boats were stationed.</p><p>There are also filter helper function if_any and if_all which allow us to filter on multiple columns at once. These can be used to perform a common task of removing observations with missing values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/675229f495c71b46948e0225d14130a6/href">https://medium.com/media/675229f495c71b46948e0225d14130a6/href</a></iframe><h4>Arrange rows based on column values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moiOMSwQeQrECGM6I_xv7g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tolga__?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tolga Ulkan</a> on <a href="https://unsplash.com/s/photos/order?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Often, we want to sort the data based on a certain criteria of interest. This is done with dplyr using arrange. Let’s sort the passengers in ascending order of age, and then sort the passengers of the same age alphabetically by name. By default, the sorting is ascending, but the desc command can be used to order descending sorting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14d9b0641e8d0fe6db5ff28791e663d1/href">https://medium.com/media/14d9b0641e8d0fe6db5ff28791e663d1/href</a></iframe><p>From this output, we might hypothesize that older passengers are more likely to be male than female. Additionally, it also seems that older passengers seemed to have been higher class passenger. For me, this is a plausible claim, knowing that the Titanic traveled from England to the United States, carrying with it a lot of people in search of new opportunities and a better life. I would assume that such people would be younger, since an older man has less incentive to move away. We will be able to answer all of these questions with the tools covered in the next two subsections.</p><h4>Obtain column summary statistics with summarise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CM9awrEFMxZUXirl75d1Qg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anne Nygård</a> on <a href="https://unsplash.com/s/photos/numeric-summary?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This command is very useful when we are not interested in individual values, but in the summary statistics of the data set. Let’s calculate the average age of the passengers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46fa3361c3ac0850d4dd4c3f249f1ed7/href">https://medium.com/media/46fa3361c3ac0850d4dd4c3f249f1ed7/href</a></iframe><p>We got an unexpected result. This is a consequence of “holes” in the data that have been replaced with NA (“Not available”, missing data). We can solve this problem by filtering the data frame to exclude passengers with an unknown age before calculating the summary statistics. When filtering, we use a special command that tests whether the data is of type NA - is.na.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca32418ac8fc0e78cb729d86da7a71b5/href">https://medium.com/media/ca32418ac8fc0e78cb729d86da7a71b5/href</a></iframe><p>Just like with mutate, summarise can also be combined with across in order to get a summary on multiple columns at once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b22b4ce241a4c2dbc067d0cad7bac71/href">https://medium.com/media/6b22b4ce241a4c2dbc067d0cad7bac71/href</a></iframe><p>In order to answer the questions about the age difference depending on the gender and passenger class, we could first filter the population of interest and then calculate the needed summary. However, this approach would require us to write out a new summary each time, similarly to how we calculated the survival rates depending on the passenger class. To avoid this we will use the group_by function covered in the next subsection.</p><h4>Group the observations based on a categorical property with group_by</h4><p>By itself, the summarise function would not be that useful, but paired with the group_by function, it allows for a quick summary of information about all the levels of categorical variables. The group_by function divides the data into groups depending on the categories of a certain variable. Then the function of interest is applied separately to each one of those groups using summarise, and the result is combined back to a single data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_f2lAXv3IxiGrHgHEQoCng.png" /><figcaption>How group_by works behind the scenes. Image by Author.</figcaption></figure><p>This combination finally enables us to elegantly answer the hypotheses laid out earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aa69f0de8d3e80e74749e8f8cc1456d/href">https://medium.com/media/8aa69f0de8d3e80e74749e8f8cc1456d/href</a></iframe><p>There were three times more men above the age 55 onboard, so it seems our first hypothesis proved to be correct.</p><p>Let’s also check the second hypothesis about the class related age differences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1df6c3d1690f7d9c91ce205acff0ee1c/href">https://medium.com/media/1df6c3d1690f7d9c91ce205acff0ee1c/href</a></iframe><p>Our hunch seems to be backed up by data, as there indeed seems to be a correlation between the passenger class and age.</p><p>Notice that this approach also enables us to more easily find out the survival differences based on the passenger class, discussed in the filter subsection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e0edee0261a42a881fd87ec3d81060f/href">https://medium.com/media/1e0edee0261a42a881fd87ec3d81060f/href</a></iframe><p>In a similar way as with the summarise function, the group by command can be combined with the mutate and filter commands.</p><p>Let’s create a variable that will rank passengers by age based on gender. The rank command will help us by assigning an ordinal number to a set of values starting from the smallest to the largest. As with the arrange command, the default order can be reversed using desc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967fdf6d01298cb88845cc8aa9d2c973/href">https://medium.com/media/967fdf6d01298cb88845cc8aa9d2c973/href</a></iframe><p>Combining group_by with filter can give us, for example, a list of the three oldest passengers for each gender.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85dc2ec5ea405479728cb9f4c215e604/href">https://medium.com/media/85dc2ec5ea405479728cb9f4c215e604/href</a></iframe><p>The results are in line with our previous conclusions, as the oldest female passenger is 17 years younger than the oldest man.</p><p>As it turns out, there is also a convenience slice_max function to achieve the same goal, so the above snippet should only be used as an educational example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1063d788c6c268811d37076690681f41/href">https://medium.com/media/1063d788c6c268811d37076690681f41/href</a></iframe><p>To cancel the grouping, we use the ungroup function. It is advisable to do this at the end of any transformation that involves grouping. This is because forgetting that we have grouped the data by some variable can cause unexpected results in further analysis.</p><h4>Functions for combining/matching data frames</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygiz93UoZWz_I4GPk0m6Wg.png" /><figcaption>How join functions work. Image by Author.</figcaption></figure><p>Earlier, while calculating the average age, we noticed that the Titanic data is incomplete. Let’s see who these passengers are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3a8d8e367d16607e833c996f39875f/href">https://medium.com/media/6e3a8d8e367d16607e833c996f39875f/href</a></iframe><p>Fortunately, the Titanic crash is so famous that there are many webpages dedicated to listing the passengers and their backgrounds. Consequently, we can create a new data frame that will contain the names and ages of some of the passengers for whom the data is missing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc9c683e375d51dd6938d7c8f7ff3012/href">https://medium.com/media/dc9c683e375d51dd6938d7c8f7ff3012/href</a></iframe><p>Since the missing data is spread out in the Titanic dataset (look at the PassengerId values which are actually just row numbers), it would be hard to append the additional information manually. These types of problems can be solved by left_join, a function which adds data from one data frame to the other based on a common identification variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e296c27882eb5b64352348cd338c562c/href">https://medium.com/media/e296c27882eb5b64352348cd338c562c/href</a></iframe><p>Notice that instead of a single Age variable, we have Age.x and Age.y. This occurs in order to enable us to discern which data frame the age variable came from. We can use mutate with case_when to merge the two age columns into one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac358ab0ebdbfb515755760ad6bdf8d8/href">https://medium.com/media/ac358ab0ebdbfb515755760ad6bdf8d8/href</a></iframe><h3>Tidying up with tidyr</h3><p>As its name suggests, the tidyr package contains commands to covert data frames into a tidy format. The Titanic data frame is already tidy, since every row represents a single passenger, and every column an independent passenger feature. However, this is often not the case with datasets. Additionally, an “untidy” format might be needed in some instances such as plotting. The next subsection will illustrate such an example.</p><h4>Wide-long format conversions using pivot_wider and pivot_longer</h4><p>These are probably the most valuable functions in the tidyr package. The pivot_longer function is useful when we want to convert multiple columns to a single one with multiple subgroups. The image below illustrates how this works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-AgY0ngkkXMnE-H3EXURw.png" /><figcaption>How the pivot functions work. Image by Author.</figcaption></figure><p>The table on the left contains three related columns — they all represent a type of relative. Knowing this, we might want to group them into a single “Relative” column. This makes the data longer (hence longer in the function name). Furthermore, it became untidy since the same person is represented by three separate rows. Why would we do this?</p><p>Well, if we wanted to make a bar chart with the type of relative on the horizontal axis, we would have to provide a single variable. We can do this with the format on the right, but not with the format on the left.</p><p>Let’s now show how to apply these transformations on the Titanic data. To make it easier to follow the transformations, we will select only the first three rows of the Titanic data frame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5453c4cdf057ded5e97b158bf406b516/href">https://medium.com/media/5453c4cdf057ded5e97b158bf406b516/href</a></iframe><p>We can display the same data using fewer columns by applying pivot_longer. For example, we could have a passenger’s name column and two columns that contain all information on the passenger’s properties (passenger class, age, gender, survival). Why two columns for properties and not one? Because one column must contain the information about the property in question, and the other the value of that property. Since we are combining numeric and character values, we must first convert all values to the same type (character).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e611f46ae7984e2261f88bef51e1c4eb/href">https://medium.com/media/e611f46ae7984e2261f88bef51e1c4eb/href</a></iframe><p>As expected, the number of rows is seven times larger because now we have to repeat the name of each passenger seven times — once for each of the parameters in the Parameter_name column. Of course, as opposed to the example on the image above, it does not make sense to group the parameters in such a way, since they are not related. However, if you work with data often, these types of issues will be the least of your problems, as the input is at least consistent. You would probably never create such data yourself, but I am doing it here so I can show you how to get out of that mess when someone brings it over (and, trust me, someone eventually will…).</p><p>As an inverse of the pivot_longer function, pivot_wider is the answer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02410d3f4205e1cf1aa0c85ab39b235d/href">https://medium.com/media/02410d3f4205e1cf1aa0c85ab39b235d/href</a></iframe><p>Of course, we should also convert the column values back to their proper types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bd70d0323ec44a4e27fa51dc040674a/href">https://medium.com/media/0bd70d0323ec44a4e27fa51dc040674a/href</a></iframe><h4>Separate() and unite()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iOk0OkRFsCwZ8UiA7sijA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@willfrancis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Will Francis</a> on <a href="https://unsplash.com/s/photos/separate?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Like the aforementioned pivot_longer and pivot_wider, these two functions are also inverses of each other. The simplest example of a reason to use the separate function is to separate date records. Let’s say we have a column of birthday dates of Olympic medal winners in the format day_month_year and we want to calculate the average age of the winners in years. This would mean that we have to somehow extract only the year from the date. separate enables us to do just that, to make, for example, three variables from one date variable: day, month and year. The unite function works the other way around, connecting multiple variables into one (eg. day, month, year into a date variable of the format day_month_year). In essence, it is just a paste function with some additional arguments, such as allowing for automatic removal of input columns from the data frame.</p><p>Looking at the names of the passengers, we can see that they can be divided into several groups. The first word before the comma is the last name, followed by the title and the first name. It is useful to separate these groups because we get additional information. For example, the information on marital status from passenger titles — Mr/Mrs for married passengers and Master/Miss for single passengers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647fbef4f550641a2b7f97483bcea6a7/href">https://medium.com/media/647fbef4f550641a2b7f97483bcea6a7/href</a></iframe><p>For those of you not familiar with regular expressions, the expression [,\\.] translates to: break up the string whenever you encounter a comma or a dot. Why do we need the the backslashes in front of the dot? Because the dot by itself has a special meaning in regular expression, so this is a way to tell R we are interested in the dot character itself, and not its special function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7596b5adecbd9096417c1c9903dc2f8/href">https://medium.com/media/b7596b5adecbd9096417c1c9903dc2f8/href</a></iframe><p>The titles give us an insight into the social structure of the passenger population we wouldn’t be able to easily access otherwise.</p><h4>Conclusions</h4><p>I hope this post was useful to you and that you learned something new. I tried to cover as many common tasks and problems as possible. However, no single (non-simulated) dataset contains all the problems you might encounter in your data analysis, so there are many issues and scenarios that have not been covered. Additionally, no exploratory data analysis can be complete without visualizing the data. Since adding that would make this post too long, I left it for some future story. Nevertheless, if you have any questions or encounter a complex issue (including visualization) that you want to solve using the tidyverse toolbox, please feel free to drop a comment!</p><p>P.S. For a quick overview/reminder of the functions in the dplyr and tidyr packages and their usage, you can use the handy <a href="https://www.rstudio.com/wp-content%2Fuploads%2F2015%2F02%2Fdata-wrangling-cheatsheet.pdf%2F">cheatsheet</a> by RStudio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f54295d5df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/diving-into-the-tidyverse-using-the-titanic-data-83f54295d5df">Diving into the tidyverse using the Titanic data</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Birds of a feather flock together” — the story of the KNN classifier]]></title>
            <link>https://medium.com/@zvonimir.boban.mef/birds-of-a-feather-flock-together-the-story-of-the-knn-classifier-d62b31eb58fa?source=rss-e31978768a4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d62b31eb58fa</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zvonimir Boban]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 09:51:30 GMT</pubDate>
            <atom:updated>2022-08-31T09:45:52.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>Birds of a feather flock together</h3><h4>The story of the KNN classifier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fjx5ME7jSvR1uujxarf07A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tumbao1949?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Wainscoat</a> on <a href="https://unsplash.com/s/photos/flock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This post will introduce you to the K nearest neighbors (KNN) classifier and how it can be implemented using the R programming language. Along the way, we will talk about the historical origin of the method and discuss the importance of having separate train and test datasets.</p><h3>About classification models</h3><h4>How well is our classifier performing?</h4><p>Classifier algorithms in general are aimed at predicting some categorical property of a data point based on its features. Of course, in order to assess anything, we have to be able to measure the classifier accuracy. The simplest such measure in a classification setting is the error rate, defined as the proportion of incorrect classifications.</p><h4>Choosing the best model — why we need the test set</h4><p>At first glance, picking the optimal model seems straightforward. We take the data, construct the model and pick the one with the lowest error rate. The problem with this approach is that we are not interested in minimizing the error rate on the dataset used for model construction, but on some previously unseen data. The simplistic approach described above would lead to an issue called <strong>overfitting</strong>, meaning the model is so attuned to the training data that it loses the ability to generalize on any other dataset.</p><p>This problem can be remedied by splitting the data into a <strong>train</strong> and <strong>test</strong> dataset. The training set is used for model construction, and the test set for its evaluation. Consequently, the best model is the one with the lowest error rate on the test dataset. The sest for training and testing should come from the same population. However, in order to produce an unbiased assessment of the error rate on real data, no information from the test set should be used during model construction.</p><h3>The KNN classifier</h3><h4><strong>Historical background and intuitive explanation</strong></h4><p>The earliest mention of the KNN algorithm dates back to 1951, and is actually a technical report¹ for the US Airforce. A reprint of the original report has been published in 1977 and 1989² (with a formal review of the classifier properties).</p><p>This method is probably the most intuitive classifier algorithm, and all of us actually use it on a daily basis. In short, it could best be described by an old English proverb:</p><blockquote>Birds of a feather flock together.</blockquote><p>In other words, the algorithm assigns classes to data points based on their surroundings (their “nearest neighbors”). Figure below illustrates the working principle of the KNN algorithm. If a decision was made based on the three nearest neighbors (the inside of the full circle), the x point would be classified as a triangle. However, extending the model to five nearest neighbors (the insides of the dotted circle) would yield a square as an estimate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*P70B1ukiWHKIQmNiXMPxkQ.png" /><figcaption>How does the KNN algorithm perform classification? Image by the Author.</figcaption></figure><h4><strong>The KNN algorithm</strong></h4><p>Technically speaking, the method can be reduced to the following steps:</p><ol><li>Splitting the data into training and testing sets</li><li>Choosing how many nearest neighbors will be taken into account when determining the unknown class of our data point (setting the value of the K parameter)</li><li>Categorizing the the data point to the class that occurs most frequently in its K nearest neighbors</li></ol><p>In order to be able to determine how close the neighbors are, we need a measure of distance. Different measures can be used in this step. However, the most commonly used one is the Euclidean distance, named after the Greek mathematician Euclid, also referred to as the father of geometry. For two points <em>a</em> and <em>b</em> in an <em>n</em>-dimensional space, the Euclidean distance can mathematically be expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/0*0nVrWwIbXmfTPIcR" /><figcaption>Euclidean distance formula</figcaption></figure><p>In two dimensions (<em>n</em> = 2), this equation reduces to the well known Pythagoras theorem, <em>c² = a² + b²</em>, where <em>c</em> is the hypotenuse, and <em>a</em> and <em>b</em> the other two sides of a right-angled triangle.</p><p>In order to give equal importance to all input parameters, we have to account for different scales used in each of them. For example, our model might use the height in meters, and weight in kilograms. Using the Euclidean measure of distance, a height difference of 1 m and a difference in weight of 1 kg would contribute equally to the model. However, we know that a difference in height of 1 m is much more important than a weight difference of 1 kg. The problem can be solved by scaling the input parameters to a [0,1] interval. For the <em>i</em>-th value of some input variable <em>a,</em> this is done using the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/0*m-qR8G5SujhZDo0i" /><figcaption>Formula for scaling the data to a [0, 1] interval.</figcaption></figure><h3>Example: iris flower species classification</h3><h4>Exploratory data analysis</h4><p>The iris dataset contains information on the physical characteristics of three iris species. We will try to use these characteristics to correctly predict the species using the KNN classifier.</p><p>The dataset is built into R, so we can access it by just typing its name into the console. In all of my posts, I am using the tidyverse set of packages to manipulate the data, so I am loading them here prior to any data analysis. If you are not familiar with data wrangling using the tidyverse , I also wrote a helpful post on that topic.</p><p><a href="https://towardsdatascience.com/diving-into-the-tidyverse-using-the-titanic-data-83f54295d5df">Diving into the tidyverse using the Titanic data</a></p><p>Let’s take a peek at a first couple of rows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab9357af74eccb795a8f38c079fcce00/href">https://medium.com/media/ab9357af74eccb795a8f38c079fcce00/href</a></iframe><p>We can see that the dataset contains five columns. The first four columns are lengths and widths of iris flower parts, and the last column contains the species label. Consequently, the first four columns contain input variables, and the last one is the output parameter of interest.</p><p>We can also plot the data in order to see how well the species are separated based on the flower characteristics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a3c9384fa41a58c414cb60cbc1bc76/href">https://medium.com/media/c5a3c9384fa41a58c414cb60cbc1bc76/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*X9TQEP4PLuM-uxEsyRzj0g.png" /><figcaption>Distribution of iris flower species based on the dimensions of their petals.</figcaption></figure><p>The graph clearly shows that the species are well separated based on the dimensions of their petals. There is only a small overlap between the versicolor and virginica species. Based on these insights, we expect that our classifier shouldn’t have a hard time figuring out the correct classes.</p><h4>Applying the algorithm to the data</h4><p>Following the algorithm recipe laid out in the previous section, we first have to scale the data and split it into a training and testing dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ed81548e23e96a708be1ff2d80c409d/href">https://medium.com/media/5ed81548e23e96a708be1ff2d80c409d/href</a></iframe><p>To create the model, we will use the knn function from the class library. The first four arguments to the function are the most important. They are the training set, testing set, training set labels, the k parameter (the number of neighbors to take into account while performing classification), respectively. The function returns the predicted labels for the test dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/291b421038976f8d5732bb5a21db37b7/href">https://medium.com/media/291b421038976f8d5732bb5a21db37b7/href</a></iframe><p>Let’s now check how accurate was our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f36e15fa1a65a0df47bf6d7eecc9fcd/href">https://medium.com/media/7f36e15fa1a65a0df47bf6d7eecc9fcd/href</a></iframe><p>The obtained accuracy is great. We have only made three mistakes. However, this result was expected since the iris species are quite different with respect to their physical characteristics. Consequently, the groups don’t overlap very much, so the classifier had an easy job. Moreover, as expected from the above graph, the setosa species was classified perfectly, and the mistakes were made only for the two overlapping species. The datasets encountered “in the wild” will usually be much more complex and noisy, so the accuracy will most often be lower as well.</p><p>[1] E. Fix i J. Hodges: “An important contribution to nonparametric discriminant analysis and density estimation”, International Statistical Review 3.57 (1951), p. 233–238.</p><p>[2] Bernard W. Silverman i M. Christopher Jones: “E. Fix and J.L. hodges (1951): An important contribution to nonparametric discriminant analysis and density estimation:Commentary on Fix and Hodges (1951)”, International Statistical Review/Revue Internationale de Statistique (1989), p. 233–238.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d62b31eb58fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>