ggplot2 coord_polar使用填充时保留顺序 [英] ggplot2 coord_polar preserve order when using fill

查看:56
本文介绍了ggplot2 coord_polar使用填充时保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

aes 指定 fill 参数会导致饼图的顺序相反,因此中断/标签将不再与饼图匹配.请参见下面的示例和结果图.

Specifying the fill argument for aes results in a reverse order of the pie chart, so the breaks/labels wont match with pie pieces anymore. Please see the example and resulting plots below.

df = data.frame(Var1 = letters[1:5], Var2 = c(6, 31, 34, 66, 77))    
df$Var1 = factor(df$Var1, levels = df$Var1, ordered = T)

# just fine, but no colors
ggplot(df, aes(x = 1,
               y = Var2)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar(theta = "y") +
  scale_fill_manual(values = c("red","green","yellow","black","white"),
                    guide_legend(title = "My_Title")) +
  scale_y_continuous(breaks = (cumsum(df$Var2) -
                                 df$Var2 / 2),
                     labels = df$Var1)

# reverse order appears
ggplot(df, aes(x = 1,
               y = Var2,
               fill = Var1)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar(theta = "y") +
  scale_fill_manual(values = c("red","green","yellow","black","white"),
                    guide_legend(title = "My_Title")) +
  scale_y_continuous(breaks = (cumsum(df$Var2) -
                                 df$Var2 / 2),
                     labels = df$Var1)

推荐答案

堆叠将以相反的顺序发生(根据v2.2.0),因此我们可以使用以下代码以原始顺序进行堆叠:

Stacking will occur in reversed factor order (per v2.2.0), and therefore we can use the following code to stack in original order:

ggplot(df, aes(x = 1,
               y = Var2,
               fill = forcats::fct_rev(Var1))) +
    geom_bar(width = 1, stat = "identity", col = 1) +
    coord_polar(theta = "y") +
    scale_y_continuous(breaks = (cumsum(df$Var2) -
                                     df$Var2 / 2),
                       labels = df$Var1)

此外,您可以使用 geom_col 代替 geom_bar(stat ="identity").

Also, you may use geom_col instead of geom_bar(stat = "identity").

这篇关于ggplot2 coord_polar使用填充时保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆