I want to plot a count of the program variable and also include total expenditure for each program.
projects <- read.table(text="
program Expense
schools 15000
hospitals 180000
forest 30000
marine 200000
schools 7000
marine 29000
forest 4300
forest 1800
schools 1789",header=TRUE)
What I did:
projects |>
group_by(program)|>
summarise(count=n())|>
ggplot(aes(x = reorder(program,(-count),decreasing=T), y = count, fill= "grey")) +
geom_bar(stat = 'identity') +
theme_clean()+
coord_flip()
The above plot turned out fine.
But I also want to add the total expense for each program in the plot. so I added the following
projects |>
group_by(program)|>
summarise(count=n())|>
ggplot(aes(x = reorder(program,(-count),decreasing=T), y = count, fill= "grey")) +
geom_bar(stat = 'identity') +
theme_clean()+
coord_flip() +
geom_text(aes(label = sum(`expense`)))
but r screamed backed at me
When you ran the summarise
in your pipeline the Expense
variable was dropped from the dataframe. You should have included:
summarise(count=n(), expense=sum(Expense))|>
And then you could use:
geom_text(aes(label = expense))