I constructed the following data using the aggregate(,,FUN =sum) function:
structure(list(Group.1 = structure(c(1L, 2L, 3L, 1L, 2L, 3L,
1L, 2L, 3L), .Label = c("Black or African American", "White Alone",
"White Alone LR"), class = "factor"), Group.2 = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("bus", "mixed", "rail"
), class = "factor"), x = c(75143.5182835844, 198737.537113379,
46973.6469041183, 46199.2335265697, 128026.568239224, 28933.3028730992,
75876.5845180076, 495166.957025367, 5909.04640985574), pos = c(37571.7591417922,
99368.7685566897, 23486.8234520592, 98243.1350468693, 262750.821232991,
61440.2983406679, 159281.044069158, 574347.583865287, 78861.4729821454
), labe = c(" 75,144", "198,738", " 46,974", " 46,199", "128,027",
" 28,933", " 75,877", "495,167", " 5,909")), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("Group.1", "Group.2", "x", "pos",
"labe"), row.names = c(NA, -9L))
I got good code to make a pie chart here and here, which led to this:
modesplit <- ggplot(data = sums) +
geom_bar( aes(factor(1), y=x, fill=Group.2), stat="identity", position="fill") +
scale_fill_discrete(guide=guide_legend(title="Mode")) +
coord_polar(theta="y") +
facet_grid(.~Group.1, labeller = label_value) +
scale_x_discrete(name=" ", breaks = NULL) +
scale_y_continuous(name=" ", breaks = NULL)
plot(modesplit)
However when I try to add the labels:
modesplit <- ggplot(data = sums) +
geom_bar( aes(factor(1),y=x,fill=Group.2),stat="identity", position="fill") +
geom_text(aes(,y=pos, label = labe), size =5) +
scale_fill_discrete(guide=guide_legend(title="Mode")) +
coord_polar(theta="y") +
facet_grid(.~Group.1,labeller = label_value) +
scale_x_discrete(name=" ", breaks = NULL) +
scale_y_continuous(name=" ", breaks = NULL) +
plot(modesplit)
The "pie" of the pie chart vanishes:
I've tried:
scale_fill_discrete
It's a scale problem. Comment out the coord_polar
and your scale_y_continuous
, then run the code with and without the geom_text
. The position = "fill"
in geom_bar makes that add up to 1, whereas your pos
values are in the tens of thousands.
Here's a solution (edited so it puts the labels nicely in the middle now)
library(dplyr)
sums2 = sums %>% group_by(Group.1) %>%
mutate(x_scaled = x / sum(x),
pos_scaled = pos / cumsum(x_scaled) - x_scaled / 2)
modesplit <- ggplot(data = sums2, aes(x = factor(1))) +
geom_bar( aes(y=x_scaled, fill=Group.2), stat="identity", position="stack") +
scale_fill_discrete(guide=guide_legend(title="Mode")) +
coord_polar(theta="y") +
geom_text(aes(y = pos_scaled, label = labe), size =5) +
facet_grid(. ~ Group.1, labeller = label_value) +
scale_x_discrete(name=" ", breaks = NULL) +
scale_y_continuous(name=" ", breaks = NULL)
plot(modesplit)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With