我想使用ggplot2
制作两个并排的饼图,但我很难将两个饼图“整个”
以下是我的数据示例。
> test
New York Berlin group
1 474 755 Never Visited
2 214 123 Visited Once
3 66 122 Visited > 1
4 142 64 Resided
当我尝试:
pie <- ggplot(data = melted2, aes(x = "", y = Cnt, fill = Type )) +
geom_bar(stat = "identity") +
geom_text(aes(label = Cnt), position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y") +
facet_grid(facets=. ~ City) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank()) + theme(legend.position='bottom') + guides(fill=guide_legend(nrow=2,byrow=TRUE))
pie
编辑: Changing facet_grid(facets=. ~ City)
到facet_grid(City ~ ., scales = "free")
有效,但它会生成垂直堆叠的图表,如下所示:
有关如何生成两个横向的整个饼图的任何建议吗?
以下是数据:
> dput(melted2)
structure(list(Type = structure(c(1L, 4L, 3L, 2L, 1L, 4L, 3L,
2L), .Label = c("Never Visited", "Resided", "Visited > 1", "Visited Once"
), class = "factor"), City = structure(c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L), .Label = c("New York", "Berlin"), class = "factor"),
Cnt = c(474L, 214L, 66L, 142L, 755L, 123L, 122L, 64L)), row.names = c(NA,
-8L), .Names = c("Type", "City", "Cnt"), class = "data.frame")
答案 0 :(得分:5)
要显示每个方面的相对比例,一个选项是使用position_fill
。它适用于条形和文本堆叠。
ggplot(data = melted2, aes(x = "", y = Cnt, fill = Type )) +
geom_bar(stat = "identity", position = position_fill()) +
geom_text(aes(label = Cnt), position = position_fill(vjust = 0.5)) +
coord_polar(theta = "y") +
facet_wrap(~ City) +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank()) +
theme(legend.position='bottom') +
guides(fill=guide_legend(nrow=2, byrow=TRUE))
答案 1 :(得分:2)
如果您将比例提供给ggplot2
,则有效:
library(dplyr); library(ggplot2)
melted2 <- melted2 %>% group_by(City) %>% mutate(per = Cnt/sum(Cnt))
pie <- ggplot(data = melted2, aes(x = "", y = per, fill = Type)) +
geom_bar(stat = "identity") +
geom_text(aes(label = Cnt), position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y") +
facet_grid(facets=. ~ City) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank()) + theme(legend.position='bottom') + guides(fill=guide_legend(nrow=2,byrow=TRUE))
pie
答案 2 :(得分:0)
也许这就是你要求的(显示百分比而不是计数):
library(tidyverse)
melted3 <- melted2 %>% group_by(City) %>% mutate(Percent = Cnt / sum(Cnt))
pie <- ggplot(data = melted3, aes(x = "", y = Percent, fill = Type)) +
geom_bar(stat = "identity") +
geom_text(aes(label = round(Percent, digits = 2)), position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y") +
facet_grid(facets = . ~ City) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank()) + theme(legend.position = 'bottom') + guides(fill = guide_legend(nrow = 2, byrow = TRUE))