r - 在 geom_bar 中使用多个变量与 ggplot 在同一 X (R)

标签 r ggplot2 geom-bar

我正在尝试找到如何使用我的数据(多个变量)制作这样的条形图( barplot )。

数据 (PlatformGlobe) 如下:

    Platformvendor total_NA total_EU total_JP total_Other total_Global
       <chr>       <dbl>    <dbl>    <dbl>       <dbl>        <dbl>
     microsoft     870.92   379.56    14.02      107.63      1372.92
     nintendo     1743.71   774.77   758.91      189.71      3469.71
      other         81.50     5.40    35.41        0.91       123.31
       PC           93.34   140.37     0.17       21.88       256.56
      sega          27.48     8.10    11.75        1.29        48.66
      sony        1526.25  1092.01   470.47      461.29      3549.89

我想在 X 轴上 total_NAtotal_EUtotal_JP ...,为每个平台使用不同的颜色和条形(Platformvendor),y 轴是表的编号。我尝试以此作为示例(数据较少):

 library(ggplot)
 library(gridExtra)

 temp4 <-ggplot(PlatformGlobe, aes(x=c("NA","EU","JP"),y=c(PlatformGlobe$total_NA,PlatformGlobe$total_EU,PlatformGlobe$total_JP),fill=PlatformGlobe$Platformvendor)) + 
 geom_bar(stat="identity")


 grid.arrange(temp4)

但它输出错误:美学必须是长度1或与数据(6)相同:x,y,填充

这是做我想做的事的最佳方式吗?任何提示都会有所帮助。

最佳答案

在使用ggplot2之前,您需要将数据框从“宽格式”格式化为“长格式”。在这里,我使用了 中的 gather 函数。包来实现这个任务。

library(tidyverse)

dat2 <- dat %>%
  gather(Total, Value, -Platformvendor)

ggplot(dat2, aes(x = Platformvendor, y = Value, fill = Total)) +
  geom_col(position = "dodge")

enter image description here

数据

dat <- read.table(text = "Platformvendor total_NA total_EU total_JP total_Other total_Global
     microsoft     870.92   379.56    14.02      107.63      1372.92
     nintendo     1743.71   774.77   758.91      189.71      3469.71
      other         81.50     5.40    35.41        0.91       123.31
       PC           93.34   140.37     0.17       21.88       256.56
      sega          27.48     8.10    11.75        1.29        48.66
      sony        1526.25  1092.01   470.47      461.29      3549.89",
                  header = TRUE, stringsAsFactors = FALSE)

关于r - 在 geom_bar 中使用多个变量与 ggplot 在同一 X (R),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47980079/

相关文章:

r - purrr::map 相当于 dplyr::do

r - 抑制 R 中由 "print"而不是 "message"或 "warning"显示的消息

r - 在 R 中的一个值上重复数据帧,选择其他列的任何值

r - 为什么这段代码在 ggplot 中静态地获取 y 轴百分比不正确?

r - Windows 上 RStudio 中的波浪号扩展

r - fiddle 图错误-提供给连续刻度的离散值

r - 在R中将条形图转换为饼图

r - ggplot2 堆叠条形图,其中每个值都是一个组/颜色

r - ggplot2: geom_bar 堆叠条形图,指定条形轮廓颜色