为每个因子组添加单独的vlines到ggplot(变量重要性随机森林的dotplot)

时间:2014-06-03 12:57:59

标签: 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页所述,在这样的数据集中,如果变量的重要性值高于最低负分数变量的绝对值,那么变量可以被认为是信息性的和重要的。 / em>的

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

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

1 个答案:

答案 0 :(得分:2)

我不确定为什么你的代码不起作用,但是geom_vlinexintercept参数中应用函数的方式出了问题。相反,请在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