简体   繁体   English

ggplot2 coord_polar 在使用填充时保留顺序

[英]ggplot2 coord_polar preserve order when using 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.aes指定fill参数会导致饼图的顺序相反,因此中断/标签将不再与饼图匹配。 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)

正好 相反的顺序

Stacking will occur in reversed factor order (per v2.2.0), and therefore we can use the following code to stack in original order:堆叠会以相反的因子顺序发生(根据 v2.2.0),因此我们可以使用以下代码按原始顺序堆叠:

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)

Also, you may use geom_col instead of geom_bar(stat = "identity") .此外,您可以使用geom_col而不是geom_bar(stat = "identity")

Another option to reverse the order of the stack would be to make use of position_stack(reverse=TRUE) :另一种反转堆栈顺序的选项是使用position_stack(reverse=TRUE)

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

library(ggplot2)

# reverse order appears
ggplot(df, aes(x = 1,
               y = Var2,
               fill = Var1)) +
  geom_bar(width = 1, 
           stat = "identity", 
           position = position_stack(reverse = TRUE)) +
  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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM