sleep_total awake bodywt brainwt
Min. : 1.90 Min. : 4.10 Min. : 0.005 Min. :0.00014
1st Qu.: 7.85 1st Qu.:10.25 1st Qu.: 0.174 1st Qu.:0.00290
Median :10.10 Median :13.90 Median : 1.670 Median :0.01240
Mean :10.43 Mean :13.57 Mean : 166.136 Mean :0.28158
3rd Qu.:13.75 3rd Qu.:16.15 3rd Qu.: 41.750 3rd Qu.:0.12550
Max. :19.90 Max. :22.10 Max. :6654.000 Max. :5.71200
NA's :27
1. Environment Setup & Data Processing
First, let’s load the necessary libraries and organize our data. We will calculate the average sleep (mean_sleep) grouped by order.
Code
library(tidyverse)
1.1 Grouping & Summarizing
We use group_by(order) to categorize the animals and summarise() to calculate the average sleep for each group.
Code
# Data Preparationsleep_data <- msleep %>%group_by(order) %>%summarise(mean_sleep =mean(sleep_total))
1.2 Factor Reordering
To make the visualization aesthetically pleasing, we use fct_reorder(). This sorts the categories from lowest to highest based on the mean sleep values.
Step 3: The Lollipop Base (Reference Line & Sticks)
We add a benchmark line for the overall average sleep and connecting “sticks” for each point.
Code
plot_step3 <- plot_step2 +# Horizontal line for overall average sleepgeom_hline(yintercept =mean(msleep$sleep_total), color ="#d580ff", linewidth =1) +# Segments to show distance from the mean linegeom_segment(aes(x = order, y =mean(msleep$sleep_total), xend = order, yend = mean_sleep), color ="#d580ff")plot_step3
Step 4: Adding Color Gradient Points
We place points at the end of the sticks that change color based on the amount of sleep.
Finally, we add an explanatory text and a curved arrow for better storytelling.
Code
final_plot <- plot_step4 +# Adding explanatory textannotate("text", x =4, y =max(msleep$sleep_total) -4, label ="Average sleep\nfor all mammals", color ="#eabfff", size =4, fontface ="bold", hjust =0) +# Adding a curved arrow pointing to the mean linegeom_curve(aes(x =3.7, y =max(msleep$sleep_total) -5, xend =1.5, yend =mean(msleep$sleep_total)), color ="#eabfff", curvature =0.5, arrow =arrow(length =unit(0.07, "npc"), type ="open"))final_plot
Key Visual Toolkit (Cheat Sheet)
fct_reorder(): Used to sort categories based on numeric values.
theme(panel.background = ...): Customizes the internal plot background.
geom_segment(): Creates the “sticks” for the lollipop chart.
**geom_curve() & annotate()**: Highlights or explains specific parts of the graph.
scale_color_gradient(): Shows color shifts for continuous data.
Congratulations! You have successfully transformed a simple plot into a high-end visualization.