ggplot2堆积的条形填充顺序不一致

时间:2019-01-08 15:31:59

标签: r ggplot2

我正在尝试制作this article

中所述的不同的堆积条形图

我的数据在这里,三列。 variable是所提出问题的标签。 value是李克特量表的响应。 n是计数,已经根据要显示在刻度的哪一侧而正或负。我有两个中性类别,以使中性以0为中心。

final = structure(list(variable = c("Optimism", "Optimism", "Optimism", 
"Market Insight", "Market Insight", "Market Insight", "Market Insight", 
"Courage", "Courage", "Courage", "Courage", "Adaptability", "Adaptability", 
"Adaptability", "Adaptability", "Bias for Action", "Bias for Action", 
"Bias for Action", "Optimism", "Optimism", "Market Insight", 
"Market Insight", "Courage", "Courage", "Adaptability", "Adaptability", 
"Bias for Action", "Bias for Action"), value = structure(c(6L, 
5L, 1L, 6L, 5L, 1L, 2L, 6L, 5L, 1L, 2L, 6L, 5L, 1L, 2L, 6L, 5L, 
1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L), .Label = c("Strongly Disagree", 
"Disagree", "Disagree Neutral", "Agree Neutral", "Agree", "Strongly Agree"
), class = c("ordered", "factor")), n = c(36, 110, -1, 22, 84, 
-1, -3, 35, 107, -1, -3, 53, 103, -1, -2, 42, 100, -1, 15, -14, 
30, -29, 16, -15, 10, -10, 16, -16)), .Names = c("variable", 
"value", "n"), row.names = c(NA, -28L), class = "data.frame")

请注意,value已经是一个有序因素,顺序是正确的,从“强烈不同意”变为“强烈同意”。

class(final$value)
#> [1] "ordered" "factor"
levels(final$value)
#> [1] "Strongly Disagree" "Disagree"          "Disagree Neutral"  "Agree Neutral"     
#> [5] "Agree"             "Strongly Agree" 

我这样制作ggplot

ggplot(data = final, aes(y = n, x = variable, fill = value)) + 
  geom_col() +
  coord_flip() + 
  scale_fill_manual(values = c("Strongly Disagree" = "#CA0020",
                         "Disagree" = "#F4A582",
                         "Disagree Neutral" = "#C0C0C0",
                         "Agree Neutral" = "#C0C0C0",
                         "Agree" = "#92C5DE",
                         "Strongly Agree" = "#0571B0"))

在生成的绘图中,图例正确排序,负数正确排序,但正数排序错误。是什么导致排序顺序不匹配,如何解决? ggplot output

0 个答案:

没有答案