【问题标题】:R: plotting decision tree labels leaves text cut offR:绘制决策树标签会使文本被截断
【发布时间】:2013-05-01 19:37:24
【问题描述】:

(我仍在学习如何在 R 中处理图像;这是rpart package: Save Decision Tree to PNG 的延续)

我正在尝试以 PNG 形式保存 rpart 中的决策树图,而不是提供的后记。我的代码如下所示:

png("tree.png", width=1000, height=800, antialias="cleartype")
plot(fit, uniform=TRUE, 
   main="Classification Tree")
text(fit, use.n=TRUE, all=TRUE, cex=.8)
dev.off()

但是在两边的边缘节点上剪掉了一点标签。这在原始 post 图像中不是问题,我已将其转换为 png 以进行检查。我尝试在par 中同时使用omamar 设置,它们被推荐作为标签/文本问题的解决方案,并且都在图像周围添加了空白,但不再显示标签。有没有办法让文字适合?

【问题讨论】:

  • 尝试阅读包含在?plot.rpart 的文档,并特别注意margin 参数。
  • 啊,我不知道设置边距的方法有这么多。谢谢!

标签: r plot rpart


【解决方案1】:

rpart.plot 包绘制 rpart 树并自动处理 保证金及相关问题。使用rpart.plot(而不是rpart 包中的plottext)。例如:

library(rpart.plot)
data(ptitanic)
fit <- rpart(survived~., data=ptitanic)
png("tree.png", width=1000, height=800, antialias="cleartype")
rpart.plot(fit, main="Classification Tree")
dev.off()

【讨论】:

  • 这个。利润不是唯一的问题。有时情节会任意切断文本标签。
【解决方案2】:

默认边距为 0。因此,如果您的文本是一组单词或只是一个长单词,请尝试在 plot call 中放置更多边距。例如,

plot(fit, uniform=TRUE,margin=0.2)
text(fit, use.n=TRUE, all=TRUE, cex=.8)

或者,您可以通过更改文本调用中的 cex 来调整文本字体大小。例如,

plot(fit, uniform=TRUE)
text(fit,use.n=TRUE, all=TRUE, cex=.7)

当然,您可以在绘图调用中调整 mar 和在文本调用中调整 cex 以获得您想要的。

【讨论】:

    【解决方案3】:

    关于rpart man,rpart()examples 作者给出了解决方案,用xpd = NA设置par options:

    par(mfrow = c(1,2), xpd = NA)
    

    否则在某些设备上文本会被剪裁

    【讨论】:

      【解决方案4】:

      问题 tiwh titanic dataset is rplot 不会加入年龄和票价以显示 nive“年龄 > 10”标签。它将按扩展名显示它们,例如:

      年龄 = 11,18,19,22,24,28,29,30,32,33,37,39,40,42,45.5,5,56,58,60...

      标签没有空间(见图)

      bad labels

      解决方案在这里: https://community.rstudio.com/t/rpart-result-is-too-small-to-see/60702/4

      基本上,您必须将年龄和票价列转变为数值变量。喜欢:

      clean_titanic <- titanic %>% 
        select(-c(home.dest, cabin, name, x, ticket)) %>%
        mutate(
          pclass = factor(pclass, levels = c(1, 2, 3), labels = c('Upper', 'Middle', 'Lower')),
          survived = factor(survived, levels = c(0, 1), labels = c('No', 'Yes')),
          # HERE. Also notice I'm removing dots from numbers
          age = as.numeric(age),
          fare = as.numeric(fare)
        )
      

      这将为您提供更好的标签,并在情节中为它们提供空间。

      还有一件事:当您使用 as.numeric 强制使用非数值时,您可能会收到警告,并且有几种方法可以解决此问题,例如替换字符或忽略警告。忽略喜欢:

      suppressWarnings(as.numeric(age)))
      

      good plot

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-24
        • 2015-12-18
        • 2013-02-09
        • 2020-08-24
        • 2017-02-21
        • 2014-08-30
        • 2016-11-09
        • 2017-01-30
        相关资源
        最近更新 更多