Reputation: 133
I am trying to create stacked barplot from dataframe with fill being rownames of dataframe while y is colSums of dataframe and x colnames of dataframe. Yet, I am getting error:
"Error: Aesthetics must be either length 1 or the same as the data (3): x, y"
Could you please advise how to solve it? Thank you in advance.
library(ggplot2)
df2<-data.frame(c(1000,700,500),c(2000,1500,1000))
rownames(df2)<-c("Revenue", "EBITDA", "EBIT")
colnames(df2)<-c("2020", "2021")
ggplot(data=df2, aes(x=colnames(df2), y=colSums(df2), fill=rownames(df2)))
Upvotes: 0
Views: 117
Reputation: 16121
library(tidyverse)
# example data
df2<-data.frame(c(1000,700,500),c(2000,1500,1000))
rownames(df2)<-c("Revenue", "EBITDA", "EBIT")
colnames(df2)<-c("2020", "2021")
# reshape dataset
df2_upd = df2 %>% rownames_to_column("x") %>% gather(year, value, -x)
# plot using the new dataset
ggplot(data=df2_upd, aes(x=year, y=value, fill=x)) + geom_col()
You need a "tidy" dataset to create this plot (i.e. each variable you want to use should have its own column).
So, first, you need to add a column with the rownames, in order to use them as a variable and then reshape the dataset in order to have your 2 distinct years (2020, 2021) in one column and the corresponding actual values in a 3rd column.
Upvotes: 1