If been trying to make a stack barplot with the ggplot2 package but when I launch the plot the result is not as I expected to be.
nombres <- c("Hotel", "Año", "Ingresos")
hoteles <- data.frame(
hc1 = c("Hawaiian Club",1993,450000),
hc2 = c("Hawaiian Club",1994,475000),
hc3 = c("Hawaiian Club",1995,390000),
fr1 = c("French Riviera",1993,225000),
fr2 = c("French Riviera",1994,240000),
fr3 = c("French Riviera",1995,205000),
bb1 = c("Bahamas Beach",1993,245000),
bb2 = c("Bahamas Beach",1994,255000),
bb3 = c("Bahamas Beach",1995,345000),
row.names = nombres)
hoteles <- data.frame(t(hoteles))
ggplot(hoteles, aes(fill=Año, y=Ingresos, x=Hotel))
geom_bar(position="stack", stat="identity")
The result is the following one:
CodePudding user response:
Up front: fix the problem as early in the process as possible.
Ultimately, you are seeing a symptom (side-effect) of a data-import problem. That is, after your code, you may notice that
str(hoteles)
# 'data.frame': 9 obs. of 3 variables:
# $ Hotel : chr "Hawaiian Club" "Hawaiian Club" "Hawaiian Club" "French Riviera" ...
# $ Año : chr "1993" "1994" "1995" "1993" ...
# $ Ingresos: chr "450000" "475000" "390000" "225000" ...
telling you that all columns are strings, despite the intuitive expectation that Año and Ingresos should be numeric or integer.
While the other answer (based on TarJae's comment) fixes the issue post-import, you should look to define the data the right way the first time. I'm going on the premise that you are storing it like that because you are building it in a source .R file somewhere, and not receiving a CSV file.
Alternatives, with that assumption:
hoteles <- tibble::tribble(
~Hotel , ~Año, ~Ingresos
, "Hawaiian Club" , 1993, 450000
, "Hawaiian Club" , 1994, 475000
, "Hawaiian Club" , 1995, 390000
, "French Riviera", 1993, 225000
, "French Riviera", 1994, 240000
, "French Riviera", 1995, 205000
, "Bahamas Beach" , 1993, 245000
, "Bahamas Beach" , 1994, 255000
, "Bahamas Beach" , 1995, 345000
)
hoteles <- read.csv(text = '
Hotel,Año,Ingresos
"Hawaiian Club" , 1993, 450000
"Hawaiian Club" , 1994, 475000
"Hawaiian Club" , 1995, 390000
"French Riviera", 1993, 225000
"French Riviera", 1994, 240000
"French Riviera", 1995, 205000
"Bahamas Beach" , 1993, 245000
"Bahamas Beach" , 1994, 255000
"Bahamas Beach" , 1995, 345000
',strip.white = TRUE)
(The embedded double-quotes are not even required, assuming you have no embedded commas.)

