r - 为每个因素组添加单独的 vlines 到 ggplot(可变重要性随机森林的点图)

标签 r ggplot2 random-forest

我正在使用 ggplot2 从随机森林中绘制六个相关变量重要性结果的点图。我的数据(我已经使用 reshape2 将其转换为长格式)如下所示(我的真实数据集更大一些):

Factor    Group    Value
Gender      A      0.000127
Age         A      0.000383
Informant   A     -0.000191
Gender      B     -0.000255
Age         B      0.000389
Informant   B     -0.000312
Gender      C     -0.000285
Age         C      0.000389
Informant   C     -0.000282

我可以像这样制作点图:

ggplot(mydata, aes(x = Value, y = Factor, colour = Group)) + geom_point() 

这是一个不同数据集的示例: from r-bloggers.com/summarising-data-using-dot-plots

但是,我想要画一条线来指示哪些因素对每个组都很重要。如 this guide 第 4 页所述,在这样的数据集中,“如果变量的重要性值高于最低负分变量的绝对值,则变量可以被认为是信息丰富且重要的”

我想要一个看起来像上面的情节,同时每个组都有单独的重要线。这段代码让我很接近,但不会为每个组做单独的行。有人知道怎么做吗?我已经尝试将美学颜色映射到组,但显然遗漏了一些东西。

ggplot(mydata, aes(x = Value, y = Factor, colour = Group)) +
geom_point() +geom_vline(data=mydata, aes(xintercept=abs(min(Value)),
colour=Group))

最佳答案

我不确定为什么您的代码不起作用,但是 geom_vline 应用 xintercept 参数中的函数的方式出了点问题。相反,在 ggplot 之外执行此操作,为 Group 的每个级别创建一个包含 x 截距值的单独数据框,并将其提供给 geom_vline.

# Create the dotplot without the significance lines
p = ggplot(mydata, aes(x = Value, y = Factor, colour = Group)) +
           geom_point()

# Create a separate data frame with the x-intercept for each level of Group 
# (I used dplyr for this, but you can of course do this in base R, data.table, 
#  or whatever your favorite method happens to be)
library(dplyr)
signif.lines = mydata %.%
  group_by(Group) %.%
  summarise(xvalue=abs(min(Value)))

# Add significance lines to the plot using the new data frame
p + geom_vline(data=signif.lines, aes(xintercept=xvalue, colour=Group))

enter image description here

关于r - 为每个因素组添加单独的 vlines 到 ggplot(可变重要性随机森林的点图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24015834/

相关文章:

python - 随机森林 : Effect of Number of Samples in Each Class

r - 桶中的数据分类

r - 将浮雕(GEOtiff,.tif)添加到瑞士国家边界的 ggplot((多边形)shapefile,.shp)

R 重新编码变量 - 意外的 INCOMPLETE_STRING

r - 使用 plotly::rangeslider 时放大 y 轴

r - R 中的判别分析(FDA 和 MDA)图

R 包 'randomForest' 未安装

python - 为什么 sklearn 预处理 LabelEncoder inverse_transform 仅适用于一列?

r - 带有基于顺序的数字的分类列的前缀标签

r - 使用 sapply() 在两个参数上循环 uniroot()