首页 > 解决方案 > 如何使用ggplot为多列创建条形图?

问题描述

如何使用 ggplot 在条形图中添加多列?

df = data.frame(c("player 1", "player 2", "player 3"),c(1,2,3), c(5,6,7), c(8,9,10))
names(df) = c("player","game 1","game 2", "game 3")

player     game 1  game 2  game 3
-----------------------------------
player 1      1      5       8
player 2      2      6       9
player 3      3      7      10

barplot(colSums(df[,2:4]))

在 gglot 中,我不确定如何添加多个 x 轴美学,而 y 轴是它们的总和。例如,对于上面的数据框,我需要创建一个带有三个 x 轴变量的条形图,分别是游戏 1、游戏 2 和游戏 3,并为每个条形添加一个标签,该标签是玩家每个 x 轴变量的总和。

请帮忙。

标签: rggplot2bar-chart

解决方案


一般来说,ggplot 最适合长数据。所以旋转它更长的时间(即将游戏变量组合成一个变量)。我假设你想要分组条形图,所以你可能想要使用fill = player它。

library(ggplot2)
library(dplyr)
library(tidyr)

dat <- data.frame(
    player = c("player 1", "player 2", "player 3"),
    game1 = c(1,2,3),
    game2 = c(5,6,7),
    game3 = c(8,9,10)
)

dat %>%
    pivot_longer(cols = contains("game"),
        names_to = "game") %>%
    ggplot(aes(x = game, y = value, fill = player)) +
        geom_col(position = "dodge")

在此处输入图像描述


推荐阅读