在R中使用plot
会导致x轴上的因子按字母顺序排列。如何在R中重新排列图中的x轴?
如何指定x轴上的因子顺序?
例子:
y <- 1:9
x <- c(rep("B", 3), rep("A", 3), rep("C", 3))
plot(y ~ as.factor(x))
这导致:
我如何能得到这个情节为 “B”, “A”, “C”?
在R中使用plot
会导致x轴上的因子按字母顺序排列。如何在R中重新排列图中的x轴?
如何指定x轴上的因子顺序?
例子:
y <- 1:9
x <- c(rep("B", 3), rep("A", 3), rep("C", 3))
plot(y ~ as.factor(x))
这导致:
我如何能得到这个情节为 “B”, “A”, “C”?
你只需要按你想要的顺序指定你的因子的水平。所以我在这里创建一个新的变量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
功能现在可以按预期。
plot(y ~ x1)
看起来你想以某种形式的顺序来绘制它们,基于每个盒子的50%的价值?以不同的数据帧为例:
temp <- structure(list(
Grade = c("U","G", "F", "E", "D", "C", "B", "A", "A*"),
n = c(20L, 13L, 4L, 13L, 36L, 94L, 28L, 50L, 27L)),
.Names = c("Grade", "n"),
class = c("tbl_df", "data.frame"),
row.names = c(NA, -9L))
如果我们绘制这一点,我们可以看到,标签搞砸了(A来之前A *)。
library(ggplot2)
ggplot(temp) +
geom_bar(stat="identity", aes(x=Grade, y=n))
我们可以手动订购如上图所示,或者我们可以决定绘制年级学生获得各等级人数顺序。这也可以手动完成,但它会更好,如果我们能自动完成:
首先我们为了数据帧:
library(dplyr)
temp <- temp %>% arrange(n)
然后我们改变Grade
柱内的各级代表的顺序数据
temp$Grade <- as.vector(temp$Grade) #get rid of factors
temp$Grade = factor(temp$Grade,temp$Grade) #add ordered factors back
运行上述所示相同的图形命令提供具有不同有序x轴绘制的数据。
这里更多讨论:http://stackoverflow.com/questions/11587111/setting-levels-when-creating-a-factor-vs-levels – harkmug