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

标签 r ggplot2

指定 fill aes 的论据导致饼图的顺序相反,因此中断/标签不再与饼图匹配。请参阅下面的示例和结果图。

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)

just fine
reverse 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)

另外,您可以使用 geom_col而不是 geom_bar(stat = "identity") .

关于r - ggplot2 coord_polar 在使用填充时保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41717159/

相关文章:

r - ggplot2:将轴连接到点的线

r - 如何使用 unicode 箭头导出高分辨率 ggplot 图形

r - 绘制带有 ggplot2 错误的形状文件

r - 如何在 R 中的二进制 h2o GBM 中获得每个类的不同变量重要性?

r - 总结 dplyr 中每组的所有其他值

r - ggplot2 stat_密度2d 产生奇怪的三角形

r - 方面ggplot2的内部排序

r - 将 R 包安装到特定目录

python - 在 Keras 模型中优化准确性而不是损失

r - fastPOSIXct 相当于将非 UTC 转换为 UTC