如何在ggplot的aes_string中调用reorder

Tin*_*esh 8 r ggplot2

我需要使用ggplot和aes_string()将条形图从高到低(从左到右)重新排序.例如,对于数据帧df < - f(X,Y,Z),可以使用

 ggplot(top10,aes(x=reorder(X,-Y),y=Y,fill=X) + geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)

但我需要通过引用数据帧的列号而不是列名来实现这一点,如下所示

 ggplot(top10, aes_string(x=colnames(top10)[num1],y=meanFeat, 
 fill=colnames(top10)[num1])) +  geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)

上面的语句使用列号绘制输出.但它不会从高到低重新排序(从左到右)

如何在aes_string中使用重新排序功能来实现这一目标?

Erd*_*kas 11

由于aes_string使用字符串,使用paste:

ggplot(top10, aes_string(x=paste0("reorder(",colnames(top10)[num1],", -Y)"),y=meanFeat,
 fill=colnames(top10)[num1])) +  geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)


MrF*_*ick 5

使用最新版本的 ggplot,您应该使用aeswith!!sym()将您的字符串转换为符号。

ggplot(top10, 
  aes(
    x = reorder(!!sym(colnames(top10)[num1]), meanFeat),
    y = meanFeat, 
    fill = !!sym(colnames(top10)[num1]))) +  
  geom_col()
Run Code Online (Sandbox Code Playgroud)

或使用.data代词

ggplot(top10, 
  aes(
    x = reorder(.data[[ colnames(top10)[num1] ]], meanFeat),
    y = meanFeat, 
    fill = .data[[ colnames(top10)[num1] ]])) +  
  geom_col()
Run Code Online (Sandbox Code Playgroud)