<?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 Darnel Bolaños on Medium]]></title>
        <description><![CDATA[Stories by Darnel Bolaños on Medium]]></description>
        <link>https://medium.com/@darnelbolaos?source=rss-a97ac3f6a351------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e3wUSzO0TsAdTyuqfmLG4Q.png</url>
            <title>Stories by Darnel Bolaños on Medium</title>
            <link>https://medium.com/@darnelbolaos?source=rss-a97ac3f6a351------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:21:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darnelbolaos/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[Deviation from Average plot with Power BI core visuals]]></title>
            <link>https://medium.com/@darnelbolaos/deviation-from-average-plot-with-power-bi-core-visuals-a97d3ddfa4ac?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/a97d3ddfa4ac</guid>
            <category><![CDATA[power-bi-tutorials]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-visualization-tools]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[power-bi-step-by-step]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 20:50:28 GMT</pubDate>
            <atom:updated>2025-03-09T02:21:39.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*E2lp9vcBXod-t8wMaf3_cg.png" /></figure><p>In my job I was asked if I could create a plot for a HR dashboard that showed the average of the hiring time for all positions and how much the indiviual average time deviates from the general average. The HR manager wanted to know which positions were the more time-consuming to stablish a more realistic time to the hiring managers.</p><p>The data at the end of the transformations looked like this (this is a made-up data sample that I created).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*jMxgQrc7DWz7o3hgyZeiIg.png" /></figure><p>My first approach was to make something very simple. Calculate the measures for general average as a constant line and the put some bars with the average of every category.</p><pre>Avg value = CEILING(AVERAGE(Test[Time]), 1)<br><br>Avg value all = <br>VAR output =<br>CALCULATE(<br>    [Avg value],<br>    ALLSELECTED()<br>)<br>RETURN<br>CEILING(output, 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*7tq1Nl56vzVu9uAO_uKM4A.png" /></figure><p>But then I realised that with this the HR manager would spend some time making the substraction between the average value and the general average to get how much deviation has the position. So this visualization wasn’t fullfiling all the objetives.</p><p>So I came across with the deviation plot and I really liked it for this purpose, because I could make that the bars’s origin was the general average and reach the actual average value; so the length of the line will mark how much the value was deviated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*jnEOOeQC16hY4a608_6fSA.png" /></figure><p>Nevertheless Power BI has the disavantage that its core visualizations are very simple and to make a non-normal plot you must to take some workarounds.</p><p>The first step was to get rid of the bars, so I put the transparency to 100%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*1tZV-JjwePLM6SkJ1aPZ4w.png" /></figure><p>Then went to Analytics Pane and enabled the Error bars. In the Upper bound I put the “Avg value” and in the Lower Bound I put the “Avg value all”. I choose the color #D64550 and put the Markers and a point with Size 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*gzNajk7n00mpggWvZVgWjQ.png" /></figure><p>And finally activate the data labels. The results was this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*BG1nWYgs2sZu8N-YdOeyTA.png" /></figure><p>Not bad but looks weird. This is because the x-axis starts on 0 so the scale of the line are pretty ugly. So I made two measures to adapt the axis to the values.</p><pre>Min plot = <br>MINX(<br>    SUMMARIZE(<br>        Test,<br>        Test[Category],<br>        &quot;Avg&quot;, [Avg value]<br>    ),<br>    [Avg]<br>) * 0.90<br><br>Max plot = <br>MAXX(<br>    SUMMARIZE(<br>        Test,<br>        Test[Category],<br>        &quot;Avg&quot;, [Avg value]<br>    ),<br>    [Avg]<br>) * 1.10</pre><p>And I put it on the x-axis to the min and max value respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*Md8NV8F1surVVQ63XqTHZg.png" /></figure><p>It looks much better! But I didn’t solve the inconvenience that the HR manager made the substraction between the general average and the other average. So I came out with the personalized data labels and put the position option as “Inside Base” so don’t overlap with the lines.</p><pre>Label Bar plot = <br>VAR resta = [Avg value] - [Avg value all]<br>VAR signo = IF(resta &gt; 0, &quot;+&quot;, &quot;&quot;)<br>RETURN<br>[Avg value] &amp; &quot; (&quot; &amp; signo &amp; resta &amp;&quot;)&quot; </pre><p>And finally it looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*1-PE9Uq9aBlsr2J0YF4_DQ.png" /></figure><p>I hope you try it some day and let me know how it went. Thanks if you read it till here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a97d3ddfa4ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve the interactivity in a plot with emojis (with R)]]></title>
            <link>https://medium.com/@darnelbolaos/how-to-improve-the-interactivity-in-a-plot-with-emojis-with-r-4d020ff4e85e?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d020ff4e85e</guid>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[shiny]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[emoji]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 02:23:47 GMT</pubDate>
            <atom:updated>2022-08-04T02:23:47.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVOOVTlPKZYc_LgOr6RzGg.png" /><figcaption>Histograms with informative emojis</figcaption></figure><p>We all have had been through this situation where our dashboard, the one in which we invest a lot of time, is ignored across the organization and someone says the infamous sentence: ‘how can I export it to Excel?’. We try to understand what went wrong? Well, sometimes the answer is simpler than we think: our design is non-interactive.</p><p>I know, is weird to say that about a dashboard, but the interactivity doesn’t come only from filters; we also have to consider that the information given by the plots in every unique scenario, be quickly interpreted by the user and <em>ease</em> its mental processing and search for answers.</p><p>Imagine a typical sales dashboard like this -that has many flaws in data visualization, but that’s another subject-:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3XTRKvG_ylXAh1KdO_xVA.jpeg" /><figcaption>Source: <a href="https://www.solverglobal.com/es/glosario-de-plantillas-de-informes-presupuestos-previsiones-y-dashboards/dashboard-de-ventas/">https://www.solverglobal.com/es/glosario-de-plantillas-de-informes-presupuestos-previsiones-y-dashboards/dashboard-de-ventas/</a></figcaption></figure><p>As you can see in the figure, the visuals don’t have any help to the user and rely all the interpretation on him/her. Then it’s probable that the user falls down in this loop for <strong><em>every </em></strong>plot:</p><ul><li>establish a scenario with filters,</li><li>read the results (labels, numbers, trends),</li><li>some mental process to interpret them,</li><li>compare mentally with its objectives,</li><li>… and repeat.</li></ul><p>This is time-consuming and exhausting!</p><p>Place a visual should not be treated as the answer but as a complement. We must <em>guide </em>the user to find the answers <strong>faster than the time he/she spends creating a pivot table in Excel</strong>. That’s why storytelling and good practices in data viz are so important.</p><p>Here I am going to use simple emojis (‘x’ and ‘check’) into a ggplot viz to interpret faster the dynamic results of a dashboard and make a decision.</p><p>I built a <a href="https://oufoi8-darnel-bola0os.shinyapps.io/Cheating_game/">Shiny app</a> to play a game based on a <a href="https://www.youtube.com/watch?v=XTcP4oo4JI4&amp;t=141s">Primer’s video</a> about Frequentist Hypothesis Testing. It’s a game where you can try to catch a cheater in a flip-a-coin game (<em>I recommend watch the video to understand everything behind the game</em>). But basically is that you act like a referee and have to judge the participants based on the number of heads they got.</p><p>And how we would do that? Easy! We will have 2 histograms with the theoretical probability distributions, one for clean and one for cheaters. Each plot has two slicers that affect them <em>dynamically</em>: limits and threshold.</p><ul><li><strong>Limits:</strong> The tolerance level for False Positives (when we accuse a clean player) and True Positives (when we catch a cheater), respectively.</li><li><strong>Threshold:</strong> Moves a vertical line inside the plots to cutoff the distributions in the same number of heads. With it, we could see how many data there are before and after the threshold.</li></ul><p>Now, imagine you just place your histograms and the threshold and let the user interpret the plot. Of course, it could notice a good portion of TP and a low portion of FP, but is within the limits? The visualization doesn’t provide that information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*V9p8dIB0kBf2D-fDPdqzJw.png" /></figure><p>Here is when we could use the emojis. Every time the user changes the limits (maybe wants them to be more flexible or rigorous) or changes the threshold, the emoji tells it quickly if the probability is within the limits or not without it needing to read every single time the plot.</p><p>You can also place the text as I did, but it’s unnecessary for some normal contexts (and not the game presented here).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F734899677%3Fh%3D6a447280a9%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F734899677&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1478677306-055b56fe4e550a71c5284c0fb8ae477c340042d65fea086846ec316198d1c441-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1894" height="898" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddf353189146f71fd0e7a0811aafe6b/href">https://medium.com/media/4ddf353189146f71fd0e7a0811aafe6b/href</a></iframe><p>Here is the code for the static visualization:</p><pre>library(tidyverse)<br>library(ggthemes)</pre><pre>n_throws &lt;- 23<br>prob_cheat &lt;- 0.75<br>threshold &lt;- 15<br>limit_FP &lt;- 0.05<br>limit_TP &lt;- 0.8</pre><pre>data &lt;- tibble(head = rep(0:n_throws, 2),<br>               prob = c(dbinom(seq(0, n_throws),<br>                               n_throws, prob = 0.5),<br>                        dbinom(seq(0, n_throws),<br>                               n_throws,<br>                               prob = prob_cheat)),<br>               cond = c(rep(c(&quot;clean&quot;),<br>                            n_throws + 1),<br>                        rep(c(&quot;cheat&quot;), n_throws + 1))) %&gt;% <br>  mutate(cond = factor(cond,<br>                       levels = c(&quot;clean&quot;, &quot;cheat&quot;)))</pre><pre>pos &lt;- data %&gt;% <br>  summarise(head = max(head) / 4,<br>            prob = 0.9 * max(prob))</pre><pre>metrics &lt;- data %&gt;% <br>  filter(head &gt;= threshold) %&gt;% <br>  group_by(cond) %&gt;% <br>  summarise(s = sum(prob)) %&gt;%<br>  ungroup() %&gt;% <br>  mutate(head = pos$head,<br>         prob = pos$prob,<br>         text = paste0(ifelse(cond == &quot;cheat&quot;, <br>                              &quot;True positives \n&quot;, <br>                              &quot;False positives \n&quot;),<br>                       round(s * 100, 2), &quot;%&quot;),<br>         emoji = ifelse((cond == &quot;cheat&quot; &amp; s &gt; limit_TP) | (cond == &quot;clean&quot; &amp; s &lt; limit_FP),<br>                        emo::ji(&quot;white_check_mark&quot;),<br>                        emo::ji(&quot;x&quot;))<br>  )</pre><pre>ggplot(data, aes(x = head, y = prob, fill = cond)) +<br>  geom_col(alpha = 0.2) +<br>  geom_line(aes(color = cond), size = 1) +<br>  geom_vline(xintercept = threshold,<br>             linetype = &quot;dashed&quot;, color = &quot;gray50&quot;,<br>             size = 1) +<br>  geom_text(data = metrics,<br>            aes(label = text, color = cond), size = 4) +<br>  geom_text(data = metrics,<br>            aes(x = head * 0.12, label = emoji), size = 9,<br>            color = ifelse(metrics$emoji == emo::ji(&quot;x&quot;),<br>                           &quot;darkred&quot;, &quot;darkgreen&quot;),<br>            family = &quot;EmojiOne&quot;) +<br>  labs(x = &quot;Number of heads&quot;,<br>       y = &quot;Likelihood&quot;,<br>       title = paste(&quot;Threshold =&quot;, threshold)) +<br>  theme_light() +<br>  scale_fill_stata() +<br>  scale_color_stata() +<br>  facet_wrap(~cond) +<br>  theme(<br>    panel.grid = element_blank(),<br>    legend.position = &quot;none&quot;,<br>    strip.background = element_rect(fill = &quot;white&quot;),<br>    strip.text = element_text(color = &quot;gray60&quot;),<br>    axis.ticks = element_line(color = &quot;gray60&quot;, size = 0.15),<br>    axis.ticks.length = unit(5, &quot;pt&quot;),<br>    axis.text = element_text(color = &quot;gray60&quot;),<br>    axis.title = element_text(color = &quot;gray40&quot;)<br>  )</pre><p>So I hope you include some emojis in your future visualizations and improve the interactivity with the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d020ff4e85e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning to predict our wins on Brawlhalla — Part Two: Predictive Analysis (with…]]></title>
            <link>https://medium.com/@darnelbolaos/machine-learning-to-predict-our-wins-on-brawlhalla-part-two-predictive-analysis-with-ceeae29814a0?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceeae29814a0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tidymodels]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 01:52:52 GMT</pubDate>
            <atom:updated>2022-03-15T14:35:38.543Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine learning to predict our wins on Brawlhalla — Part Two: Predictive Analysis (with R-tidymodels)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbY-v4nYQSVY3-GH691nDg.jpeg" /><figcaption>Koji from Brawlhalla (my favorite character). Source: <a href="https://www.brawlhalla.com/wallpapers/">https://www.brawlhalla.com/wallpapers/</a></figcaption></figure><p>I’m a data analyst, not a data scientist, but lately, I’ve been reading about Machine Learning algorithms theory and its implementation in R, and I wanted to try it. Then… I tried to build an ML model to predict the probability of winning for my sister and me in Brawlhalla Ranked 2v2.</p><p>I didn’t get the expected results and failed (but learning), so if you have any recommendations for a beginner to improve this model, <em>I will appreciate it!</em> This article is the continuation of the Descriptive Analysis:</p><p><a href="https://medium.com/mlearning-ai/machine-learning-to-predict-our-wins-on-brawlhalla-part-one-descriptive-analysis-with-r-61fdca6635b1">Machine learning to predict our wins on Brawlhalla — Part One: Descriptive Analysis (with R)</a></p><h3>Data transformation</h3><p>The original data is the same as in the previous article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*cw78smVMlG9amli1Q0Crgg.png" /></figure><p>The aim is to predict based on the information in pre-match features (characters and color chosen by us, stage and enemies characters); the KO’s and Hits don’t apply, cause that’s information after-match. The objective variable is pretty balance: 0 = 318 and 1 = 320.</p><p>Our team is taken as one variable instead of the individual character. When we achieve a Rating greater than 1389 the “league” is Gold and below from 1389 is Silver. Every categorical feature has too many unique values, hence I lump many of them, considering using dummy variables in the future and not ending with a thousand columns dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*d8YOfKMcVf9D7es7ZQ82Iw.png" /><figcaption>Unique values in every column from the original dataset</figcaption></figure><p>The last transformation is to combine Enemy_1 and Enemy_2 but it can be the same way as team because here doesn’t matter the order, then I used a <a href="https://medium.com/@darnelbolaos/target-encoding-function-with-r-8a037b219fb7">target encoding function</a> for each column and calculate the harmonic mean.</p><pre>set.seed(123)<br>brawlhalla_clean &lt;- brawlhalla %&gt;% <br>  mutate(team = paste0(Ch_D, &quot;-&quot;, Ch_S),<br>         team = fct_lump_n(team, 7, other_level = &quot;Other&quot;),<br>         Rating = ifelse(Rating &lt;= 1389, &quot;Silver&quot;, &quot;Gold&quot;),<br>         Color = fct_lump_min(Color, 30, other_level = &quot;Other&quot;),<br>         Stage = fct_lump_min(Stage, 32, other_level = &quot;Other&quot;),<br>         k = sample(1:5, nrow(brawlhalla), replace = TRUE)) %&gt;% <br>  select(-starts_with(c(&quot;KO&quot;, &quot;Hit&quot;, &quot;Ch&quot;)))</pre><pre>#Creating a dataframe of enemies and lumping below 2%<br>most_freq_enemies2 &lt;- data.frame(<br>  enemy = c(brawlhalla_clean$Enemy_1,<br>            brawlhalla_clean$Enemy_2),<br>  win = rep(brawlhalla_clean$Win, 2),<br>  k = rep(brawlhalla_clean$k, 2)<br>) %&gt;% <br>  mutate(enemy = fct_lump_prop(enemy, 0.02,<br>                               other_level = &quot;Other_ch&quot;))</pre><pre>#Target encoding from enemies<br>tar_enc_enemies &lt;- target_enc(data = most_freq_enemies2,<br>                              enc_col = &quot;enemy&quot;, tar_col = &quot;win&quot;,<br>                              k_col = &quot;k&quot;, kmin = 1, kmax = 5)</pre><pre>brawlhalla_clean &lt;- brawlhalla_clean %&gt;% <br>  mutate(Enemy_1 = ifelse(Enemy_1 %in% tar_enc_enemies$enemy,<br>                          Enemy_1, &quot;Other_ch&quot;),<br>         Enemy_2 = ifelse(Enemy_2 %in% tar_enc_enemies$enemy,<br>                          Enemy_2, &quot;Other_ch&quot;))</pre><pre>#Joining the enemies to final dataset for ML<br>brawlhalla_ML &lt;- brawlhalla_clean %&gt;%<br>  left_join(tar_enc_enemies, by = c(&quot;Enemy_1&quot; = &quot;enemy&quot;)) %&gt;% <br>  rename(Enemy_1_tar = tar_enc_enemy) %&gt;% <br>  left_join(tar_enc_enemies, by = c(&quot;Enemy_2&quot; = &quot;enemy&quot;)) %&gt;% <br>  rename(Enemy_2_tar = tar_enc_enemy) %&gt;% <br>  mutate(Enemy_mean = <br>    (2 * Enemy_1_tar * Enemy_2_tar) / (Enemy_1_tar + Enemy_2_tar)<br>  ) %&gt;% <br>  select(-c(Enemy_1_tar, Enemy_2_tar, <br>            Enemy_1, Enemy_2,<br>            k)) %&gt;% <br>  mutate(Rating = factor(Rating),<br>         Win = factor(Win))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*Lb7tyOxIv0N7B7jbuS1rnQ.png" /><figcaption>Final dataset for ML algorithm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*YDx55Z6Ni5o3WYt0XzdSLw.png" /><figcaption>Unique values in every column from final dataset</figcaption></figure><h3>Splitting dataset</h3><p>After the initial split (75% training), I introduce some noise into the Enemy_mean on training dataset to avoid overfitting due to data leakage.</p><pre>set.seed(684)<br>brawlhalla_split &lt;- initial_split(brawlhalla_ML, strata = Win)<br>brawlhalla_train &lt;- training(brawlhalla_split)<br>brawlhalla_test &lt;- testing(brawlhalla_split)</pre><pre>Enemy_train_vect &lt;- brawlhalla_train %&gt;% <br>  pull(Enemy_mean)</pre><pre>noise_limit &lt;- (max(Enemy_train_vect) - min(Enemy_train_vect)) * 0.3</pre><pre>set.seed(1919)<br>brawlhalla_train &lt;- brawlhalla_train %&gt;% <br>  mutate(noise = runif(nrow(.), -noise_limit, noise_limit),<br>         Enemy_mean = Enemy_mean + noise) %&gt;% <br>  select(-noise)</pre><h3>Tuning hyperparameters</h3><p>I used random forest, which is one I know best than others more complex like ‘support vector machine’ or ‘neural networks’. In the validation dataset, I went with bootstrap technique with 30 folds.</p><p>The parameters mtry (quantity of features randomly selected by the algorithm to use in the trees) and min_n (number of data points required in the node before split) were tuned. The number of trees is fixed to 500. The first grid was generic using 20 combinations.</p><pre>set.seed(1313)<br>brawlhalla_folds &lt;- bootstraps(brawlhalla_train,<br>                               strata = Win, times = 30)</pre><pre>#recipe definition<br>brawlhalla_rec &lt;- recipe(Win ~., data = brawlhalla_train) %&gt;% <br>  step_dummy(all_nominal_predictors())</pre><pre>#model definition<br>rand_spec &lt;- rand_forest(mtry = tune(),<br>                         min_n = tune(),<br>                         trees = 500) %&gt;% <br>  set_mode(&quot;classification&quot;) %&gt;% <br>  set_engine(&quot;ranger&quot;)</pre><pre>#workflow definition<br>brawlhalla_wf &lt;- workflow() %&gt;% <br>  add_recipe(brawlhalla_rec) %&gt;% <br>  add_model(rand_spec)</pre><pre>doParallel::registerDoParallel()<br>set.seed(797)<br>rand_rs &lt;- tune_grid(<br>  brawlhalla_wf,<br>  resamples = brawlhalla_folds,<br>  grid = 20,<br>  metrics = metric_set(accuracy, roc_auc)<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*haA8HxFI8KTMuJRG-k0EmQ.png" /><figcaption>Mean accuracy for every hyperparameter after validation</figcaption></figure><p>As you can see, the accuracy is pretty low, hence looking for a little optimization, another grid was built considering that 20 ≤ min_n ≤ 35 and 1 ≤ mtry ≤ 5 have the greater mean values.</p><pre>rf_grid &lt;- grid_regular(mtry(range = c(1, 5)),<br>             min_n(range = c(20, 35)),<br>             levels = 6)</pre><pre>doParallel::registerDoParallel()<br>set.seed(694)<br>regular_rs &lt;- brawlhalla_wf %&gt;%  <br>  tune_grid(resamples = brawlhalla_folds,<br>            grid = rf_grid)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*C_4tlJI7-1lyNFXGR4Ls1g.png" /><figcaption>Accuracy mean values for the hyperparameter optimization</figcaption></figure><p>The accuracy went up a little bit. The hyperparameter mtry = 2 and min_n = 20 gives the maximum accuracy but a low ROC-AUC; I chose mtry = 1 and min_n = 32 cause is a balance between the two metrics.</p><pre>best_tune &lt;- tibble(mtry = 1, min_n = 32)</pre><pre>final_rf &lt;- finalize_model(<br>  rand_spec,<br>  best_tune<br>)</pre><h3>Testing the model</h3><p>With all set up, we can finally test the model with the last_fit function, which trains the model in training dataset and evaluate it in testing dataset, all at once.</p><pre>final_wf &lt;- workflow() %&gt;% <br>  add_recipe(brawlhalla_rec) %&gt;%<br>  add_model(final_rf)</pre><pre>set.seed(857)<br>final_res &lt;- final_wf %&gt;% <br>  last_fit(brawlhalla_split)</pre><pre>final_res %&gt;% <br>  collect_metrics()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*lzGgavyK5yccamn7mB9VHQ.png" /><figcaption>Results of the model in test data</figcaption></figure><p>Well, it could be worse, am I right? In the plot below, we can see the probability given by the model for the test set points in x-axis and the categories of color and team on y-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix0Lij4mxJVklRHjKY664g.png" /></figure><p>The model has a hard time classifying when color is Charged OG or Skyforged, and team in general. This may be due to the many points that have those variables, but the difference between wins and losses is minimal, and it can confuse the model. Gray color, for example, has a pretty huge difference in win-loss (-10) and the model prediction is almost right.</p><p>Also, I think the model is skewed for the low quantity of points. For example, team Zariel-Val is the best one with a win ratio of 70% but it only has 26 points in the entire dataset; then the model predicted all probabilities for that team &gt; 0.5; cause in the training data there were 14 wins and 4 losses.</p><p>Finally, the variable importance (a cool thing of random forest). Thundergard Stadium and Enigma are our best Stage and King Pass our worst, and all are there; Zariel-Val our best team and Goldenforged and Home team our best color. I think the model has the right direction and identifies some patterns but it needs a little push from my data (a.k.a. more data).</p><pre>set.seed(1912)<br>final_rf %&gt;%<br>  set_engine(&quot;ranger&quot;, importance = &quot;permutation&quot;) %&gt;%<br>  fit(Win ~.,<br>      data = juice(prep(brawlhalla_rec))) %&gt;% <br>  vip(geom = &quot;point&quot;) + theme_light()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*FkupA6T5Z61drVcgRW9naQ.png" /></figure><p>In conclusion, I need more points; the dataset has too many categorical variables, which combination doesn’t work as good predictors. Perhaps the model wasn’t that bad, but I’ll keep collecting data and researching with more complex or easier models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceeae29814a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Target encoding function with R]]></title>
            <link>https://medium.com/@darnelbolaos/target-encoding-function-with-r-8a037b219fb7?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a037b219fb7</guid>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 22:22:33 GMT</pubDate>
            <atom:updated>2022-01-09T16:54:30.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbMU3ZAn9uVG5dOmQoa87Q.jpeg" /></figure><p>Humans love words and normally use them to represent and describe data (categorical features). Sadly, ML algorithms don’t share our passion for words, they prefer numbers. That’s why in the preprocessing phase, before we feed our ML model to make predictions, it’s required to encode the categorical features.</p><p>Encode it’s essentially assign a <strong>well-thought</strong> <strong>number</strong> to each category of the feature. There are many methods, the most popular are <em>one-hot-encoding</em> (n categories) and <em>dummy variable</em> (n-1 categories), which create a binary column for every category: 1 if the category it’s present and 0 if not. The problem with those methods comes when there are too many categories in the feature, cause it will create a lot of columns and the majority will be zeros, so this can confuse our model or even slow it down.</p><h3><strong>Target encoding introduction</strong></h3><p>Target encoding is a method that uses the mean value of the output based on each category. For example, the image below shows that the output it’s 1 for 3 out of 4 of the times in category <em>A, </em>so the mean value is 0.75;<em> </em>0.25 in category <em>B, </em>and 0.33 in category C. Comparing with one-hot encoding (ohe) we don’t need three columns (or many more), just one. And that’s a significant advantage of this method, it can handle a lot of categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*-kK1nxGJwAaan5lUpC83fw.png" /><figcaption>Target encoding and one-hot encoding example.</figcaption></figure><p>Easy peasy lemon squeezy, right? Well, there’s a problem. As you can see, the method strictly depends on the target variable, the one we want to predict. This generates a problem known as <em>leakage</em>. Briefly, is when we “give” some interpretation answers (data that it shouldn’t have access to) to the model, so it grabs this advantage and returns outstanding results in the training set, but in the test set and real data, the performance could be bad, driving to overfitting.</p><p>There are multiple approaches to solve or minimize this problem (disclaimer: the sources is where I saw it, not necessarily the original source):</p><ul><li>Time windows [<a href="https://www.amazon.com/_/dp/1491953241?tag=oreilly20-20">Zheng &amp; Casari (2018)</a>]: use an early and independent data batch to compute the target encoding; then use the actual data (another batch) for training with the first batch target encoding and lastly, use the future data for testing. This solution is especially good for production real-time situations but needs a delay to gather the early batch.</li><li>Noise [<a href="https://towardsdatascience.com/a-data-scientists-toolkit-to-encode-categorical-variables-to-numeric-d17ad9fae03f">Dr. Dataman (2019)</a>]: introduce a random noise to the target encoding results so isn’t too precise on the training set. The noise ranges from 0 to a fraction of the target variable. The analyst chooses the fraction value (like a hyperparameter).</li><li>k-validation sets [<a href="https://www.youtube.com/watch?v=2Yx2Y545yBk&amp;list=LL&amp;index=23&amp;t=107s">Thakur (2021)</a>]: assign randomly, to each data point a k-value to create subsets, whatever the quantity you want (5 is a good number). It’s an iterative process and similar to leave-one-out.<br>Create two sets: validation (one subset: k = k_n) and training (other subsets: k != k_n). <br>Target encoding is calculated with the training set and results are left_join with the validation set and then repeats the process for every subset. Finally, use the mean of all of them for each category.</li></ul><p>Thakur’s approach was adopted in the function presented here. But you can implement your favorite or research for more solutions.</p><p>Another slight problem with target encoding is that it needs to be updated frequently if the distribution of the categories changes constantly. For example, in marketing analytics, where the trends and customers&#39; interests change every minute, a delay in updates and subsequently wrong inputs can lead to a loss in profits.</p><h3>The section you came for</h3><p>The data was generated randomly using the LETTERS vector and a binary target feature. Besides, the prob argument was also random, so all categories didn’t have approx the same quantity.</p><pre>set.seed(946) #in case you want the same results</pre><pre>data &lt;- tibble(cat = sample(LETTERS, 6000,<br>                            replace = TRUE,<br>                            prob = rep(runif(26))),<br>               target = sample(c(0, 1), 6000,<br>                               replace = TRUE))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*UpPjDCHFZhxqH1eNryxNeQ.png" /><figcaption>Count for each category.</figcaption></figure><p>Now we create the k-value for each row. I used 5 subsets, but you can use more or less. The prob is uniform cause we want the subsets to have mostly the same data.</p><pre>set.seed(123)<br>data &lt;- data %&gt;% <br>  mutate(k = sample(1:5,<br>                    nrow(.),<br>                    replace = TRUE))<br>head(data, 10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*nHcS8BLdikoASJr44zEdFg.png" /><figcaption>First 10 rows from the dataset with k-sets = 5</figcaption></figure><p>Alright! We set up everything. Now, let’s take a look at the function.</p><p>The function uses tidyverse, so make sure you have it installed [install.packages(“tidyverse”)]. It has 6 arguments:</p><ul><li>data (dataframe or tibble): data that contains all the variables.</li><li>enc_col (string): the column name we want to encode.</li><li>tar_col (string): the column name of the target feature.</li><li>k_col (string): the column name that has the k-sets.</li><li>kmin and kmax (integer): the minimum and maximum of k. It assumes a sequence with a step of 1.</li></ul><p>With map_df we loop through a vector of k’s given by kmin and kmax, map_df returns a dataframe. Split the data in training (xtrain) and validation (xvalid). The target encoding is calculated with xtrain. The results are left_join with xvalid and select the columns we are interest (category and category encoded). The results for every k in loop are store in temp_df.</p><p>Then we compute the last results with the mean of every category and with those results, left_join to the original data.</p><pre>target_enc &lt;- function(data, enc_col, tar_col, k_col,<br>                       kmin, kmax){<br>  require(tidyverse)<br>  col_name &lt;- paste0(&quot;tar_enc_&quot;, enc_col)<br>  <br>  temp &lt;- map_df(kmin:kmax, function(k){<br>      <br>      xtrain &lt;- data[data[k_col] != k, ]<br>      xvalid &lt;- data[data[k_col] == k, ]<br>      <br>      feat &lt;- xtrain %&gt;% group_by_at(enc_col) %&gt;%<br>        summarise_at(.vars = tar_col, mean)<br>      <br>      colnames(feat)[2] &lt;- col_name<br>      temp_df &lt;- xvalid %&gt;% left_join(feat, by = enc_col) %&gt;% <br>        select(all_of(enc_col), all_of(col_name))<br>      <br>      return(temp_df)<br>    })<br>  <br>  temp_enc &lt;- temp %&gt;% group_by_at(enc_col) %&gt;% <br>    summarise_at(.vars = col_name, .funs = mean) %&gt;% <br>    ungroup()<br>  <br>  data %&gt;% left_join(temp_enc, by = enc_col)<br>    <br>}</pre><blockquote><strong><em>Recommendation:</em></strong><em> summarize the rare categories in one category. The target encoding could have meaningless or unbalanced results with categories that appear a few times.</em></blockquote><p>I summarize in one category all the categories with n &lt; 75 before using the function. As you can see, all categories are encoded.</p><pre>data &lt;- data %&gt;% <br>  mutate(cat = fct_lump_min(cat, 75))</pre><pre>target_enc(data = data, enc_col = &quot;cat&quot;,<br>           tar_col = &quot;target&quot;, k_col = &quot;k&quot;,<br>           kmin = 1, kmax = 5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*fg5cvnznTSS22HVfl1k2YQ.png" /><figcaption>First 10 rows from output from function</figcaption></figure><p>If you want to see the encoded value for each category (note some letters disappear and there is a category “Other”):</p><pre>target_enc(data = data, enc_col = &quot;cat&quot;,<br>           tar_col = &quot;target&quot;, k_col = &quot;k&quot;,<br>           kmin = 1, kmax = 5) %&gt;% <br>  distinct(cat, tar_enc_cat) %&gt;%<br>  arrange(cat) %&gt;% View()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*W93RAaCkZtfFKkFnkAj9LQ.png" /><figcaption>Encode value for each category.</figcaption></figure><p>Hurray! We did it. Hope it helps you someday! See you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a037b219fb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning to predict our wins on Brawlhalla — Part One: Descriptive Analysis (with R)]]></title>
            <link>https://medium.com/@darnelbolaos/machine-learning-to-predict-our-wins-on-brawlhalla-part-one-descriptive-analysis-with-r-61fdca6635b1?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/61fdca6635b1</guid>
            <category><![CDATA[brawlhalla]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[rstudio]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 03:42:51 GMT</pubDate>
            <atom:updated>2021-12-20T14:57:07.876Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine learning to predict our wins on Brawlhalla — Part One: Descriptive Analysis (with R)</h3><figure><img alt="Brawlhalla’s poster of Season 4" src="https://cdn-images-1.medium.com/max/600/1*8QJmhMsaOKobulLUJmrsZQ.jpeg" /><figcaption>Brawlhalla’s poster for Season 4.</figcaption></figure><p>If you are a data enthusiast like me, it’s possible that you want to know answers to questions about ordinary situations, so you wake up a random day and start collecting data. This article is about one of those questions that nobody asks, but I wanted to know.</p><p>My sister and I play a video game called Brawlhalla since 3 years ago. The bad news is that even if we have been playing this game for a long time, we strongly <em>believe </em>that we are terrible! But as the famous Edward’s saying goes: “Without data, you’re just another person with an opinion”. Thus, I decided to find, how bad are we? With data!</p><p>The article has two parts:</p><ol><li>Descriptive analysis: Our aim here is to describe the data through visualizations and some discussion.</li><li>Predictive analysis: We are going to build a model that predicts the probability of winning based on variables <em>before</em> a match begins.</li></ol><h4><strong>Introduction</strong></h4><p>Brawlhalla is a 2D platform fighter, free to play for almost every recent platform you can imagine. Over the last years, has won popularity for its multiple <a href="https://www.brawlhalla.com/crossovers/">crossovers of popular character</a>s, constant updates, and… cause it’s truly fun!</p><p>We play Ranked 2V2: a fight mode of us against another 2 players; every character has 3 lives. The couple who wins gains ELO points and the losers, well, lose ELO points. <a href="https://www.youtube.com/watch?v=Tk8ytQ-ri_A">Here</a> is an example. The interesting thing about this mode is that if you’re not careful, you can hit your partner and damage her/him (minute 1:15 from the video above).</p><h4><strong>Data description</strong></h4><p>My sister and I hit each other a lot! Then we proposed a hypothesis:</p><blockquote><strong>We usually lose because the higher the hits, the easier for the opponents to kill us.</strong></blockquote><p>Besides, we also believe that we have colors and stages that give us ‘luck’ and where is easier for us to win. We collect the data for every match we play in 5 months (638 observations):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*gYaJ-gAwWTc0ZcHv88CpeA.png" /><figcaption>Sample of data for Brawlhalla matches.</figcaption></figure><ul><li>Rating: ELO points at beginning of the match.</li><li>Ch_S, Ch_D: Character used by my sister and by me.</li><li>Hit_S, Hit_D: Count of hits against the other.</li><li>KO_S, KO_D: Count of KOs (kill an enemy) each did. Note: sum(KO_S, KO_D) ≤ 6; If sum(KO_S, KO_D) == 6 then Win = 1 cause 6 KOs means we kill 3 times each enemy.</li><li>Color: Color picked for our characters.</li><li>Enemy_1, Enemy_2: Characters used by opponents.</li><li>Stage: The stage of the match (randomly picked by the game)</li><li>Win: 0- lose, 1- win. The data is pretty balanced (mean_win = 0.5016), unfortunately for our skills.</li></ul><h4>Do the hits affect our performance?</h4><p>That’s the big question! The individual performance is given by KOs, even the correlation between sum(KO_S, KO_D) and Win is high (0.709). This means if we get higher KOs, then will get more wins and following our hypothesis, <em>fewer hits, </em>right?</p><p>Well… not. Once again, data proves me wrong -for good-. As the visualization shows, the average of hits increased on the matches we won for both of us and for all KOs values (except when I did 5 KOs).</p><p>Our hypothesis falls apart even more on my sister’s data, cause she actually has better performance if she hits me more. My data, when we won, follows the expected behavior since the average of hits tends to decrease with a good performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4P3Y4Ed7GLQ6EuvdgJILw.png" /></figure><h4>There are lucky colors or stages?</h4><p>We have our favorite colors (Home Team, Soul Fire, Charged OG, and Gray). As you can see, the most frequent colors have a positive balance, thus data supports us on this one! The negative balance for Charge OG (high frequency) is not too big, but what really hurts is Gray, cause we literally called it “the lucky color”.</p><p>On contrary, the stages have a negative balance on the most frequent ones. We have the worst performance on stages with multiple platforms (except Enigma) and small borders. The platforms often interfere with the flow of the battle and if the borders are small is probable that the limited jumps aren’t enough to save us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8vHLf4ha2PNkPAOAD-oqA.png" /></figure><h4>Character analysis</h4><p>Finally, who are the responsible for those amazing victories and hideous defeats?</p><p>Brawlhalla has a list of <a href="https://www.brawlhalla.com/legends/">54 characters (legends) available</a> (and still growing), and of course, we don’t know how to use all of them. Each of us uses like 3, and sometimes we experiment with other combinations. How we play a team mode, it’s more optimal to analyze which is our better couple.</p><p>The visualization shows the percentage of victories of the 7 most frequent teams (and rest are grouped into “Other”). An interesting thing, and maybe the answer of “why we lose so much?”, is because the most effective team <em>Zariel — Val</em> is barely used, and the most used team <em>Koji — Val</em> has only a 45% of effectiveness.</p><p>So it’s possible that we are not optimizing our legend election in order to win the match and we are fooling ourselves with our favorites (in my case, <em>Koji</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQ7s8AxuLoFHRg02AQDJSg.png" /></figure><p>And of course, we can’t forget about the enemies. They also a team, but it’s a team that doesn’t depend on us, therefore I want to know which are the most played legends by other people and how we dealt with them.</p><p>For this one, I extract the top 10. Mordex is the legend the most people use with 6.4% of the occasions, personally I think Sandstorm has some influence on this (in the viz I explain who is Sandstorm).</p><p>If you hear something about this game (or with this, have some curiosity) will know that the <a href="https://www.youtube.com/watch?v=vsCBH_6bac4"><em>Rocket Lance</em> it’s the most annoying weapon in the game</a>! We usually lose more against the legends with that weapon (Ulgrim, Artemis, Scarleth and Orion) and also against Teros. Teros it’s one of the strongest legends in the game, so if he hits you three or four times, probably kills you really fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*pLX3erHLWLnfDPR4Wbjb9Q.png" /></figure><p>So, in conclusion: my sister and I are really bad at this game! But now we know why and when we are terrible.</p><p>That’s the lesson here: you can make your own data analysis about anything and probably you’ll have an amazing time finding out things to random questions. Data analysis is not just a six-figure salary (even if I don’t have it) is an adventure that you should take advantage of.</p><p>For the next article, we going to build a ML model to predict the probability of winning implementing our new knowledge.</p><p>If you get here, I appreciate it! Hope you liked it.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61fdca6635b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I have a problem, therefore I simulate (with R)]]></title>
            <link>https://medium.com/@darnelbolaos/i-have-a-problem-therefore-i-simulate-with-r-81eb208b0ed9?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/81eb208b0ed9</guid>
            <category><![CDATA[monte-carlo-simulation]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[rstudio]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 21:02:13 GMT</pubDate>
            <atom:updated>2021-12-09T21:02:13.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyByyPIIlV_f_l5hTV8LOw.jpeg" /><figcaption>Me every time I have to take any unimportant decision</figcaption></figure><p>We overthinkers have this weird power to simulate several scenarios for every important and unimportant decision that causes us any teeny-tiny stress. Many choose the best decision, many don’t (like me), but it’s always important to have the options to understand what is coming on.</p><p>Is common that every stage of any process has its own randomness (human factor, budget, maintenance, weather, suppliers, an extremely contagious virus that changes the whole economic system), and sometimes define manually all variables to visualize the <em>worst</em>, <em>prevailing </em>and <em>better </em>scenario is difficult. In these cases is where the Monte Carlo simulation shines.</p><p>This article aims to show the basis of Monte Carlo simulation with R, so we’re going to solve two popular probabilistic problems. Maybe later I’ll write more realistic problems or you can suggest to me and I’ll be happy to try it!</p><h4><strong>What is Monte Carlo simulation?</strong></h4><p>Basically, is to compute a process, assigning the respective variability to the variables (dah!) following a probabilistic distribution, and repeat it n-times to get the target variable or maybe the number of times that an event occurs. From these outcomes, we can calculate its statistical parameters or even the probability of the event happening.</p><blockquote><em>The first and most important step in the Monte Carlo simulation is to define: </em>what do I want to know?</blockquote><blockquote><em>Cause you have to design your simulation in order to get the result you want. Something simple as tossing a coin can have a lot of questions! And not all the simulations are the same.</em></blockquote><p>A Monte Carlo simulation example is in the movie <em>Avengers: Infinity War</em>, when <a href="https://www.youtube.com/watch?v=Jo_TDvQ9Qyg">Dr. Strange</a> uses the <em>Eye of Agamotto</em> to simulate 14,000,605 alternative futures to predict, from all outcomes, that the probability of winning the battle against Thanos is 1/14,000,605 (7.1425e-08). Fortunately, we won!</p><p>In R programming, Monte Carlo simulation has the following basic structure:</p><pre>B &lt;- 10000 #number of simulations</pre><pre>simulations &lt;- replicate(B, {<br>  #function that recreates the process one time<br>  var_interest &lt;- conditional that evaluates if the event occurred or just the result of the variable<br>  return(var_interest)<br>})</pre><p>The simulations object stores all the results from every simulation.</p><p><strong>Two tails in a row</strong></p><p>Of course! Of course, there would be a coin exercise! Here, we’re going to solve an exercise proposed by <a href="https://www.linkedin.com/posts/data-science-dojo_datascience-probability-polltime-activity-6861706702408949760-ptBk">Data Science Dojo on LinkedIn</a>. The question is: <em>What is the </em><strong><em>expected number</em></strong><em> of coin flips needed to get two consecutive tails?</em></p><p>I have to accept it; I didn’t know how to solve it <a href="https://www.quora.com/What-is-the-expected-number-of-coin-flips-until-you-get-two-heads-in-a-row">analytically</a>. But then I remembered “I have the power of simulations on my side!”, so I took that approach. My solution <strong>isn’t the most optimal</strong>, but it works and it’s fast.</p><p>In our programming solution, tails are going to be represented with 1 and heads with 0. Before everything, we need to define three variables: i (counter), value (representation of two tails in a row, the event we are interested) and event (empty and temporal vector to storage every toss).</p><p>Then we enter a while loop cause we don’t know when it’ll finish. So, we toss a coin and store the result in event, then convert the numeric vector to character and paste it all together in chars vector (for example, instead of 1 0 1 0 1 1, our result is “101011”). At last, we check in every toss if value is in char. If it is, we return how many tosses it took, if not, increase the counter. When the simulations are over, calculate the mean of s vector, cause we need to know the expected value.</p><p><strong>Note:</strong> Notice that if you want to know another value than two, like three or four or even any combination (two tails and one head), you only have to change the value vector (“110”) and you have it! That’s the wonderful and funny thing with Monte Carlo simulations.</p><pre>B &lt;- 10000</pre><pre>s &lt;- replicate(B, {<br>  i &lt;- 1<br>  value &lt;- &quot;11&quot;<br>  event &lt;- c()<br>  <br>  while (TRUE) {<br>    coin &lt;- sample(c(1, 0), 1)<br>    <br>    event[i] &lt;- coin<br>    chars &lt;- paste0(as.character(event), collapse = &#39;&#39;)<br>    <br>    if (grepl(value, chars, fixed = TRUE)) {<br>      return(i)<br>      break<br>    } else {<br>      i &lt;- i + 1<br>    }<br>    <br>  }<br>})</pre><pre>mean(s)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rp8HR8wUYMiO8fxjM-NFA.png" /><figcaption>Number of flips needed to get two tails in a row (20,000 simulations)</figcaption></figure><p><strong>Birthday paradox</strong></p><p><em>How many people randomly picked do we need in a room to get at least a 50% chance, that two of them to share the same birthday?</em> It’s possible you already know the <a href="https://www.youtube.com/watch?v=ofTb57aZHZs&amp;t=12s">analytical answer</a>: 23 people (50,7% chance). Now we are going to prove it with a simulation.</p><p>We already set up <em>what we want to know</em>: the number of people randomly picked till two of them share a birthday.</p><p>A way to do it in programming is a loop that samples the birthday days of people from 1 to 365 (for example my birthday is 353) and storage the sample in an empty and temporal vector event. Then, every sample is checked to see if is a duplicated number. If it is, return how many times the loop sampled people; if not, then keep going with the loop.</p><p>Finally, we calculate the s vector’s median to have the value where 50% of simulations happened.</p><pre>B &lt;- 10000</pre><pre>s &lt;- replicate(B, {<br>  i &lt;- 1<br>  event &lt;- c()<br>  <br>  while (TRUE) {<br>    birthday &lt;- sample(seq(1, 365), 1)<br>    <br>    event[i] &lt;- birthday<br>    <br>    if (sum(duplicated(event)) == 1) {<br>      return(i)<br>      break<br>    } else {<br>      i &lt;- i + 1<br>    }<br>    <br>  }<br>})</pre><pre>median(s)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dl-HjWV1ryLaJSLhxW6-XA.png" /><figcaption>Cumulative probability curve of Birthday Paradox simulation</figcaption></figure><p>And we did it! If you get here, thanks, I appreciated it! As a reward, I want to give you a challenge:</p><blockquote>“How many people randomly picked do we need in a room to get at least a 50% chance, that one of them shares its birthday with me (353)?” <a href="http://0.0.0.253/"><em>Answer</em></a>.</blockquote><p>In conclusion, simulations are so useful when we have uncertain scenarios cause variables have many variations or their analytical solution is pretty complex and don’t worth it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81eb208b0ed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interactive line plot with ggplot and ggiraph in R]]></title>
            <link>https://medium.com/@darnelbolaos/interactive-line-plot-with-ggplot-and-ggiraph-in-r-606d655a1547?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/606d655a1547</guid>
            <category><![CDATA[interactive]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 06:23:27 GMT</pubDate>
            <atom:updated>2021-11-13T06:23:27.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2powkA0F63rTPcb39UINvQ.png" /><figcaption>Interactive plot with ggplot and ggirapgh</figcaption></figure><p>So I was taking one of the Bill Shander’s courses <a href="https://www.linkedin.com/learning/learning-data-visualization-3/">“Learning Data Visualization”</a> from LinkedIn Learning and some lessons he showed one of his works: “<a href="https://billshander.com/dataviz/occupations/">Trends in U.S Occupations 2000–2019</a>”, an interesting and well-explained data storytelling about how occupations have evolved over time, <strong>highly recommended</strong>.</p><p>Anyway, when I saw the first plot, I really like it, so I want to replicate it in R, cause I know little about D3 and it’s my main programming language. My first try was with ggplotly (from plotly) but the interaction wasn’t the expected. Besides, it had some minor issues with the themes options. And after a little research, I found <a href="https://davidgohel.github.io/ggiraph/">ggiraph</a>! I think is a little more compatible with ggplot and the functionality is exactly what I was looking for.</p><p>The final plot isn’t cool as Bill’s, but it works and maybe it can help you someday on your <em>RMarkdown </em>or <em>Shiny </em>reports.</p><h3>Libraries and data</h3><p>The libraries used are:</p><ul><li>tidyverse: data manipulation and ggplot.</li><li>ggthemes: extra pre-defined themes for ggplot.</li><li>ggiraph: allows the interactivity of a ggplot object.</li></ul><p>The dataframe was made up for representative purposes. It has three variables: year, profession, and values. Each value was ranked per year, and add a text column for the label:</p><pre>library(ggthemes)<br>library(tidyverse)<br>library(ggiraph)</pre><pre>year &lt;- rep(seq(2000, 2010), 5)<br>professions &lt;- rep(c(&quot;Retail&quot;, &quot;Food&quot;, &quot;Health&quot;, &quot;Office&quot;,<br>                     &quot;Manager&quot;), each = 11)<br>values &lt;- runif(55, 5e4, 5e6)</pre><pre>data &lt;- data.frame(year, professions, values) %&gt;% <br>  mutate(texto = paste0(professions, &quot;\n&quot;,<br>                        year, &quot;: &quot;,<br>                        format(round(values, 0),<br>                               big.mark = &quot;,&quot;))) %&gt;% <br>  group_by(year) %&gt;% <br>  mutate(rank = rank(values)) %&gt;% <br>  ungroup()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*AgktNxtHXJK3eK1S05YEDg.png" /><figcaption>Dataframe used for visualization</figcaption></figure><h3>ggplot line chart</h3><p>Before the interactivity, is necessary to build the base plot. The plot commands are exactly the same as a ggplot chart, except that the layers and elements that we want to be interactive with usually have the word interactive. Also, is important to specify the data_id in the aesthetics function cause is on that variable where the interactivity options of ggiraph will work.</p><pre>#plot schema</pre><pre>gg &lt;- ggplot(data, <br>             aes(x = year,<br>                 y = rank, #rank so all lines have the same height<br>                 color = professions,<br>                 data_id = professions,<br>                 group = professions)) +</pre><pre>  #interactive elements of layers (points, lines and text at final)<br>  geom_line_interactive(size = 1.2,<br>                        alpha = 0.4) +<br>  geom_point_interactive(<br>                aes(tooltip = texto), #specifies tooltip for ggiraph<br>                         fill = &quot;white&quot;,<br>                         size = 2.5,<br>                         stroke = 1.5,<br>                         shape = 21) +<br>  geom_text_interactive(data = data %&gt;% filter(year == max(year)),<br>                        aes(x = year + 0.7, y = rank,<br>                            color = professions, <br>                            label = professions),<br>                        check_overlap = T)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*oxImUMMRqKilV0g5o4EbCg.png" /><figcaption>Base line chart in ggplot</figcaption></figure><p>As you can see, the interactive command affects nothing in the plot&#39;s construction. Now add some formatting things so the plot can look more like the Bill’s.</p><pre>gg &lt;- gg +<br>  labs(x = NULL, y = NULL) +<br>  scale_x_continuous(labels = c(&quot;2000&quot;, rep(&quot;&quot;, 9), &quot;2010&quot;),<br>                     breaks = seq(2000, 2010),<br>                     position = &quot;top&quot;) +<br>  scale_color_tableau() +<br>  theme_minimal() +<br>  theme(<br>    panel.grid = element_blank(),<br>    plot.background = element_rect(fill = &quot;gray95&quot;, color = NA),<br>    panel.background = element_rect(fill = &quot;gray95&quot;, color = NA),<br>    axis.text.y = element_blank(),<br>    axis.text.x = element_text(color = &quot;gray50&quot;, size = 10, <br>                               face = &quot;bold&quot;),<br>    legend.position = &quot;none&quot;<br>  )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*_lI3_4tSJkRetirklzwI2w.png" /><figcaption>Formatted chart from ggplot (static)</figcaption></figure><h3>Adding interactivity</h3><p>Finally! The plot seems pretty messy and difficult to follow any of the lines. Highlighting the one line of interest could help a lot and that’s precisely the interactivity ggiraph offers.</p><p>ggiraph has many options to change the behavior of the actions. <a href="https://cran.r-project.org/web/packages/ggiraph/ggiraph.pdf">Here</a> you can find a deeper explanation of all of them. This plot only uses three:</p><ul><li>opts_tooltip: configuration of tooltip box, accepts CSS code.</li><li>opts_hover: configuration of the interactive elements when the mouse hovers over them. This plot has three elements interactive: lines, points, and text. When the mouse hovers over any of them, the configuration is activated and with points even shows the tooltip. But if we had defined geom_point instead of geom_point_interactive, then if the mouse hovers over the points, nothing would happen. Accepts CSS code.</li><li>opts_hover_inv: define the configuration of the other interactive elements that aren’t hovered. Accepts CSS code.</li></ul><pre>girafe(ggobj = gg, <br>       width_svg = 8, height_svg = 6, #sizes the output plot<br>       options = list(<br>          opts_tooltip(<br>            opacity = 0.8, #opacity of the background box <br>            css = &quot;background-color:#4c6061; color:white; padding:10px; border-radius:5px;&quot;),<br>       opts_hover_inv(css = &quot;stroke-width: 1;opacity:0.6;&quot;),<br>       opts_hover(css = &quot;stroke-width: 4; opacity: 1;&quot;)<br>       )<br>)</pre><p>The original plot has an alpha (opacity) = 0.4 for lines. So when the mouse hovers some element, all that belong to the defined data_id (professions) increase its opacity = 1, and the stroke border of the points increases from 1.5 to 4 points. The elements that weren’t selected reduce their stroke border to 1.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fforcefulthiseastsiberianlaika&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fforcefulthiseastsiberianlaika&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FForcefulThisEastsiberianlaika-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1440" height="810" frameborder="0" scrolling="no"><a href="https://medium.com/media/713b8cdcc5e84de94028d1341f42fab7/href">https://medium.com/media/713b8cdcc5e84de94028d1341f42fab7/href</a></iframe><p>So I hope you try it.</p><h3>References</h3><ul><li><a href="https://billshander.com/dataviz/occupations/">https://billshander.com/dataviz/occupations/</a></li><li><a href="https://davidgohel.github.io/ggiraph/">https://davidgohel.github.io/ggiraph/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=606d655a1547" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ggdogs: Random packages that make me love R]]></title>
            <link>https://medium.com/@darnelbolaos/random-packages-that-make-me-love-r-ggdogs-5201b245d7f0?source=rss-a97ac3f6a351------2</link>
            <guid isPermaLink="false">https://medium.com/p/5201b245d7f0</guid>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[dogs]]></category>
            <category><![CDATA[memes]]></category>
            <category><![CDATA[rstudio]]></category>
            <dc:creator><![CDATA[Darnel Bolaños]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 03:51:35 GMT</pubDate>
            <atom:updated>2021-11-09T17:11:19.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*fEDZGzHSTMaDasgCl8qntg.jpeg" /><figcaption>Source: https://knowyourmeme.com/photos/234765-i-have-no-idea-what-im-doing</figcaption></figure><p>Whoever is passing through a tough moment in these pandemic times or is an introverted person who loves being at home -or both, like me- could agree that in modern life there are three things that bring us joy: memes, pets, and data.</p><p>(Maybe the last one is not true for everybody, but it is for those enthusiastic data analysts who spend their free time looking for some fun ways to kill it.)</p><p>That is how on a lazy day, I found on Google a way to combine the three pillars of joy: ggdogs. An R package, created by <a href="https://github.com/R-CoderDotCom/ggdogs">R-CoderDotCom</a> as part of its ‘memeverse’. Three packages of some popular internet memes (dogs, cats, and Bernie Sanders) that allow you to use some image memes in your ggplot charts.</p><p>My favorite by far is ggdogs. Its combination between memes and popular doggy characters (25 dogs in total) makes me love it so much! The dog can be customized as any other geom_imagelayer with size, aesthetics, position. So I made three random examples to show you how to add dogs to your next professional presentation.</p><p>First, you need to install the package</p><pre>install.packages(&quot;remotes&quot;)<br>remotes::install_github(&quot;R-CoderDotCom/ggdogs@main&quot;)</pre><h3><strong>Dinosaur and dog</strong></h3><p>The first one is a very simple plot, to set the basis. As you can see, I used the datasauRuspackage to draw a cute T-Rex. Then with geom_dogwe add the meme specifying the position in the plot, in this case without aestheticsand the name of the dog (can check it up in the Github link above). Also, I add the “<em>this is fine</em>” catchphrase so the meme can be complete.</p><pre>library(datasauRus)<br>library(tidyverse)<br>library(ggdogs)</pre><pre>dozen &lt;- datasaurus_dozen %&gt;% <br>  filter(dataset == &quot;dino&quot;)</pre><pre>ggplot(dozen, aes(x, y)) +<br>  geom_point(color = &quot;midnightblue&quot;) +<br>  geom_dog(x = 90, y = 80, dog = &quot;thisisfine&quot;, size = 5) +<br>  geom_label(x = 95, y = 95, label = &quot;This is fine&quot;,<br>             fill = &quot;white&quot;, color = &quot;black&quot;, size = 5) +<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*rmy0JP8kWX8pFJRYGTOe-g.png" /><figcaption>Basic Dinoplot with dog meme “This is fine”</figcaption></figure><h3>Dogecoin by doge</h3><p>Probably many of you invest in cryptocurrency in the year&#39;s boom. Almost every day for the six first months of 2021 I watched the value of different coins cause it really amazes me how unstable they were and how their value could grow up -or down- from one day to another. So yeah, I didn’t invest and I’m still poor.</p><p>But anyways, the next example is an animated plot where we can see the instability of the dogecoin guided by doge who gives the name to the coin. Here, the dog is part of the aestheticsdue the animation requires the step-by-step, so doge has to be at every point of the plot. Finally, the animation is stored as a .gif.</p><p>I extracted the data from this <a href="https://www.coindesk.com/price/dogecoin/">real-time data</a> platform.</p><pre>library(tidyverse)<br>library(ggdogs)<br>library(gganimate)</pre><pre>doge &lt;- read.csv(&quot;doge_coin.csv&quot;, sep = &quot;;&quot;) %&gt;%<br>  rename(price = Closing.Price..USD.) %&gt;%<br>  mutate(Date = as.Date(Date, format = &quot;%d/%m/%Y&quot;))</pre><pre>p &lt;- ggplot(doge, aes(x = Date, y = price)) +<br>  geom_line(size = 1, color = &quot;darkgreen&quot;) +<br>  geom_dog(aes(dog = &quot;doge&quot;), size = 2) +<br>  labs(x = NULL, y = NULL,<br>     title = &quot;Dogecoin transition in 1 year (11-2020 to 11-2021)&quot;) +<br>  theme_minimal() +<br>  theme(<br>    plot.margin = margin(5.5, 40, 5.5, 5.5),<br>    plot.title = element_text(size = 15,<br>                              face = &quot;bold&quot;,<br>                              color = &quot;black&quot;),<br>    panel.border = element_rect(color = &quot;gray60&quot;, fill = NA),<br>    panel.grid = element_blank()<br>  ) +<br>  transition_reveal(Date)</pre><pre>anim_save(&quot;doge.gif&quot;, p, fps = 7, height = 8, width = 10, units = &quot;in&quot;, res = 150)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fagilevaluablebuzzard&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fagilevaluablebuzzard&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FAgileValuableBuzzard-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1500" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eca5d751f9312dc397b0bfac464e32d/href">https://medium.com/media/9eca5d751f9312dc397b0bfac464e32d/href</a></iframe><h3>Scooby-Doo TV Shows</h3><p>And last, but no less important, I made a plot about Scooby-Doo’s TV shows to describe which has been the higher rated in IMDb.</p><p>The dataset for this plot is from the <em>tidytuesday </em>challenges. I highly recommend if you’re interested in this dataset see <a href="https://www.youtube.com/watch?v=2g6f-j3sHS4&amp;t=589s">Julia Silge’s video</a> where she tune a decision tree algorithm, and it&#39;s pretty cool.</p><p>The dog selected is the unique and almost eternal Scooby-Doo! I used the <a href="https://www.dafont.com/es/scoobydoo.font">font </a>from the shows. <a href="https://medium.com/analytics-vidhya/5-easy-steps-to-import-new-fonts-into-r-6651bf263a07">Here</a> is a guide to import the font to R (in case you didn’t know, like me 10 hours ago).</p><pre>library(tidyverse)<br>library(ggthemes)<br>library(ggalt)<br>library(ggdogs)<br>library(ggtext)<br>library(extrafont)</pre><pre>font_import(paths = &quot;C:/Users/darnel.bolanos/AppData/Local/Microsoft/Windows/Fonts&quot;)<br>extrafont::loadfonts(device=&quot;win&quot;)</pre><pre>scooby_raw &lt;- read_csv(&quot;<a href="https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-07-13/scoobydoo.csv">https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-07-13/scoobydoo.csv</a>&quot;)</pre><pre>#a coordinate location for Scooby in the facet<br>coord_dog &lt;- data.frame(season = &quot;Season 4&quot;)</pre><pre>#creating the dataset to use<br>avg_imdb &lt;- scooby_raw %&gt;%<br>  filter(season %in% c(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;)) %&gt;% <br>  mutate(imdb = parse_number(imdb),<br>         season = paste(&quot;Season&quot;, season),<br>         season = factor(season)) %&gt;%<br>  filter(!is.na(imdb)) %&gt;% <br>  group_by(series_name, season) %&gt;%<br>  summarise(avg = round(mean(imdb, na.rm = TRUE), 2),<br>            beg_date = lubridate::year(min(date_aired)),<br>            end_date = lubridate::year(max(date_aired))) %&gt;%<br>  ungroup() %&gt;% <br>  group_by(series_name) %&gt;% <br>  mutate(series_name = paste0(series_name, <br>                              &quot; (&quot;, min(beg_date),<br>                              &quot; - &quot;, <br>                               max(end_date),<br>                              &quot;)&quot;))<br>head(avg_imdb)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*EPwKZZ2CpJkUPmkBQA3zUA.png" /></figure><p>I did the entire plot in one pipe (<strong>it’s not recommended</strong>) so if you have any doubt in any code line, please comment below or send me a message and I’ll clear it for you.</p><p>The Scooby-Doo image was placed in the <em>Season 4</em> facet with help of the auxiliary data frame we did early coordog. This is important, cause if that is not specified Scooby-Doo will appear in every facet.</p><p>In this specific plot, the dog has a related and more meaningful appearance, so maybe you can really use this package for enhancing the visualization.</p><pre>ggplot(avg_imdb, aes(x = reorder(series_name, beg_date), y = avg)) +</pre><pre>geom_col(width = 0.85, show.legend = F,<br>           aes(fill = ifelse(avg &gt; 8, &quot;max&quot;, &quot;others&quot;))) +</pre><pre>geom_text(aes(y = 1.2, label = avg), color = &quot;white&quot;,<br>            fontface = &quot;bold&quot;, size = 5, show.legend = F) +</pre><pre>geom_dog(data = coord_dog, aes(x = 5, y = 7),<br>           dog = &quot;scooby&quot;, size = 10.5) +</pre><pre>geom_label(data = coord_dog,<br>             aes(x = 8.5, y = 3, label = &quot;Scooby-Dooby-Doo!&quot;),<br>             size = 5, color = &quot;#4b0055&quot;, family = &quot;Scooby Doo&quot;,<br>             fontface = &quot;bold&quot;) +</pre><pre>coord_flip() +</pre><pre>scale_fill_manual(values = c(&quot;#4b0055&quot;, &quot;#17BDB9&quot;)) +</pre><pre>scale_y_continuous(limits = c(0, 10)) +</pre><pre>labs(x = NULL, y = NULL,<br>       title = &quot;Looking for best TV Show of Scooby-Doo in IMDb&quot;,<br>       subtitle = paste0(&quot;From the 30 seasons of 15 different TV                     shows, the second season of &#39;Scooby-Doo Mystery Incorporated&#39; is the best rated by IMDb. Besides the first season and the first show from 1969!&quot;, <br>                         &quot;\n&quot;,<br>                         &quot;Ironically the show released before the best one (&#39;Shaggy &amp; Scooby-Doo Get a Clue!&#39;) has been the worst rated so far, so maybe they learned from their mistakes.&quot;)) +</pre><pre>facet_grid(cols = vars(season),<br>             scales = &quot;free&quot;, switch = &quot;y&quot;) +</pre><pre>theme_minimal() +</pre><pre>theme(<br>    plot.margin = margin(5.5, 40, 5.5, 5.5),<br>    plot.title = element_text(size = 30, face = &quot;bold&quot;,<br>                              color = &quot;#4b0055&quot;,<br>                              family = &quot;Scooby Doo&quot;),<br>    plot.subtitle = element_text(size = 13,<br>                                 color = &quot;gray60&quot;),<br>    axis.text.x = element_blank(),<br>    panel.grid = element_blank(),<br>    panel.border = element_rect(color = &quot;gray60&quot;,<br>                                fill = NA),<br>    strip.text = element_text(size = 13,<br>                              face = &quot;bold&quot;,<br>                              color = &quot;gray60&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sloofe6lhIfFKt7UR1ITnQ.png" /><figcaption>Average IMDb rating for every season of Scooby-Doo TV Show.</figcaption></figure><p>So that’s all, hope you like it and make your own dog-plots.</p><h3>References</h3><ol><li><a href="https://www.youtube.com/watch?v=2g6f-j3sHS4&amp;t=589s">https://www.youtube.com/watch?v=2g6f-j3sHS4&amp;t=589s</a></li><li><a href="https://github.com/R-CoderDotCom/ggdogs">https://github.com/R-CoderDotCom/ggdogs</a></li><li><a href="https://www.coindesk.com/price/dogecoin/">https://www.coindesk.com/price/dogecoin/</a></li><li><a href="https://medium.com/gfycat/how-to-add-gifs-to-your-medium-blog-with-gfycat-9e458d7af8b1">https://medium.com/gfycat/how-to-add-gifs-to-your-medium-blog-with-gfycat-9e458d7af8b1</a></li><li><a href="https://medium.com/analytics-vidhya/5-easy-steps-to-import-new-fonts-into-r-6651bf263a07">https://medium.com/analytics-vidhya/5-easy-steps-to-import-new-fonts-into-r-6651bf263a07</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5201b245d7f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>