且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ggplot2:更改图例中的因子顺序

更新时间:2023-11-27 08:36:52

通过在因子中重新排列级别,可以更改图例标签的顺序.运行:

By reordering the levels in your factor, you can change the order of the legend labels. Run:

df$var2 <- factor(df$var2, levels=c("levelB", "levelC", "levelA"))

然后重新运行ggplot代码,现在levelB应该位于图例的顶部,绿色,levelC第二和红色,levelA第三和黑色.

Then rerun the ggplot code, and levelB should now be at the top of the legend and green, levelC second and red, and levelA third and black.