Pie plot code improvement.
Opened this issue · 0 comments
Suggested by Cédric Scherer
original ---------------------------------------------------------------------
Libraries
library(tidyverse)
library(hrbrthemes) ## not needed
library(viridis) ## not needed
library(patchwork)
create 3 data frame:
data1 <- data.frame( name=letters[1:5], value=c(17,18,20,22,24) )
data2 <- data.frame( name=letters[1:5], value=c(20,18,21,20,20) )
data3 <- data.frame( name=letters[1:5], value=c(24,23,21,19,18) )
Plot
plot_pie <- function(data, vec){
ggplot(data, aes(x="name", y=value, fill=name)) +
geom_bar(width = 1, stat = "identity") + ## why not geom_col?
coord_polar("y", start=0, direction = -1) +
scale_fill_viridis(discrete = TRUE, direction=-1) + ## ggplto2 has its own viridis scale
geom_text(aes(y = vec, label = rev(name), size=4, color=c( "white", rep("black", 4)))) + ## sizeand color should NOT be listed inside aes(). Plus, colors could be handled dynamically
scale_color_manual(values=c("black", "white")) + ## not used at all
theme_ipsum() + ## just use theme_void?
theme(
legend.position="none",
plot.title = element_text(size=14),
panel.grid = element_blank(),
axis.text = element_blank(),
legend.margin=unit(0, "null")
) +
xlab("") + ## not needed in combination with theme_void(), and if better use xlab(NULL)
ylab("") ## not needed in combination with theme_void(), and if better use ylab(NULL)
}
a <- plot_pie(data1, c(10,35,55,75,93))
b <- plot_pie(data2, c(10,35,53,75,93))
c <- plot_pie(data3, c(10,29,50,75,93))
a + b + c
updated ----------------------------------------------------------------------
Libraries
library(tidyverse)
library(patchwork)
Create 3 data sets:
data1 <- data.frame( name = letters[1:5], value = c(17,18,20,22,24) )
data2 <- data.frame( name = letters[1:5], value = c(20,18,21,20,20) )
data3 <- data.frame( name = letters[1:5], value = c(24,23,21,19,18) )
Plot
plot_pie <- function(data, vec){
retrieve number of slices
n <- nrow(data)
ggplot(data, aes(x = "name", y = value, fill = name)) +
geom_col(width = 1) +
geom_text(
aes(y = vec, label = rev(name)),
## dynamic mapping of colors depending on position -> fill of slice
color = c(rep("black", floor(n / 2)), rep("white", ceiling(n / 2))),
size = 8, fontface = "bold"
) +
coord_polar("y", start = 0, direction = -1) +
scale_fill_viridis_d(end = .9, guide = "none") +
theme_void()
}
a <- plot_pie(data1, c(10,36,56,75,93)) ## adjust label positions
b <- plot_pie(data2, c(9,31,51,71,90)) ## adjust label positions
c <- plot_pie(data3, c(8,28,48,70,93)) ## adjust label positions
a + b + c