背景
我正在构建一个函数来包装一些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轴中的变量进行重新排序(图表顶部的最大值)?
答案 0 :(得分:2)
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")