Home > other >  How to combine 2 bar graphs
How to combine 2 bar graphs

Time:12-10

I have 2 datasets, bachelors and family.

Bachelors

Rent
150
120

Family

Rent
200
300

I wish to plot a bar graph displaying the average rent from bachelors and family. How can I do this?

CodePudding user response:

Assuming the data is in the same data.frame, you could use a dataframe where 'family' and 'bachelors' are two values in the same column. Assuming you have two dataframes bachelors and family that are identical in structure, you could do this and combine the data into one big dataframe with a column that differentiates the rows like

type rent
family 200
family 300
bachelor 150
bachelor 120

then use the fun.y parameter in geom_bar to get what you want.

library(tidyverse)

# Add a column to identify which values rent belongs to
bachelors$type <- rep('bachelor')
family$type <- rep('family')

# merge the two dataframes together
# assumes all columns are of the same type otherwise
your_data_frame <- bind_rows(family,bachelors)

# Now create the barchart with the proper aggregation argument
my_barchart <- ggplot(data = your_data_frame, aes(x = as.factor(type), y = rent))  
  geom_bar(position = 'dodge', stat = "summary", fun.y = "mean")

my_barchart 

CodePudding user response:

Using dplyr, row-bind the dataframes, summarize grouped by tenant type, then plot:

library(dplyr)
library(ggplot2)
library(scales)

bachelors <- data.frame(Rent = c(150, 120))
family <- data.frame(Rent = c(200, 300))

bind_rows(Bachelor = bachelors, Family = family, .id = "Tenant") %>% 
  group_by(Tenant) %>% 
  summarize(Rent = mean(Rent)) %>% 
  ggplot(aes(Tenant, Rent))  
  geom_col()  
  scale_y_continuous(labels = dollar)

  • Related