我试图找到如何做这样的条形图(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,fill
这是做我想要的最好方法吗?任何提示都会有所帮助。
在使用ggplot2
之前,您需要将数据框格式从“宽格式”格式化为“长格式”。在这里,我使用gather
包中的tidyr函数来完成此任务。
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)