r - 如何使用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 轴变量的总和。
请帮忙。
解决方案
一般来说,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")
推荐阅读
- javascript - 为什么我的 mongoDB update-function 在成功更新文档后没有退出?
- python-3.x - python 3.6 __str__ 如何影响 print()
- java - Java:同时写入和读取文件
- c# - 如何在使用 NUnit 或 XUnit 时将参数传递给 dotnet test 命令
- c++ - GNU 链接器如何决定需要哪些 C/C++ 库文件?
- java - 我的布局 .xml 文件中允许使用我的所有元素
- php - 是什么导致了这个 InvalidSignature 异常?(公钥和签名由 PHP 创建,验证在 Python 中完成)
- powershell - foreach 循环中的 if else continue 语句出现问题
- javascript - 不同的子组件通过同时调用 setState 来搞乱父组件的状态
- amazon-s3 - 将 Content-Encoding 标头添加到签名的 URL 上传文件