我正在尝试找到如何使用我的数据(多个变量)制作这样的条形图( 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_NA
、total_EU
、total_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
之前,您需要将数据框从“宽格式”格式化为“长格式”。在这里,我使用了 tidyr 中的 gather
函数。包来实现这个任务。
library(tidyverse)
dat2 <- dat %>%
gather(Total, Value, -Platformvendor)
ggplot(dat2, aes(x = Platformvendor, y = Value, fill = Total)) +
geom_col(position = "dodge")
数据
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/