简体   繁体   中英

How to make a Grouped Bar chart for multiple columns?

I want to make a grouped bar chart where each month is clustered together, then within that cluster each variable gets its own bar. So for the sample code below (my actual data has more than 2 rows) I want a bar for x1, for x2, for x3 and for x4 in January, then again a bar for x1, for x2, for x3 and for x4 in February, etc.

x1 x2 x3 x4 Month
7.8 3.4 9.8 2.1 Jan
5.5 2.3 6.1 0.7 Jan

I must be missing something fairly obvious but I can't figure out how to make each column a bar. This is my best guess so far,

Levels = c(x1, x2, x3, x4)
Plot <- ggplot(data, aes(x = Month, fill = Levels)) + geom_col(position = 'dodge')

which is obviously wrong because Levels isn't connected to the data in any way.

Any ideas would be appreciated.

library(tidyverse)
df %>% 
  pivot_longer(
    -Month
  ) %>% 
  ggplot(aes(x = Month, y = value, fill=name)) + 
  geom_bar(position="dodge", stat="identity")

在此处输入图像描述

data:

df <- structure(list(x1 = c(7.8, 5.5, 4.8, 5.5), x2 = c(3.4, 2.3, 6.4, 
7.3), x3 = c(9.8, 6.1, 9.8, 3.1), x4 = c(2.1, 0.7, 2.1, 7.7), 
    Month = c("Jan", "Jan", "Feb", "Feb")), class = "data.frame", row.names = c(NA, 
-4L))

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