r - 带有完整饼图的多个ggplot饼图

标签 r ggplot2

我想使用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

但这会产生:enter image description here

编辑:Changing facet_grid(facets=. ~ City)facet_grid(City ~ ., scales = "free")可以工作,但它会生成垂直堆积的图表,如下所示:

enter image description here

关于如何生成两个水平的整个饼图有什么建议吗?

数据如下:
> 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")

最佳答案

要显示每个方面的相对比例,一种选择是使用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))

enter image description here

关于r - 带有完整饼图的多个ggplot饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42489277/

相关文章:

r - 世界地图 - 使用 ggplot2 将国家的一半映射到不同的颜色

r - 对颜色/流程进行分组,以便条形图创建第一个条形图

r - ggplot2:使用 stat_summary() 时绘制条形图

r - ggplot2 中汇总统计的图例

r - 将世界地图分为特定国家/地区的面板

r - 如何将标签放置在远离饼图的位置

r - ggplot 图例中重叠的形状和字符

R:使用 if/else 将列附加到具有不同长度对象的列表中

根据向量的第一个字符在 R 中重新编码变量

r - 使用 stat_summary 在线图上的形状