ggplot未按data.frame原有顺序绘图的问题排查
解决ggplot绘图未保留data.frame原始顺序的问题
我有如下data.frame的头部数据:
feature Comparison Primary diff key work 15.441176 20.588235 5.1470588 1 employee 22.794118 19.117647 -3.6764706 2 good 11.029412 11.764706 0.7352941 3 improve 8.088235 10.294118 2.2058824 4 career 2.941176 8.823529 5.8823529 5 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)但ggplot并未按照data.frame的原有顺序绘图,请问我遗漏了什么?
这个问题我之前也碰到过!核心原因很简单:你的feature列是字符型变量,ggplot默认会对字符型的分类变量按字母顺序排序,完全忽略数据框里的原始排列顺序。
给你两种简单有效的解决方法:
方法1:手动将feature转为因子并指定原始顺序
直接把feature转换成因子类型,明确告诉R因子的水平(也就是显示顺序)就是数据框里feature列的原有顺序:
# 转换feature为因子,保留原始顺序 x$feature <- factor(x$feature, levels = x$feature) # 重新运行你的绘图代码 p = ggplot(x, aes(x = feature, size=8)) + geom_point(aes(y = Primary)) + geom_point(aes(y=Comparison)) + coord_flip() ggplotly(p)
方法2:用forcats包快速处理(更简洁)
如果你已经在用tidyverse工具集,forcats包的fct_inorder()函数可以一键将字符型变量转为按出现顺序排列的因子:
library(forcats) # 按数据中出现的顺序设置因子水平 x$feature <- fct_inorder(x$feature) # 绘图代码不需要改动 p = ggplot(x, aes(x = feature, size=8)) + geom_point(aes(y = Primary)) + geom_point(aes(y=Comparison)) + coord_flip() ggplotly(p)
额外小提示:如果你的key列是用来标记顺序的,也可以用它来指定水平,比如levels = x$feature[order(x$key)],不过第一种方法直接用x$feature作为levels更直接省心。
内容的提问来源于stack exchange,提问作者Ted Mosby
相关产品推荐
相关产品推荐

