ggplot2:改变轴上因子变量的显示顺序 [英] ggplot2: change order of display of a factor variable on an axis

查看:1477
本文介绍了ggplot2:改变轴上因子变量的显示顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 geom_tile() ggplot2 和离散标度时,标签在x轴上按升序排列,并且在y轴上按降序排列:

When I use geom_tile() with ggplot2 and discrete scales the labels are in ascending order on the x-axis and in descending order on the y-axis:

#some sample data
a <- runif(400)
a <- matrix(a, ncol=20)
colnames(a) <- letters[seq( from = 1, to = 20 )]
rownames(a) <- letters[seq( from = 1, to = 20 )]
a <- melt(a)



When I plot the dataframe a this comes out:

ggplot(a, aes(X1, X2, fill = value)) + geom_tile() + 
scale_fill_gradient(low = "white",  high = "black", breaks=seq(from=0, to=1, by=.1), name="value") + 
opts(axis.text.x=theme_text(angle=-90, hjust=0)) +
scale_x_discrete(name="") + scale_y_discrete(name="") 

以及x和y的坐标标记不同:

and the coords are labeled differently for x and y:

我希望将标签按从上到下和从左到右的顺序排列。有没有一个快速的方法来做到这一点?

I would like to have the labels sorted from a-z from top to bottom and from left to right. is there a quick way to do this?

推荐答案

这里重要的一点是因素水平的顺序。等级中的顺序也是图中的顺序。您可以使用 rev 来颠倒这个级别的顺序(注意,我只是对data.frame中的一列重新排序):

The important point here is the order of the factor levels. The order in the levels is also the order in the plot. You can use rev to reverse the order of the levels like this (note that I just reorder one column in a data.frame):

df$X1 = with(df, factor(X1, levels = rev(levels(X1))))

使用此语法根据需要对您的因素重新排序。

Use this syntax to reorder your factors as needed.

这篇关于ggplot2:改变轴上因子变量的显示顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆