Search code examples
rggplot2pie-chart

Creating single row pie chart for budget in R with ggplot


To start off, this is my dput:

structure(list(Income = 18000, Rent = 7300, Wifi = 477, Gas = 900, 
MTR_Bus = 600, Food = 3000, Total_Expenses = 12277, Remaining_Income = 5723), class = "data.frame", row.names = c(NA, -1L))

That comes up with a data frame like this: Data Frame

I'm trying to create a simple pie chart in R using this budget, though I just need the expenses and income (in other words, I don't need the variables "Total Expenses" or "Remaining Income").

My issue is that the best I can come up with is something like this:

bar <- ggplot(data = Budget) + geom_bar(mapping = aes(x = Total_Expenses, fill = row))+coord_polar()

I guess my question is two-fold: 1) is this the correct structure for my code and 2) what should I be using for x or fill? I didn't really have much of a good answer from my book I was using.

Thanks for any help you can give!


Solution

  • Reshape you data using e.g. tidyr::pivot_longer():

    library(tidyr)
    library(dplyr)
    library(ggplot2)
    
    budget_pie <- Budget %>% 
      pivot_longer(everything()) %>% 
      filter(!grepl("^(Total|Remaining)", name))
    
    ggplot(data = budget_pie, aes(x = "", y = value, fill = name)) +
      geom_col() +
      coord_polar("y", start = 0)