Home > Mobile >  How to implement small graphs to show distribution of spending in multiple categories
How to implement small graphs to show distribution of spending in multiple categories

Time:08-24

10 people submitted monthly spending patterns for four categories of spending, "gas, groceries, restaurants, and entertainment (ent)".

I would like to show a small grid of graphs summarizing the spending so you can see in each category the distribution of the spending.

Here are the issues with my code below.

  1. The four separate graphs with the shared x-axis are good. However, I want the y-axis to reflect the amount of people at that level of spending, not four categories as it does now.

  2. Looking at "grocery" for example, it appears there are some people with negative spending. I guess this is an artifact of using, geom_density_ridges. What would be a better choice?

library("tidyverse")
library("ggridges")

spend_df <- tibble(
  gas = c(100, 100, 100, 100, 100, 100, 100, 100, 100, 100),
  grocery = c(200, 200, 200, 500, 500, 500, 1200, 1200, 1200, 2200),
  ent = c(0, 0, 50, 50, 50, 50, 1000, 1100, 1200, 3000),
  restaurant = c(500, 0, 50, 2000, 20, 120, 220, 5, 250, 1000)
)

# Make long
spend_long <- spend_df |> 
  gather(category, category_monthly_spend, gas:restaurant) 

# Reorder ridgelines
spend_long$category <- factor(spend_long$category,
                              levels = c("gas", "grocery", "restaurant", "ent"))

ggplot(spend_long, aes(x = category_monthly_spend, y = category))   
  geom_density_ridges()   facet_wrap(~category)

CodePudding user response:

Assuming that your real data has more than 10 observations, and that you do want a density-like visualization of distribution, perhaps just geom_density with facets could work?

You may also want to experiment with scales = "free_y" in the facets.

spend_long %>% 
  ggplot(aes(category_monthly_spend))   
  geom_density()   
  facet_wrap(~category)

Result:

enter image description here

  • Related