Home > Blockchain >  How to use two bars that are diferent variables in R?
How to use two bars that are diferent variables in R?

Time:05-05

I have this table:

enter image description here

And what I want to do is a side-by-side bar plot using ggplot function.

So far, I got this:

data1 %>% 
  ggplot(aes(x = Countries))   
  geom_bar(aes(y = A2004),width=.5, position='dodge', stat='identity', fill = "blue")  
  geom_bar(aes(y = A2018),width=.5, position='dodge', stat='identity', fill = "red")

But what I got was enter image description here

How can I put the bars for A2004 and A2018 side-by-side and not inside one another?

CodePudding user response:

The easiest way to do this is to pivot your data into long format and map the fill aesthetic to the resulting names column:

library(tidyverse)

data1 %>%
  pivot_longer(-1) %>%
  ggplot(aes(Countries, value, fill = name))  
  geom_col(position = "dodge")  
  scale_fill_manual(values = c("red", "blue"))


Reproducible data taken from image in question

data1 <- data.frame(Countries = c("SI - Eslovenia", "Gr - Grecia", 
                                  "CZ - Republica Checa"),
                    A2004 = c(2.9, 3, 2.9),
                    A2018 = c(4, 4.2, 2.6))

data1
#>              Countries A2004 A2018
#> 1       SI - Eslovenia   2.9   4.0
#> 2          Gr - Grecia   3.0   4.2
#> 3 CZ - Republica Checa   2.9   2.6
  • Related