简体   繁体   中英

ggplot how to plot bar chart by multiple columns?

I have this data frame:

  District `2011` `2016` `2021`
  <chr>     <dbl>  <dbl>  <dbl>
1 YTM       44045  49046  44458
2 KC        37660  41802  40994

df <- tibble(District = c("YTM", "KC"),
       `2011` = c(44045, 37660),
       `2016` = c(49046, 41802),
       `2021` = c(44458, 40994))

and I hope to plot a bar chart with x as district and need to group by years.

the result is similar to this

在此处输入图像描述

Here you go:

Note: This is a motivation for you to see what is possible. In the future please first see here how to ask a question on stackoverflow

library(tidyverse)

df %>% 
  pivot_longer(-District) %>% 
  ggplot(aes(x = name, y = value, fill = District)) +
  geom_col(position = position_dodge())+
  scale_fill_manual(values = c("red", "blue"))+
  labs(title = "Number of Things per Month", x="Year", "Value")+
  theme_minimal()+
  theme(legend.position = "bottom")

在此处输入图像描述

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