enderland
enderland

Reputation: 14135

Plot Average Values in R Based on Column Headings

Ok this should be easy but I can NOT figure it out. I have data that is called avePrice (using diamond information in ggplot2):

Fair      Good Very Good   Premium     Ideal 
282.0    3050.5    2648.0    3181.0    1809.0

I want to plot, using the headings (the first row) on the x-axis as labels and the values (second row) on the y-axis.

This seems it should be easy in R but I cannot seem to figure it out!

I can do this

qplot(x=c("Fair", "Good", "Very Good", "Premium",  "Ideal"), y=avePrice, geom="bar", xlab="Diamond Cut", ylab="Average Price")

which works, but it would seem there HAS to be a simple way to do this without typing in the xlabels manually? Hopefully?

Thanks in advance... I'm expecting to feel dumb when someone points out how :)

Clarification: I know I can move the x=c("Fair...") stuff out of the qplot command and have it elsewhere, but I still am having to manually enter it at that point.

Upvotes: 2

Views: 5631

Answers (2)

Ramnath
Ramnath

Reputation: 55695

You can directly plot this using ggplot2 without having to calculate the average prices by cut. Here is a one-liner

qplot(cut, price, data = diamonds, stat = 'summary', fun.y = 'mean')

Upvotes: 3

Justin
Justin

Reputation: 43255

ggplot generally wants data in columns of the data frame.

df <- data.frame(Fair=282.0, Good=3050.5, Very.Good=2648.0, Premium=3181.0, Ideal=1809.0)

df.fix <- data.frame(grades=names(df), avePrice=t(df), row.names=NULL)

qplot(grades, avePrice, data=df.fix, geom='bar', stat='identity')

But in one line:

qplot(x=names(df), y=t(df), geom='bar', stat='identity')

Upvotes: 2

Related Questions