<?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 Francisco Suárez Salas on Medium]]></title>
        <description><![CDATA[Stories by Francisco Suárez Salas on Medium]]></description>
        <link>https://medium.com/@francisco-ss?source=rss-5601e7c446d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wU09-_HbRyj-BJrtGm5qLQ.png</url>
            <title>Stories by Francisco Suárez Salas on Medium</title>
            <link>https://medium.com/@francisco-ss?source=rss-5601e7c446d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:43:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@francisco-ss/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 plot Likert scales with a weighted survey in a dplyr friendly way]]></title>
            <link>https://medium.com/data-science/how-to-plot-likert-scales-with-a-weighted-survey-in-a-dplyr-friendly-way-68df600881a?source=rss-5601e7c446d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68df600881a</guid>
            <category><![CDATA[likert-scale]]></category>
            <category><![CDATA[surveys]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Francisco Suárez Salas]]></dc:creator>
            <pubDate>Sun, 03 May 2020 22:25:51 GMT</pubDate>
            <atom:updated>2020-05-05T18:35:07.685Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked with Likert scale visualizations in R, probably you know the Likert <a href="https://github.com/jbryer/likert">package</a> by Jason Bryer. Although this is a wonderful package, its capabilities when working with weighted surveys are limited. When looking for a workaround, I found this <a href="http://rnotr.com/likert/ggplot/barometer/likert-plots/">great post</a> that explained the process but using a lot of base R functions that weren’t quite familiar to me. Finally, I managed to replicate the process in a <a href="https://dplyr.tidyverse.org/">dplyr</a> friendly way that fitted into my workflow and thought that it could be useful to other R users facing the same issue. Here I will guide you through the whole process.</p><h4>Data</h4><p>To make this a very general case, let’s generate some random data that you could find in a weighted survey. Our data frame will have an id for each respondent, their answer for 5 different questions on a Likert scale, a letter indicating the group they represent, and finally, the weight assigned to each respondent.</p><pre>library(tidyverse)</pre><pre>n_sample &lt;- 100</pre><pre>sample_data &lt;- tibble(<br>  id = seq(1, n_sample, 1),<br>  q1 = sample.int(5, n_sample, replace = TRUE),<br>  q2 = sample.int(5, n_sample, replace = TRUE),<br>  q3 = sample.int(5, n_sample, replace = TRUE),<br>  q4 = sample.int(5, n_sample, replace = TRUE),<br>  q5 = sample.int(5, n_sample, replace = TRUE),<br>  group = sample(c(&quot;A&quot;,&quot;B&quot;), n_sample, replace = TRUE),<br>  weight = runif(n_sample, 1, 3)<br>)</pre><h4>Getting the weighted results</h4><p>Our main goal here is to get our results weighted (or else we would be using the Likert package directly). To do this, you can use the super useful <a href="http://r-survey.r-forge.r-project.org/survey/">survey package</a> that provides you with a lot of tools for working with survey data. This package is not that compatible with the tidyverse tools that I normally use, but luckily we can use the <a href="https://github.com/gergness/srvyr">srvyr package</a>, that allows us to work with the survey package functions using dplyr syntax.</p><p>First, we are going to transform our data into a survey object. Then we will define a function that extracts the weighted results for a single question, and finally, we will be applying this function to get the results for each of our questions.</p><pre>library(srvyr)</pre><pre># Tranform sample data into survey data<br>survey_data &lt;- sample_data %&gt;%<br>  as_survey_design(id = 1,<br>                   weights = weight)</pre><pre># Function that gets the weighted frequency of answers for a single question<br>get_weighted_results &lt;- function(q, survey_data){<br>  survey_data %&gt;%<br>    group_by(group) %&gt;%<br>    summarize(a = survey_total(get(q) == 1),<br>              b = survey_total(get(q) == 2),<br>              c = survey_total(get(q) == 3),<br>              d = survey_total(get(q) == 4),<br>              e = survey_total(get(q) == 5)) %&gt;%<br>    pivot_longer(-group,<br>                 names_to = &quot;ans&quot;,<br>                 values_to = &quot;freq&quot;) %&gt;%<br>    filter(!str_detect(ans, &quot;se&quot;)) <br>}</pre><pre># Apply function to each question and calculate proportion<br>likert_results &lt;- tibble(q = c(&quot;q1&quot;, &quot;q2&quot;, &quot;q3&quot;, &quot;q4&quot;, &quot;q5&quot;)) %&gt;%<br>  mutate(results = map(q, get_weighted_results, survey_data)) %&gt;%<br>  unnest(results) %&gt;%<br>  group_by(q, group) %&gt;%<br>  mutate(prop = freq / sum(freq)) %&gt;%<br>  ungroup()</pre><p>Let’s take a moment to study what our new function does:</p><ol><li>Takes your survey data and groups it by a predefined variable. I’m assuming here that you have a grouping variable: if you don’t, just ignore this step.</li><li>Summarizes to get the weighted frequencies for each possible answer on a Likert scale. Note that I’m saving each answer in a different letter. We will translate these letters into text later on.</li><li>Pivots our data frame to a tidy format. This will be helpful when we start plotting with ggplot2.</li><li>Filters rows containing “se”. By default, the survey_total function will also return the standard error of the total. We won’t use it here, but you can leave it if needed.</li></ol><p>Then, we create a new data frame from scratch, with a column containing the variable names of our Likert questions. We apply our function to this column, unnest the results, and calculate the proportion that we will be plotting. You should get a data frame that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Ak42u5xCwN8nNqnkVUQutQ.png" /><figcaption>The tidy data frame that we will plot should look like this</figcaption></figure><h4>Making our plotting function</h4><p>In my case, I had a lot of Likert scale questions to show in different groupings, so I figured that the most convenient solution was to make a function that plotted whichever questions I needed. The function turned out quite long, but don’t be afraid of it, I will guide you through it step by step. Let’s take a look at it.</p><pre>plot_weighted_likert &lt;- function(x, my_labels, likert_results) {<br>  # Filter data for questions needed<br>  likert_results2 &lt;- likert_results %&gt;%<br>    filter(q %in% x)<br>  # Create data frame with labels<br>  prop_labels &lt;- likert_results2 %&gt;%<br>    mutate(<br>      position = case_when(<br>        ans == &quot;a&quot; | ans == &quot;b&quot; ~ &quot;left&quot;,<br>        ans == &quot;c&quot; ~ &quot;center&quot;,<br>        ans == &quot;d&quot; | ans == &quot;e&quot; ~ &quot;right&quot;<br>      )<br>    ) %&gt;%<br>    group_by(q, group, position) %&gt;%<br>    summarize(label = sum(prop * 100)) %&gt;%<br>    pivot_wider(names_from = position,<br>                values_from = label)<br>  # Data frame with right side values<br>  high_columns &lt;- likert_results2 %&gt;%<br>    filter(ans == &quot;c&quot; | ans == &quot;d&quot; | ans == &quot;e&quot;) %&gt;%<br>    mutate(prop = case_when(ans == &quot;c&quot; ~ prop / 2 * 100,<br>                            ans == &quot;d&quot; ~ prop * 100,<br>                            ans == &quot;e&quot; ~ prop * 100,)) %&gt;%<br>    arrange(ans)<br>  # Data frame with left side values<br>  low_columns &lt;- likert_results2 %&gt;%<br>    filter(ans == &quot;a&quot; | ans == &quot;b&quot; | ans == &quot;c&quot;) %&gt;%<br>    mutate(prop = case_when(ans == &quot;a&quot; ~ prop * 100,<br>                            ans == &quot;b&quot; ~ prop * 100,<br>                            ans == &quot;c&quot; ~ prop / 2 * 100)) %&gt;%<br>    arrange(ans)<br>  # Define empty ggplot object<br>  p &lt;- ggplot() +<br>    # Add central black line<br>    geom_hline(yintercept = 0) +<br>    # Add right side columns<br>    geom_bar(<br>      data = high_columns,<br>      mapping = aes(x = group,<br>                    y = prop,<br>                    fill = ans),<br>      position = position_stack(reverse = TRUE),<br>      stat = &quot;identity&quot;<br>    ) +<br>    # Add left side columns<br>    geom_bar(<br>      data = low_columns,<br>      mapping = aes(x = group,<br>                    y = -prop,<br>                    fill = ans),<br>      position = &quot;stack&quot;,<br>      stat = &quot;identity&quot;<br>    ) +<br>    # Left side labels<br>    geom_text(<br>      data = prop_labels,<br>      mapping = aes(<br>        x = group,<br>        y = -100,<br>        label = paste(round(left) , &quot;%&quot;, sep = &quot;&quot;)),<br>        hjust = 1,<br>        color = &quot;black&quot;,<br>        size = 3<br>    ) +<br>    # Central labels<br>    geom_text(<br>      data = prop_labels,<br>      mapping = aes(<br>        x = group,<br>        y = 0,<br>        label = paste(round(center) , &quot;%&quot;, sep = &quot;&quot;)),<br>        hjust = 0.5,<br>        color = &quot;black&quot;,<br>        size = 3<br>    ) +<br>    # Right side labels<br>    geom_text(<br>      data = prop_labels,<br>      mapping = aes(<br>        x = group,<br>        y = 100,<br>        label = paste(round(right) , &quot;%&quot;, sep = &quot;&quot;)),<br>        hjust = -0.2,<br>        color = &quot;black&quot;,<br>        size = 3<br>    )  +<br>    # Scale formatting<br>    scale_y_continuous(<br>      breaks = seq(-100, 100, 50),<br>      limits = c(-105, 105),<br>      labels = abs<br>    )  +<br>    # More formatting<br>    theme(legend.title = element_blank(),<br>          legend.position = &quot;bottom&quot;,<br>          axis.ticks = element_blank(),<br>          strip.background = element_rect(fill = &quot;#F0F0F0&quot;,<br>                                          color = &quot;#F0F0F0&quot;),<br>          panel.background = element_blank(),<br>          panel.border = element_rect(<br>            colour = &quot;#F0F0F0&quot;,<br>            fill = NA,<br>            size = 1.5)<br>          ) +<br>    facet_wrap(~ q, ncol = 1) +<br>    coord_flip() +<br>    ylab(&quot;Proportion&quot;) +<br>    xlab(&quot;&quot;) +<br>    # Change Likert labels<br>    scale_fill_discrete(labels = my_labels)<br>  # Print the plot<br>  p<br>}</pre><p>Ok, so, what are we doing here?</p><ol><li>Our function will take a character vector with the name of the questions that we want to plot, another character vector containing the labels of our Likert scale, and the data frame we had created.</li><li>The first step is to filter the data frame because we are just interested in a given set of questions.</li><li>We then calculate the labels that will go on the left, center, and right side of our plot. As in the original Likert package, on each side, we want to show the percentage of extreme answers. For this reason, we create a new column named position (left, right, or center), calculate the sum of the proportions for each position, and finally, pivot the data frame into a wider format so it’s easier to use.</li><li>Now we will prepare two new data frames to be plotted, which will contain the lower and higher values separately The central value will be divided by two and each half will go in one of these data frames. We have to arrange each data frame by the `ans` column, so values are stacked properly in our plot.</li><li>We are ready to start plotting. To start, we create an empty ggplot object and add our central line.</li><li>Then we add two geom_bar , for our left and right columns. Note two things here: for the left-side values, we are plotting -value as our y aesthetic, and we are specifying position_stack(reverse = TRUE) in the right-side bars so they stack in our desired order.</li><li>We then add three geom_text to plot our percentage labels. As our labels are currently decimal numbers, we round them and paste them with a percentage sign. For the hjust parameters, I just went along with the default values in the original Likert package.</li><li>Next, we give formatting to our y scale. Here I pass the abs function in thelabels parameters so our labels go from 100 to 0 to 100.</li><li>Then I do some more formatting with theme. In this case, I went for a panel border a little different than the original, because I liked it better. After that, I add the faceting, flip the scales, add labels,</li><li>Finally, I add a scale_fill_discrete to change my “a, b, c, d, e” labels to the desired ones.</li></ol><h4>Results</h4><p>Let’s see some examples of the resulting Likert plots. (Don’t forget to define a labels object, as there is no default one in the function).</p><pre>my_labels &lt;- c(&quot;Very\nunsatisfied&quot;,<br>               &quot;Unsatisfied&quot;,<br>               &quot;Neutral&quot;,<br>               &quot;Satisfied&quot;,<br>               &quot;Very\nsatistifed&quot;)</pre><pre>plot_weighted_likert(c(&quot;q1&quot;), my_labels, likert_results)<br>plot_weighted_likert(c(&quot;q2&quot;, &quot;q3&quot;, &quot;q4&quot;), my_labels, likert_results)<br>plot_weighted_likert(c(&quot;q1&quot;, &quot;q2&quot;, &quot;q3&quot;, &quot;q4&quot;, &quot;q5&quot;), my_labels, likert_results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsFhxb02YwI55TxjtqH8HQ.png" /><figcaption>A plot of just one question</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qd5MeBkrtw_OYzZyYNOC7w.png" /><figcaption>A plot of three questions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESP_vkq8WTrCYw9u7JTcJQ.png" /><figcaption>A plot of five questions</figcaption></figure><p>And that’s it! I hope this has been helpful and let me know if you have any doubts.</p><h4>Some refinements</h4><p>There could be some refinements that you may need to do to your plots that I did not cover here. I’ll address these issues briefly:</p><ul><li>Personalized colors. To do this, replace the scale_fill_discrete for a scale_fill_manual , keep the labels parameter and add a 5 color vector to the values parameter.</li><li>Groups order. In our resulting plots, we got group B plotted above group A. To define the order in which groups will be plotted, you can mutate your group column using the factor function and specifying the order of the groups.</li><li>Questions labels. The simplest way here is to make your q column contain the question text. In this way, the function will keep working as intended. You can also add a new text column that contains the question text. If you do this, you will have to modify the function so it uses text as a variable instead of q when needed.</li><li>Questions order. When plotting questions text, your questions may be shown in a different order than expected. To account for this issue, you could create a text_order vector that contains the questions in the order that you need them to be shown, and mutate the text column in the likert_results2 data frame (inside the function, after you filter it) with the factor function and passing this vector.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68df600881a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-plot-likert-scales-with-a-weighted-survey-in-a-dplyr-friendly-way-68df600881a">How to plot Likert scales with a weighted survey in a dplyr friendly way</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>
    </channel>
</rss>