简体   繁体   English

如何为多个列制作分组条形图?

[英]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.因此,对于下面的示例代码(我的实际数据超过 2 行),我想要一月份的 x1、x2、x3 和 x4 的条形图,然后再为 x1、x2、x3 和 x4 的条形图二月等

x1 x1 x2 x2 x3 x3 x4 x4 Month
7.8 7.8 3.4 3.4 9.8 9.8 2.1 2.1 Jan
5.5 5.5 2.3 2.3 6.1 6.1 0.7 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.这显然是错误的,因为 Levels 没有以任何方式连接到数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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