我目前正在学习r,并且我有一个数据框,其中包含我从足球网站上抓取的数据。 每行有58列(变量,属性)。在这些变量中,我希望在单个条形图中绘制3个。我有3个重要的变量``名称'',``Goals.with.right.foot'',``Goals.with.left.foot''。 我要构建的是一个条形图,每个“名称”出现在x轴上,两个独立的条形表示其他两个变量。 样本行条目: {.......,RONALDO,10(left),5(right),............}
我尝试使用ggplot2 geom_bar玩了很多,但没有成功。 我也搜索了类似的问题,但是我不明白答案。有谁能简单地解释我该如何解决这个问题?
barplot(counts, main="Goals",
xlab="Goals", col=c("darkblue","red"),
legend = rownames(counts))
答案 0 :(得分:1)
您可以这样尝试:
我模拟了一个框架作为您的支架,只需将其替换为包含您感兴趣的列的框架:
df <- data.frame(names = letters[1:5], r.foot = runif(5,1,10), l.foot = runif(5,1,10))
# transform your df to long format
library(reshape2)
plotDf <- melt(df, variable.name = 'footing', value.name = 'goals')
# plot it
library(ggplot2)
ggplot(plotDf, aes(x = names, y = goals, group = footing, fill = footing)) +
geom_col(position = position_dodge()) #does the same as geom_bar, but uses stat_identity instead of stat_count
此图的结果: your plot
之所以可行,是因为ggplot需要一个包含y轴所需值的变量,以及一个或多个包含分组因子的变量。
使用melt
函数,您的data.frame
被合并为所谓的“长格式”,这正是数据所需的方向。