【发布时间】: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 并没有保持数据框中的顺序(示例就是这种情况)。