汇总条形图的值

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

在R中,我试图制作一个bar plot,它聚合图表中共享变量的值,如下所示:

counts3 <- aggregate(x = data1$Annualized.Booking, by = list(data1$Country), FUN = sum)
barplot(counts3, main="Booking Distribution by Region",
    xlab="Regions", ylab="Annualized Bookings")

但是,我收到此错误消息:

这说明它不是矩阵,我不明白。作为参考,这是count3的样子:

是否有更简单的方法尝试这样做?或者我的矩阵/载体有什么误解?谢谢。

r plot bar-chart
2个回答
0
投票

你试图在barplot上使用data.frame。尝试使用命名向量或矩阵。

示例,包含一些示例数据:

counts3 <- data.frame(Group.1 = c("A", "B", "C", "D"), x = c(10, 20, 5, 15))

你的错误:

barplot(counts3, main = "Booking by Region", xlab = "Regions", ylab = "Value")
# Error in barplot.default(counts3, main = "Booking by Region", xlab = "Regions", :
#   'height' must be a vector or a matrix

试试这个:

barplot(with(counts3, setNames(x, Group.1)), main = "Booking by Region",
        xlab = "Regions", ylab = "Value")

enter image description here


0
投票

barplot需要向量作为输入,但aggregate返回一个数据帧。因此,在调用barplot时,您需要显式访问向量。例如:

data1 <- data.frame(bookings = c(100, 200, 300, 100, 200, 300),
                    country = c("a", "b", "a", "a", "b", "b"))

c3 <- aggregate(data1$bookings, list(data1$country), sum)

barplot(c3$x, names.arg = c3$Group.1)

看看ggplot可能是值得的,ggplot具有非常富有表现力的图形语法,例如:它会自动执行聚合步骤。使用上面定义的data1数据框,这将生成您正在寻找的条形图:

library(ggplot2)
ggplot(data = data1, aes(x = country, y = bookings)) + geom_col()

这里发生的是,你首先告诉R你想要用data1作为输入数据做一个ggplot,并且country应该在x轴上结束,而bookings应该在y轴上结束。然后,您只需将可视化类型添加到绘图中。

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