在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