ggplot piecharts on a ggmap: labels destroy the small plots

我只是一个虾纸丫 提交于 2019-11-29 05:20:36

Short answer:

I think the problem is actually in your earlier line:

geom_bar(position = "fill", alpha = 0.5, colour = "white", stat="identity") +

If you change the position from fill to stack (i.e. the default), it should work properly (at least it did on mine).

Long(-winded) explanation:

Let's use a summarised version of the mtcars dataset to reproduce the problem:

dfm <- mtcars %>% group_by(cyl) %>% summarise(disp = mean(disp)) %>% ungroup()

# correct pie chart
ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "stack") + 
  geom_text(position = position_stack(vjust = 0.5)) + 
  coord_polar(theta = "y") + theme_void()

# "empty" pie chart
ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "fill") + 
  geom_text(position = position_stack(vjust = 0.5)) + 
  coord_polar(theta = "y") + theme_void()

Why does changing geom_bar's position affect this? If we look at the plot before the coord_polar step, things may become clearer:

ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "stack") + 
  geom_text(position = position_stack(vjust = 0.5))

Check the bar chart's y-axis. The bars & the labels are correctly positioned.

Now the version with position = "fill":

ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "fill") + 
  geom_text(position = position_stack(vjust = 0.5))

Your bar chart now occupies the range 0-1 on the y-axis, while your labels continue to occupy the original full range, which is much larger. Thus when you convert the chart to polar coordinates, the bar chart is squeezed to a tiny slice that becomes practically invisible.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!