1

I want to build a bar chart showing comparison of cost in combination with two variables. Data: enter image description here

Cost should be in Y' axis and Age and Gender should be in X' axis. To findout, which combination of Age and gender having more cost?

Can anyone help out on this ?

I tried:

x = c(q4$Age,q4$Gender)
y = q4$Cost
plt <- ggplot(data = q4, mapping = aes(x,y)) + geom_bar(stat = "identity")

I want help on to build Age and Gender bars should be in side by side to compare the cost of each combination of Age and Gender.

Thanks a lot for your valuable time.

krishna
  • 401
  • 6
  • 16

3 Answers3

1

You can have the use of interaction into your aes:

library(ggplot2)
ggplot(df, aes(x = interaction(age,gender), y = cost, fill = interaction(age, gender)))+
  geom_bar(stat = "identity", position = position_dodge())

enter image description here

Alternatively, you can also create a new column in your dataframe (here using the function mutate from dplyr) and plot according to this column:

library(ggplot2)
library(dplyr)
df %>% mutate(Age_Gender = paste0("Age: ",age,"\n","Gender: ",gender)) %>%
  ggplot(aes(x = Age_Gender, y = cost, fill = Age_Gender))+
  geom_bar(stat = "identity", show.legend = FALSE)+
  theme(axis.text.x = element_text(angle = 45, hjust =1))

enter image description here

Does it answer your question ?

Data

structure(list(age = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5), gender = structure(c(2L, 
1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L), .Label = c("F", "M"), class = "factor"), 
    cost = c(100, 45, 50, 56, 60, 55, 50, 70, 70, 60)), class = "data.frame", row.names = c(NA, 
-10L))
dc37
  • 15,840
  • 4
  • 15
  • 32
0

It would be a lot easier with a sample of your data. Please, use dput and check here how to make a great R reproducible example.

However, as I read your request, you can use tidyverse

I wrote the following, please try this on your data inserting your relevant covariates

#Data
attatch(mtcars)
w <- mtcars

#Script
library(tidyverse)
w %>% 
  as_tibble() %>% 
  mutate(cyl=as.character(cyl),
         vs =as.factor(vs)) %>% 
  bind_rows(., mutate(., cyl="all")) %>% 
  count(cyl, vs) %>% 
  ggplot(aes(cyl, n, color = vs, fill= vs))  +
  scale_fill_manual(values = c("#fcebeb", "#edf1f9"), name="", label=c("Text 1", "Text 2")) +
  scale_colour_manual(values = c("red", "#1C73C2"), name="", label=c("Text 1", "Text 2"))  + 
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1)) 

Which yields

enter image description here

cmirian
  • 2,572
  • 3
  • 19
  • 59
0
datax$Gender <- as.factor(datax$Gender)
ggplot(datax, aes(fill=Gender, y=cost, x=Age)) + geom_bar(position="dodge", 
stat="identity")
krishna
  • 401
  • 6
  • 16