使用R中的qplot生成矢量条形图

问题描述 投票:1回答:3

我的载体如下:

x = c(1:10)
y = c(1, 8, 87, 43, 67, 22, 99, 14, 75, 56)

我想生成一个条形图,其中x轴标记为1-10,y轴是上面y向量中每个值的高度。我尝试了几个与此类似的命令:

qplot(x, y, geom= "bar")

这会导致错误

Mapping a variable to y and also using stat="bin".
With stat="bin", it will attempt to set the y value to the count of cases in each group.
This can result in unexpected behavior and will not be allowed in a future version of ggplot2.
If you want y to represent counts of cases, use stat="bin" and don't map a variable to y.
If you want y to represent values in the data, use stat="identity".

所以,我尝试了这条消息中的两条建议。第一:

qplot(x, stat="bin", geom= "bar")

但是这导致了一个图表,其中所有10个柱都是高度为1的。第二:

qplot(x, stat="identity", geom= "bar")

但这会导致错误:as.environment(where)中的错误:'where'缺失

作为一个附带问题,我想让每个栏都不同(或至少是随机颜色)。这是直截了当的事吗?

r ggplot2
3个回答
4
投票

怎么样:

qplot(x, y, geom="bar", stat="identity")

geom="bar"很棘手,因为默认情况下它想要收集东西。如果您提供y值,则必须告诉它不要对数据应用统计量。这就是stat="identity"所做的。身份基本上意味着“不做任何事情”。如果你这样做,那么你必须指定一个y值(这是你在最后一个例子中缺少的)。要添加颜色,您可以:

qplot(x, y, geom="bar", stat="identity", fill=as.factor(x))

5
投票

有什么理由使用qplot? ggplot提供了更大的灵活性,尽管在这个简单的情况下不需要。

x = c(1:10)
y = c(1, 8, 87, 43, 67, 22, 99, 14, 75, 56)
df <- data.frame(x,y)
library(ggplot2)
ggplot(df, aes(x, y, fill = as.factor(x))) + geom_bar(stat = "identity")


1
投票

不推荐使用qplotstat参数。要使用现有数量作为条形的长度,请使用weight参数:

qplot(x, weight = y, geom = "bar")

这将为您提供通常的“计数”y轴标签。

然而,对于这种类型的数据,最明确的方法是使用col geom而不是bar,因为col期望y参数表示条/列的长度:

qplot(x, y, geom = "col")

这将使用您的变量名称而不是“count”为您提供y轴标签。

© www.soinside.com 2019 - 2024. All rights reserved.