问题
I'm trying to find how to do a barplot like this (barplot), but with my data (multiple variables).
The data (PlatformGlobe
) is the following:
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
I would like in the X axis total_NA
, total_EU
, total_JP
..., with different colors and bars for each platform (Platformvendor
) and y axis being the number of the table. I tried this as an example (with less data):
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)
But it outputs an error: Aesthetics must be either length 1 or the same as the data (6): x, y, fill
This is the best way to do what I want? Any tip will be helpful.
回答1:
You need to format your data frame from "wide-format" to "long-format" before using the ggplot2
. Here I used the gather
function from the tidyr package to achieve this task.
library(tidyverse)
dat2 <- dat %>%
gather(Total, Value, -Platformvendor)
ggplot(dat2, aes(x = Platformvendor, y = Value, fill = Total)) +
geom_col(position = "dodge")
DATA
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)
来源:https://stackoverflow.com/questions/47980079/using-multiple-variables-in-geom-bar-with-ggplot-at-same-x-r