我想按照现在的顺序绘制这个data.frame的条形图:
df <- data.frame(y=rnorm(5),row.names=c("C","G","D","A","R"))
高度应为y,x应为行名。
我尝试过以下尝试但没有成功:
df$labels <- row.names(df)
ggplot(df, aes(x = labels, y = y)) + geom_bar(stat = "identity")
ggplot(df, aes(x = factor(labels, ordered = TRUE), y = y)) + geom_bar(stat = "identity")
df <- within(df, labels.factor <- factor(labels, levels=labels, ordered=T))
ggplot(df, aes(x = labels.factor, y = y)) + geom_bar(stat = "identity")
所以我的问题是:为什么我的“订单”会被忽略?我该怎么做呢?我确信我错过了一些明显的东西,因为它是如此基本。提前谢谢。
编辑:我在R会话中犯了一个错误并且监督了一个提议的解决方案确实有效。谢谢@jlhoward和user2633645。
答案 0 :(得分:1)
尝试:
df <- data.frame(cbind(x = c("C","G","D","A","R"), y=rnorm(5)), stringsAsFactors = FALSE)
head(df)
df$x <- factor(df$x, levels = c("C","G","D","A","R"))
levels(df$x)
class(df$y)
df$y <- as.numeric(df$y)
ggplot(df, aes(x = x, y = y)) + geom_bar(stat = "identity")