0
votes

I'm using a bar chart to show the income distribution of parking meters in a city. My data frame includes columns for parking meter ID, annual revenue for that meter, and which decile (1-10) that meter falls into based on its total revenue. So my command looks like this:

> rev <- ggplot(parking, aes(x=decile, y=revenue))
> rev + geom_bar(stat="identity")

And the result is exactly what I want, but I'd like to add the total revenue for each decile atop each bar in the graph, and I don't know how. I tried this:

> aggrev <- aggregate(revenue~decile, data=parking, sum)
> totals <- aggrev$revenue 
> rev + geom_bar(stat="identity") + geom_text(aes(label=totals))

But I get this error message: Error: Aesthetics must either be length one, or the same length as the dataProblems:totals.

I checked length(decile) and length(totals), and their values are 4600 and 10, respectively. So I understand why this is happening, but why can't I just add any 10 characters to the 10 bars? Or to get the chart to display the bar totals automatically, maybe using "identity"? I've decided to just run this:

ggplot(aggrev, aes(x=decile,y=revenue))+geom_bar()+geom_text(aes(label=revenue))

which works, but I'd rather not have to make a new dataframe each time I want to have labels.

2
You need to tell ggplot where you want the labels... how could it know you want them at the top of each bar... take a look hereJustin
Making new data frames for a new layer, or creating whole new variables is what you signed up for when you started using ggplot. It isn't called "the grammar of graphics" for nothing. If what you try isn't grammatically correct, well...joran

2 Answers

0
votes

Add the totals to the parking dataframe:

parking$totals <- aggrev$revenue 

That will allow the token "totals" to get found in the correct environment. (You may also need to specify an x and y vector.)

0
votes

Simply put, you have to have a dataset that looks like what you are plotting except it will have a variable "labels". It maps your specific label to x y coordinate. This gets a little tricky once you add facet.grid.

if your dataframe has 80 rows with 4 factors: Your label dataframe will have 80 rows of x y values as well as your factor variable + "label".

 datain <- data.frame(type=rep(c('dog','cat'),40),height=c(1,5,3,2,5,2,6,8,10,3))
 datain <- datain[order(datain$type),]


 for_text <- data.frame(type=c('dog','cat'),height=c(10.5,9),label=c('dog','cat'))
 plot <- ggplot(datain,aes(x=type,y=height)) + 
    geom_boxplot(width=1) + 
    geom_text(data=for_text,aes(x=for_text$type,y=for_text$height,label=for_text$label))

enter image description here