在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的样子:
是否有更简单的方法尝试这样做?或者我的矩阵/载体有什么误解?谢谢。
你试图在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")
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轴上结束。然后,您只需将可视化类型添加到绘图中。