Q:

how to build a bar chart with multidimensional data in R

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

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.

A:

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())

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))

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))

