如何在R中的绘图中重新排列x轴? [英] How can I reorder the x axis in a plot in R?

查看:424
本文介绍了如何在R中的绘图中重新排列x轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中使用plot会使x轴上的因子按字母顺序排序.

Using plot in R causes the factors on the x-axis to be alphabetically ordered.

如何指定x轴上因子的顺序?

How can I specify the order of the factors on the x-axis?

示例:

y <- 1:9
x <- c(rep("B", 3), rep("A", 3), rep("C", 3))
plot(y ~ as.factor(x))

结果是:

我如何将其绘制为"B","A","C"?

How can I get this to plot as "B", "A", "C"?

推荐答案

您只需要按所需顺序指定因子水平.所以在这里我创建一个新变量x1

You just need to specify the levels of your factor in the order you want. So here I create a new variable x1

x1  = factor(x, levels=c("B", "C", "A"))

其中

R> x1
[1] B B B A A A C C C
Levels: B C A

plot函数现在可以正常工作了.

The plot function now works as expected.

plot(y ~ x1)

这篇关于如何在R中的绘图中重新排列x轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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