简体   繁体   中英

Plot bar chart by group side-by-side with ggplot2 in R

I have a dataframe in R with the following dataset structure (dummy data):

Years    Spain     Russia     Malta
1995     31.3      45         84.3
2009     32.4      4          90

And I want it to be plotted in a bar chart where X is the years and for the year 1995, the values of each country are represented by vertical bars side-by-side, the same for 2009. My code for plotting the data is:

ggplot(data, aes(x = years)) +
  geom_histogram(binwidth=1, position="dodge") +
  theme_minimal()

However my bar chart is being plotted like the image below, 1) where the XX has every year between, 2) no colours to differentiate countries and 3) the 3 countries are obviously not side by side for each year. How can I represent this in R?

在此处输入图像描述

What you need is a geom_bar or geom_col not geom_histogram :

First bring your data in long format with pivot_longer then use geom_col with position = "dodge :

library(tidyverse)

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM