使用ggparcoord时如何通过列名指定列并自定义顺序?
解决ggparcoord用列名指定自定义列顺序的问题
直接用列名给columns参数赋值确实不行,因为这个参数只认列索引或者预设的排序规则(比如'skewness'这类)。不过有两种标准方法可以通过列名实现自定义顺序:
方法一:用
match()把列名转成索引
把你想要的列名向量传给match(),匹配数据框的列名得到对应的索引,再传给columns参数。示例代码(用鸢尾花数据集):library(GGally) data(iris) # 自定义列名顺序 custom_cols <- c('Petal.Width', 'Sepal.Width', 'Petal.Length', 'Sepal.Length') # 转成列索引 col_indices <- match(custom_cols, colnames(iris)) ggparcoord(data = iris, columns = col_indices, groupColumn = 'Species')方法二:先重排数据框的列顺序
先把数据框的列按你想要的顺序重新排列,再直接用连续的列索引(比如1:4)绘图:library(GGally) data(iris) custom_cols <- c('Petal.Width', 'Sepal.Width', 'Petal.Length', 'Sepal.Length') # 重排数据框列 iris_reordered <- iris[, custom_cols] # 再加上分组列(如果需要的话) iris_reordered$Species <- iris$Species ggparcoord(data = iris_reordered, columns = 1:4, groupColumn = 'Species')
这两种方法都能实现用列名定义的自定义顺序,本质还是给columns传索引,但通过列名来间接指定,符合需求。
内容的提问来源于stack exchange,提问作者MDStat
相关产品推荐
相关产品推荐

