R Tutorial: Making Better Plots

Learn how to reorder factors in R plots using the forcats package. Use fctreorder to sort by another variable, fctinfreq to sort by frequency, and fct_rev to reverse the order. Better ordering makes scatter plots and bar charts much easier to read.
Chapters
One of the places for cats really shines is in helping you make better graphs. Have you ever made a graph and everything is in the wrong order? What's wrong with this plot? Well, how quickly could you answer? What's the third biggest problem people face? It's very hard to read this graph right away. For example, to find the problem, the largest percentage of people consider an issue. We have to find the point all the way on the right and then connect it back to the text on the Y axis. It's even more difficult to do this for points in the middle. To fix this, we can use the forecast function fctreorder. Many forecast functions start with fct, which stands for factor. From now on, I'll be saying factor instead of fct. Factor reorder takes two arguments. The variable you want to reorder and the variable you want to reorder it by. By adding this to our ggplot2 function, we'll have a nicely ordered scatter plot and we can read the Y axis top to bottom. In that case, we're looking at your unordered variable and in relation to another variable. But sometimes we are looking at the variable by itself, such as in a bar chart. Then you usually want to order by its frequency. Let's take a look at how we can do this. For a frequency bar chart for current job title, select Just like in the previous graph, this one is hard to read. It's fairly easy to see. Data Scientist is the most popular job title and Operations Research Practitioner and Data Miner the least. But what about the fourth most popular title? To make the graph easier to read, we can use the forecast function FactorInfreq. This orders a factor by the frequency of each level. Now the graph is much more easy to read. We can easily see that the fourth most popular title is Data Analysts. To make it even better, we could switch the order from most to least frequent. To do this, we can use the function factorref. This takes the current levels of the factor and reverses them. Time to put this into practice.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







