如何在 R 中使用两个不同变量的条形图?

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

我有这个table:

enter image description here

我想做的是使用 ggplot 函数绘制并排条形图。

到目前为止,我得到了这个:

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

但我得到的是 enter image description here

如何将 A2004 和 A2018 的条形并排放置,而不是彼此放在一起?

最简单的方法是将数据转换为长格式并将填充美学映射到生成的名称列:

library(tidyverse)

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


从有问题的图像中获取的可重现数据

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