【问题标题】:Use reorder in ggplot2 wrapped in a function在包含在函数中的 ggplot2 中使用重新排序
【发布时间】:2015-10-15 06:44:37
【问题描述】:

背景

我正在构建一个函数来包装一些 ggplot2,如下所示:

df <- data.frame("Variable" = c("CHK_ACCOUNT3", "AMOUNT", "DURATION"), "Overall_Imp" = c(71.44, 54.24, 34.84))

    clevelandPlot <- function (dataFrame, xValue, yValue) {

  ggplot(data = dataFrame, aes_string(x=xValue, y=yValue)) +
    geom_segment(aes_string(yend = yValue), xend = 0, colour = "grey50") +
    geom_point(size=3) +
    scale_x_continuous(expand = c(0.01, 0)) +
    theme_bw() +
    theme(panel.grid.major.y = element_blank()) +
    xlab("Importance") +
    ylab("")

}

此功能有效:

clevelandPlot(df, "Overall_Imp", "Variable")

但是当我尝试使用以下代码重新排序值时,它不起作用:

clevelandPlot <- function (dataFrame, xValue, yValue) {

  ggplot(data = dataFrame, aes_string(x=xValue, y=reorder(yValue, xValue))) +
    geom_segment(aes_string(yend = yValue), xend = 0, colour = "grey50") +
    geom_point(size=3) +
    scale_x_continuous(expand = c(0.01, 0)) +
    theme_bw() +
    theme(panel.grid.major.y = element_blank()) +
    xlab("Importance") +
    ylab("")

}

问题

如何在 y 轴上按降序对变量重新排序(图顶部的最大值)?

【问题讨论】:

  • 一种方法应该是在您的函数内部绘图之前重新排序dataFrame 中的因子。
  • 我确实做到了。但是 ggplot2 并没有保持数据框中的顺序(示例就是这种情况)。

标签: r ggplot2


【解决方案1】:
clevelandPlot <- function (dataFrame, xValue, yValue) {

  ix <- sort.int(dataFrame[,xValue], decreasing = FALSE, index.return = TRUE)$ix
  dataFrame[,yValue] <- factor(dataFrame[,yValue], dataFrame[ix,yValue])

  ggplot(data = dataFrame, aes_string(x=xValue, y=yValue)) +
    geom_segment(aes_string(yend = yValue), xend = 0, colour = "grey50") +
    geom_point(size=3) +
    scale_x_continuous(expand = c(0.01, 0)) +
    theme_bw() +
    theme(panel.grid.major.y = element_blank()) +
    xlab("Importance") +
    ylab("")
}

clevelandPlot(df, "Overall_Imp", "Variable")

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 1970-01-01
    • 2015-05-19
    • 2021-12-09
    • 2016-06-26
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多