Use reorder in ggplot2 wrapped in a function

2019-09-14 15:45发布

问题:

Background

I am building a function to wrap some ggplot2 as follow:

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("")

}

This function works:

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

But when I try to reorder the values with the following code, it does not work:

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("")

}

Question

How to reorder the variable in the y axis in a decreasing order (biggest value at the top of the plot)?

回答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")



标签: r ggplot2