ggplot2:更改轴上因子变量的显示顺序 [英] ggplot2: change order of display of a factor variable on an axis
问题描述
当我将 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)
当我绘制数据框 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:
我希望将标签从 a-z 从上到下和从左到右排序.有没有快速的方法来做到这一点?
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屋!