[英]ggplot2: change order of display of a factor variable on an axis
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: 当我使用带有
ggplot2
和离散比例的geom_tile()
,标签在x轴上按升序排列,在y轴上按降序排列:
#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: 当我绘制数据帧时
a
这就出现了:
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="")
and the coords are labeled differently for x and y: 并且对于x和y标记的coords不同:
I would like to have the labels sorted from az from top to bottom and from left to right. 我想让标签从上到下,从左到右排序。 is there a quick way to do this?
有一个快速的方法来做到这一点?
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): 您可以使用
rev
来反转这样的级别顺序(请注意,我只是重新排序data.frame中的一列):
df$X1 = with(df, factor(X1, levels = rev(levels(X1))))
Use this syntax to reorder your factors as needed. 使用此语法可根据需要重新排序因子。
For the cases where you would prefer to not modify the order of the factor in underlying data, you can get the same result using the limits
argument to scale_y_discrete
: 对于您不希望修改基础数据中因子顺序的情况,可以使用
scale_y_discrete
的limits
参数获得相同的结果:
ggplot(a, aes(X1, X2, fill = value)) +
geom_tile() +
scale_y_discrete(name="", limits = rev(levels(a$X2)))
Giving this output: 给出这个输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.