ggplot2 - get annotations in legend - r

I'm working with a dataframe and using ggplot to generate a pie chart.
df <- data.frame(Make=c('toyota','toyota','honda','honda','jeep','jeep','jeep','accura','accura'),
Model=c('camry','corolla','city','accord','compass', 'wrangler','renegade','x1', 'x3'),
Cnt=c(10, 4, 8, 13, 3, 5, 1, 2, 1))
row_threshold = 2
dfc <- df %>%
group_by(Make) %>%
summarise(volume = sum(Cnt)) %>%
mutate(share=volume/sum(volume)*100.0) %>%
arrange(desc(volume))
dfc$Make <- factor(dfc$Make, levels = rev(as.character(dfc$Make)))
pie <- ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
coord_polar("y") +
geom_text(aes(label = paste0(round(share), "%")),
position = position_stack(vjust = 0.5)) +
labs(x = NULL, y = NULL, fill = NULL,
title = "Market Share") +
guides(fill = guide_legend(reverse = TRUE)) +
theme_classic() +
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5, color = "#666666")) +
scale_color_brewer(palette = "Paired")
this gives me a pie chart as below - how do I add %share along with the Make labels like honda (45%) instead of just honda

This can be achieved by adding breaks and labels to the scale_fill_brewer.
First of all you mapped Make to fill so to control the color you need to use a fill_scale. Secondly if you want to provide custom legend entries define the keys present in the legend in breaks and the new names in labels :
library(ggplot2)
ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
coord_polar("y") +
geom_text(aes(label = paste0(round(share), "%")),
position = position_stack(vjust = 0.5)) +
labs(x = NULL, y = NULL, fill = NULL,
title = "Market Share") +
guides(fill = guide_legend(reverse = TRUE)) +
theme_classic() +
theme(axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5, color = "#666666")) +
scale_fill_brewer(palette = "Paired",
labels = rev(paste0(dfc$Make, " (", round(dfc$share), "%)")),
breaks = rev(dfc$Make))

Related

How to do a pie chart with two factor variables and % inside the plot

How can I transform this bar plot into a pie chart?
This is the bar plot I have:
This is the code I use to make the bar plot:
dados_gráfico_distrito <- dados_desde_2015 %>%
filter(!is.na(qsd_distrito_nascimento_rec)) %>%
group_by(anoletivo_cat) %>%
count(anoletivo_cat, qsd_distrito_nascimento_rec) %>%
mutate(pct = n / sum(n), pct_label = scales::percent(pct, accuracy=1))
dados_gráfico_distrito$qsd_distrito_nascimento_rec <- factor(dados_gráfico_distrito$qsd_distrito_nascimento_rec, levels = c("Other", "Porto", "Braga"))
ggplot(dados_gráfico_distrito, aes(x= anoletivo_cat, fill = qsd_distrito_nascimento_rec, y = pct)) +
geom_bar(position = "fill", stat="identity", width = 0.5) +
geom_text(aes(label = paste(pct_label), y = pct), position = position_fill(vjust = 0.5), colour = "black", size = 3.2) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme_void() + scale_fill_brewer(palette="Paired") +
theme(legend.text = element_text(size = 8, colour = "black")) +
theme(axis.text = element_text(size = 8, colour = "black")) +
theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))
When I try to transform it in a pie chart, adding the code line coord_polar () I get this chart:
This is what I pretend:
Thank you!
As you did not provide sample data, I have used some other sample data. Perhaps this will meet your needs. Please modify as necessary.
library(ggrepel)
library (ggplot2)
df = read.csv("https://www.dropbox.com/s/lc3xyuvjjkyeacv/inputpie.csv?dl=1")
df <- df %>% group_by(fac) %>%
mutate(
facc = ifelse(fac=="f1", "15/16 to 19/20", "20/21"),
cs = rev(cumsum(rev(per))),
text_yp = per/2 + lead(cs, 1),
text_yp = if_else(is.na(text_yp), per/2, text_yp)
) %>% data.frame()
df$type <- factor(df$type, levels=unique(df$type))
ggplot(df, aes(x="", y=per, fill=type )) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
facet_grid(facc~. ) +
scale_fill_brewer(palette="Paired") +
theme_void() +
geom_label_repel(
aes(label = text_y, y = text_yp), show.legend = FALSE
) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme(legend.text = element_text(size = 8, colour = "black")) +
#theme(axis.text = element_text(size = 8, colour = "black")) +
#theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))

R Stacked percentage bar plot with two factor variables - How to label the % inside the plot, without decimal cases?

How can I put the labels inside the plot without decimal cases, in both bars?
This is my code:
dados_gráfico_cursoanteriorsatisfação_PA <- PA_dados_desde_2015 %>%
filter(!is.na(qsd_3PA_curso_anterior_satisfação_rec)) %>%
group_by(anoletivo_cat) %>%
count(anoletivo_cat, qsd_3PA_curso_anterior_satisfação_rec) %>%
mutate(pct = n / sum(n), pct_label = scales::percent(pct))
dados_gráfico_cursoanteriorsatisfação_PA$qsd_3PA_curso_anterior_satisfação_rec <- factor(dados_gráfico_cursoanteriorsatisfação_PA$qsd_3PA_curso_anterior_satisfação_rec, levels = c("Very satisfied", "Satisfied", "Insatisfied", "Very insatified"))
ggplot(dados_gráfico_cursoanteriorsatisfação_PA, aes(x= anoletivo_cat, fill = qsd_3PA_curso_anterior_satisfação_rec, y = pct)) +
geom_bar(position = "fill", stat="identity", width = 0.5) +
geom_text(aes(label = paste(pct_label), y = pct), position = position_fill(vjust = 0.5), colour = "black", size = 3.2) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme_void() + scale_fill_brewer(palette="Paired") +
theme(legend.text = element_text(size = 8, colour = "black")) +
theme(axis.text = element_text(size = 8, colour = "black")) +
theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))
This is the plot I'm getting:
Thank you in advance! :)

Center geom_text on ggplot while controlling bar width

I am trying to make a horizontal bar chart in ggplot2 where the bars are of equal width and with text labels centered on the bars. There are two groups on the y axis -- one with 2 bars, and one with three.
There are a lot of similar questions on SO that address both of these issues, but I haven't been able to fix one without breaking the other. Here's my data:
## data
df <- tibble(var1 = c("a", "b", "b", "c", "c"),
var2 = c("x", "y", "x", "y", "x"),
proportion = c(100, 33.3, 66.7, 66.7, 33.3)) %>%
mutate(var1 = factor(var1, levels = var1_order))
var1_order <- c("a", "c", "b")
Here's an example where the widths are good, but the labels of the y group are off:
## labels bad
df %>%
ggplot(aes(x = proportion, y = var2, fill = var1,
label = paste0(round(proportion, 1), "%"))) +
geom_col(position = position_dodge2(preserve = "single", padding = 0), width = .9) +
geom_text(size = 3, position = position_dodge2(width = 0.9), hjust = -.5,
color = "black", aes(group = var1)) +
scale_fill_manual(name = "", values = c("#093D6E","#5D8AA8", "#00918B",
"#F8AF54", "#CD9575")) +
labs(x = NULL) +
theme(axis.ticks = element_blank(),
axis.title.y = element_blank(),
axis.line=element_blank(),
axis.text.x = element_blank(),
panel.background = element_blank(),
strip.text = element_text(size = 7, face = "bold")) +
scale_x_continuous(expand = c(.2, .2)) +
guides(fill = guide_legend(reverse = TRUE))
And here's an example where the labels are good but the widths are now off:
## col widths bad
df %>%
ggplot(aes(x = proportion, y = var2, fill = var1,
label = paste0(round(proportion, 1), "%"))) +
geom_col(position = position_dodge(width = 0.9)) +
geom_text(size = 3, position = position_dodge(width = 0.9), hjust = -.5,
color = "black", aes(group = var1)) +
scale_fill_manual(name = "", values = c("#093D6E","#5D8AA8", "#00918B",
"#F8AF54", "#CD9575")) +
labs(x = NULL) +
theme(axis.ticks = element_blank(),
axis.title.y = element_blank(),
axis.line=element_blank(),
axis.text.x = element_blank(),
panel.background = element_blank(),
strip.text = element_text(size = 7, face = "bold")) +
scale_x_continuous(expand = c(.2, .2)) +
guides(fill = guide_legend(reverse = TRUE))
Note that this will be part of a parameterized report, so it needs to be capable of dealing with different numbers of var1 and var2 groups. Thanks!
Try this approach. You can use position_dodge2() to keep uniform bars. Here the code:
library(ggplot2)
#Code
df %>%
ggplot(aes(x = proportion, y = var2, fill = var1,
label = paste0(round(proportion, 1), "%"))) +
geom_col(position = position_dodge2(preserve = 'single',width = 0.9)) +
geom_text(size = 3, position = position_dodge2(preserve = 'single',width = 0.9), hjust = -.5,
color = "black", aes(group = var1)) +
scale_fill_manual(name = "", values = c("#093D6E","#5D8AA8", "#00918B",
"#F8AF54", "#CD9575")) +
labs(x = NULL) +
theme(axis.ticks = element_blank(),
axis.title.y = element_blank(),
axis.line=element_blank(),
axis.text.x = element_blank(),
panel.background = element_blank(),
strip.text = element_text(size = 7, face = "bold")) +
scale_x_continuous(expand = c(.2, .2)) +
guides(fill = guide_legend(reverse = TRUE))
Output:

ggplot facet_wrap as_labeller does not display the new sequence

I created a vector of ordered names and tried to replace each panel title with the ordered one (e.g., Jessie with 1. Jessie, Marion with 2.Marion, etc.). But, I am getting NAs for each panel title instead. Any hints what is going wrong.
With the NAs
With the labeller commented out
list.top.35.names.ordered <- data.frame( cbind(order = c(1:35),list.top.35.names)) %>%
unite( name.new, c("order" ,"list.top.35.names"), sep = ".")
list.top.35.names.ordered <- list.top.35.names.ordered$name.new[1:35]
str(list.top.35.names.ordered)
chr [1:35] "1.Jessie" "2.Marion" "3.Jackie" "4.Alva" "5.Trinidad" "6.Ollie" ...
data.babyname.all %>%
ggplot( mapping = aes(x = year, y = perc, fill = sex)) +
geom_density(stat = "identity", position = "stack" , show.legend = F ) +
facet_wrap(~name, ncol= 7, nrow =5, labeller= as_labeller(list.top.35.names.ordered)) +
scale_fill_manual(values = c('#E1AEA1','#9ABACF')) +
geom_point(data = most.unisex.year.and.value, mapping = aes(x = year, y = perc),
size = 3,
fill = "white",
color = "black",
shape = 21) +
scale_y_continuous(breaks = c(0,.50,1), labels= c("0%", "50%","%100")) +
scale_x_continuous(breaks = c(1940, 1960, 1980,2000), labels= c('1940', "'60","'80",'2000')) +
geom_text(mapping = aes(x =x , y = y , label = label), check_overlap = F, na.rm = T, position = position_dodge(width=.9), size=3) +
theme_minimal() + #set theme
theme(
text = element_text(size = 10),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank(),
plot.background = element_blank(),
axis.ticks.x = element_line(color = "black"),
axis.ticks.length =unit(.2,'cm'),
strip.text = element_text(size = 10, margin = margin(l=10, b = .1)))

ggplot pie chart choose axes ticks

I would like to know if it's possible to modify the ticks of x axis with a ggplot pie chart.
Here what I can do :
# Some colors
couleurs <- data.frame(
id=seq(1,17,1),
mix=c(c(rep(1,6),rep(2,7),rep(3,4))),
html=c("#A00020","#109618","#388EE4","#C484D1","#FFAA33","#CCCDD0","#004AC5","#F80094","#CB5023","#638995","#33CFCF","#95DC4E","#F7D633","#5C403C","#F72020","#00D96C","#FDE4C5")
)
couleurs$html <- factor(couleurs$html, levels = couleurs$html[order(couleurs$id, decreasing = FALSE)])
# Data
activite <- data.frame(label=c("B to B","B to C","B to B / B to C", "B to B"), cible=c(rep("Externe",3), "Interne"), nb=c(12,9,3,12))
activite$label <- factor(activite$label, levels = activite$label[order(activite$nb[activite$cible=="Externe"], decreasing = TRUE)])
library(plyr)
activite<-ddply(activite,.(cible),transform,pc=(nb/sum(nb))*100)
activite
# Pie chart
library(ggplot2)
ggplot(data = activite, aes(x = "", y = nb, fill = label )) +
geom_bar(stat = "identity", position = position_fill(), width = 1) +
coord_polar(theta= "y", start = 0, direction = -1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white", fontface = "bold", position = position_fill(vjust = 0.5)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_line(colour = "grey75")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.length = unit(0, "mm")) +
theme(axis.title.x = element_blank(),axis.title.y = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Here my result:
After several hours of serach, I didn't find a solution to create what I want. The exact same pie chart but with personalised ticks like that :
With these particular conditions :
- do not change the direction of the data in the pie chart, I want it like exactly this
- if possible (but if not possible, it's okay), I would like the ticks' labels not superposed with the axis.
If someone can help me, I would really appreciate.
Here's one solution:
ggplot(data = activite %>%
group_by(cible) %>%
arrange(desc(nb)) %>%
mutate(axis.label = cumsum(nb),
axis.position = cumsum(pc)/100) %>%
mutate(axis.label = ifelse(pc == min(pc),
paste(axis.label, "0", sep = "-"),
axis.label)),
aes(x = 1, y = nb, fill = label )) +
geom_segment(aes(x = 1, xend = 1.6, y = axis.position, yend = axis.position),
colour = "grey75") +
geom_vline(xintercept = 1.6, colour = "grey75") +
geom_bar(stat = "identity", position = position_fill(reverse = T), width = 1) +
coord_polar(theta= "y", start = 0, direction = 1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white",
fontface = "bold", position = position_fill(vjust = 0.5, reverse = T)) +
geom_text(aes(x = 1.7, label = axis.label), size = 3,
position = position_fill(reverse = T)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.text = element_blank()) +
theme(axis.ticks = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Explanation:
The sequence in your labels went clockwise, while the direction of the polar coordinates went counter-clockwise. That makes labelling rather troublesome. I switched the direction for polar coordinates, & added reverse = T inside the position adjustment calls for the geoms.
It's hard to assign different axis breaks to different facets of the same plot, so I didn't. Instead, I modified the data to include calculated axis labels / margin positions, added margins via geom_segment / geom_vline, & hid the axis text / ticks in theme().

Resources