Home > Mobile >  Plot a triple bar chart in R
Plot a triple bar chart in R

Time:12-30

I have a csv that looks like this:

enter image description here

I want a plot that has the countries in the x axis, and for each country, 3 bars corresponding to those variables.

I'm trying the following code:

ggplot(data, aes(x = country, y = x48), fill = "Rent price for a 1 room apartment in the center")  
    geom_bar(stat = "identity", position = "dodge")  
    geom_bar(aes(y = x49, fill = "Rent price for a 1 room apartment outside the center"), stat = "identity", position = "dodge")  
    geom_bar(aes(y = x54, fill = "Average monthly salary"), stat = "identity", position = "dodge")

But instead of getting what I want, I get the following plot:

enter image description here

It seems like an easy fix but I'm not managing to fix it.

Thank you in advance for the help.

CodePudding user response:

library(tidyverse) 

df %>%  
  pivot_longer(-country) %>% 
  ggplot()   
  aes(x = country, y = value, fill = name)   
  geom_col(position = "dodge")   
  theme_light()

enter image description here

From that, you could:

df %>%  
  pivot_longer(-country) %>% 
  ggplot()   
  aes(x = country, y = value, fill = name)   
  geom_col(position = "dodge")   
  theme_light()   
  scale_fill_discrete(name = "Metric", 
                      labels = c("1 room in the center", 
                                 "1 room outside the center", 
                                 "Average Monthly Salary"))   
  xlab("Country")   
  ylab("USD")

enter image description here

  • Related