如何在 ggplot 中按指定顺序绘制值向量?

How do I plot a vector of values in the specified order in ggplot?

我有一个值向量(列均值),它们都属于某个问题。我试图在 y 轴上绘制值,在 x 轴上绘制问题名称。我的数据框如下所示:

> colMeansDf
    colMeans Question
Q2  3.468240       Q2
Q3  3.677858       Q3
Q4  3.147913       Q4
Q5  3.072595       Q5
Q6  2.382940       Q6
Q7  2.556261       Q7
Q8  2.852087       Q8
Q9  2.663339       Q9
Q10 2.816697      Q10
Q11 4.735027      Q11
Q12 3.820327      Q12
Q13 3.000000      Q13
Q14 3.114338      Q14
Q15 2.806715      Q15
Q16 2.238657      Q16
Q17 3.228675      Q17
Q18 2.023593      Q18
Q19 3.986388      Q19
Q20 2.913793      Q20
Q21 2.611615      Q21
Q22 2.446461      Q22

现在,当我尝试使用 ggplot 来可视化此数据时 ggplot 似乎出于某种原因更改了数据框的顺序,而不是从 Q2 开始并在 Q22 结束,我得到从 Q10 移动到 Q19、Q2、Q20、Q21、Q22、Q23 以及从 Q3 移动到 Q9 的 x 轴。

到目前为止我的代码是这样的:

ggplot(colMeansDf, aes(x = Questions, y = colMeans)) +
    geom_point(alpha = .6) +
    labs(x = "Question", y = "Average Reponse") +
    geom_hline(yintercept = mean(colMeansDf$colMeans), color = "red") +
    scale_y_continuous(limits = c(1, 7), breaks = 1:7)

提前致谢!

您好,它正在将问题名称排序为字符串。您可以添加一个索引(仅包含问题编号)并使用该索引以数字方式重新排列问题名称。

colMeansDf <- colMeansDf %>% 
  mutate(index = as.numeric(substr(Questions,2,nchar(as.character(Questions)))),
         Questions = factor(Questions, levels=((colMeansDf %>% arrange(index))$Questions)))

ggplot(colMeansDf, aes(x = Questions, y = colMeans)) +
  geom_point(alpha = .6) +
  labs(x = "Question", y = "Average Reponse") +
  geom_hline(yintercept = mean(colMeansDf$colMeans), color = "red") +
  scale_y_continuous(limits = c(1, 7), breaks = 1:7)