【问题标题】:ggplot doesn't plot the order of the data.frameggplot 不绘制 data.frame 的顺序
【发布时间】:2018-04-18 18:15:18
【问题描述】:

如果我有一个head(df) 喜欢:

    feature Comparison   Primary       diff key
1     work  15.441176 20.588235  5.1470588   1
2 employee  22.794118 19.117647 -3.6764706   2
3     good  11.029412 11.764706  0.7352941   3
4  improve   8.088235 10.294118  2.2058824   4
5   career   2.941176  8.823529  5.8823529   5
6  manager   2.941176  8.823529  5.8823529   6

我正在尝试用以下方式绘制一些东西:

 p = ggplot(x, aes(x = feature,size=8)) + geom_point(aes(y = Primary)) +
        geom_point(aes(y=Comparison)) + coord_flip()
      ggplotly(p)

我是否遗漏了什么导致p 不绘制上面数据的顺序?剧情中的前五个是

work
train
time
skill
people

但根据 df,应该是工作、员工、良好、改进、职业。

【问题讨论】:

  • 这样的事情对你有用吗? x$feature <- factor(x$feature, levels = rev(x$feature))。另外,traintimeskillpeople 都不在您的样本数据中
  • feature的结构是什么?如果它是一个因素,它可能已经分配了特定的订单。如果您需要特定顺序,通常最简单的方法是向数据添加级别或重新排序因子
  • Featurechr 不是一个因素。训练、时间、技能、人员在df 中更进一步。我发布了head(df)
  • 在我看来,第二个解决方案 here 会起作用,在您的 ggplot 调用中使用 fct_inorder(),如下所示:p = ggplot(x, aes(x = fct_inorder(feature), size = 8)) + geom_point(aes(y = Primary)) + geom_point(aes(y = Comparison)) + coord_flip()

标签: r ggplot2 ggplotly


【解决方案1】:

这些东西称为“级别”,ggplot 使用这些东西来确定事物应该出现在图中的顺序。如果您在控制台中运行levels(x$feature),那么我敢打赌您看到的列表与图中显示的顺序相同。

要让它们按您想要的顺序显示,您只需覆盖特征列的“级别”即可。

x$feature = factor(x$feature, levels = c("work",
                                         "employee",
                                         "good",
                                         "improve",
                                         "manager"))

【讨论】:

  • 功能不是一个因素。功能只是chr。如果我做levels(x$feature) 我得到NULL。如果我这样做了 is.factor(x$feature) = FALSE
  • 哦,好的。我不好。上面的代码应该仍然可以工作。它将 x$feature 转换为因子并设置级别。
  • 我正在使用先验函数,该函数先根据 Primary 然后比较对 df 进行排序。这也在 Shiny 应用程序中,因此 df 是响应式的并且会发生变化,因此无法硬编码级别。
  • 将您的解决方案与 Mike H 结合起来。评论虽然有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
相关资源
最近更新 更多