Plotting the sum of values in one column a dependi

2019-05-19 15:55发布

I'm pretty new to R and to ggplot coming from a spreadsheet background and I'm looking for something very easy to do in a pivot graph. I want to plot sums of values of a given column depending of the category given in another column.

Let's have an example :

element qty category
apples  2   Red
apples  1   Green
apples  4   Red
apples  3   Green
apples  6   Yellow

I want a graph which plots all the apples depending on their category not by the count in the column category but by the sum of the corresponding values in the qty column.

Meaning 6 red apples 4 green apples and 6 yellow apples... Is there some short way to do this directly in ggplot or do I need to work my data beforehand - fi. with plyr ?

Sorry if this question is a noob question but I wasn't able to find any answer...

标签: r ggplot2
1条回答
疯言疯语
2楼-- · 2019-05-19 16:14

To make Roman's comment more explicit:

# Create the data frame
element <- rep("apples", 5)
qty <- c(2, 1, 4, 3, 6)
category <- c("Red", "Green", "Red", "Green", "Yellow")
d <- data.frame(element=element, qty=qty, category=category)

The use stat="identity" to calculate the sums inside ggplot

ggplot(d, aes(x=category, y=qty)) + geom_bar(stat="identity")

enter image description here

EDIT : Missing ")" added end of the ggplot function

查看更多
登录 后发表回答