helloworld
helloworld

Reputation: 181

Barplot averages with strings as x axis

so i'm having some trouble creating a barplot with strings as the x axis and the height as its averages.

so say i have a column called fruits = c("strawberry", "apple", "strawberry", "banana", "apple"....)

and a corresponding column with its count = c(2, 3, 4, 2,...)

I've tried doing

barplot(as.numeric(fruits$amount), names.arg = fruits$type)

but that seems gives a bar for every single occurrence of the fruit. so I'm getting 100+ bars even though i have only around 10 types of fruit.

I've also tried converting it to a table before hand and plotting that but that also doesn't work.

test <- table(as.numeric(fruits$amount), row.names = fruits$type)
barplot(test)

I'm new to R so I aplogize if this is a obvious fix/dumb question. Any suggestions? thanks!

Upvotes: 0

Views: 96

Answers (2)

d.b
d.b

Reputation: 32548

#DATA
df1 = data.frame(fruits = c("strawberry", "apple", "strawberry", "banana", "apple"), 
                 counts = c(2, 3, 4, 2, 4))

#Summarize
temp = aggregate(counts~fruits, df1, sum)

#Plot
barplot(temp[["counts"]], names.arg = temp[["fruits"]], las = 1, horiz = TRUE)

Upvotes: 1

And_R
And_R

Reputation: 1667

Maybe this would be helpful:

fruits <- data.frame(amount=c(2,3,5,1,7), type=c("Strawberry",
                                  "Apple", "Pear", "Banana", "Orange"))

b <- barplot(as.numeric(fruits$amount), names.arg = fruits$type,
        horiz = T, las=1, xlim=c(0,10), col="steelblue")

abline(v=mean(fruits$amount), col="red", lwd=2)
axis(1,mean(fruits$amount), col.axis ="red")
text(y = b, x = fruits$amount,
          pos = 4, cex = 2, col="darkblue")

The output is: enter image description here

Upvotes: 2

Related Questions