绘图条按降序显示某列的值的计数?

时间:2016-01-22 13:12:01

标签: r plot ggplot2

给出如下数据框:

V1           V2
a            089
a            065
a            012
b            101
b            110

现在我想绘制一个条形图,第一列V1中的值的计数为y轴,它应该是降序。

我试过了:

library(ggplot2)
ggplot(data = df, aes(reorder(V1,..count..), y = ..count..) ) +geom_bar(stat = "count")

但失败并产生警告:

Warning messages:
1: In min(x, na.rm = na.rm) :
no non-missing arguments to min; returning Inf
2: In max(x, na.rm = na.rm) :
no non-missing arguments to max; returning -Inf
3: In min(diff(sort(x))) : no non-missing arguments to min; returning  Inf
4: In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'
5: Computation failed in `stat_count()`:
arguments imply differing number of rows: 0, 1 

我也尝试更改stat = "bin",但它既没有效果也没有。 你有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

如果您需要按降序排列直方图,则需要先更改V1的级别:

df$V1 <- factor(df$V1, levels = names(sort(table(df$V1), decreasing = TRUE)))

然后我们可以使用

library(ggplot2)

# with qplot
qplot(df$V1, geom="histogram") 

# with ggplot
ggplot(df, aes(V1)) + geom_histogram()

enter image description here

答案 1 :(得分:0)

您的代码建议您尝试绘制条形图而不是直方图。假设您确实正在寻找条形图,请尝试if password in data: print "Password found in data" (否则请查看stat="identity

geom_histogram

这是你在找什么?

enter image description here