从ggplot上的data.frame订购

时间:2018-01-04 13:33:55

标签: r dataframe ggplot2 geom-bar

我有数据框:

values <- c("a", "d", "b", "c", "e", "f")
n <- c(1463, 159, 54, 52, 52, 220)
frequency <- c(0.7315, 0.0795, 0.027, 0.026, 0.026, 0.11)
tmp <- as.data.frame(cbind(values, n, frequency))

我想绘制这些数据的geom_bar(x =值,y =频率),但绘图的数据应该按照数据框(a,d,b,c,e,f)的顺序排序。不幸的是ggplot自动排序列值,我得到(a,b,c,d,e,f)。情节代码:

ggplot(data=tmp, aes(x=values, y=frequency)) +
  geom_bar(fill="#003366", stat="identity") +
  labs(title = "...", x = "values", y = "Frequency")

我应该在情节函数中改变什么来解决我的问题?

1 个答案:

答案 0 :(得分:2)

可以使用factor函数重新排序因子级别。

values <- c("a", "d", "b", "c", "e", "f")
n <- c(1463, 159, 54, 52, 52, 220)
frequency <- c(0.7315, 0.0795, 0.027, 0.026, 0.026, 0.11)
tmp <- as.data.frame(cbind(values, n, frequency))
# reorder using factor
tmp$values = factor(tmp$values, levels = values)

ggplot(data=tmp, aes(x=values, y=frequency)) +
  geom_bar(fill="#003366", stat="identity") +
  labs(title = "...", x = "values", y = "Frequency")