# Stacked Bar Chart in R

I wondered if someone could help with a re-labelling 'fill' variables ' and the x-axis on a stacked bar chart please?

My ambition is to:

• Express the fill variable(s) as of six domains in the health survey, titled ' MR, Mob, SC, Act, Pain, Anx')
• And have the x-variable representing the 'health states' (0,1, 2, 3,4, 5), rather than X0, X1....X5
library(ggplot2)
library(dplyr)
library(reshape2)
library(viridis)
library(hrbthemes)

data <- read.table(text = "0    1   2   3   4   5
MR  155 211 64  14  1   1
Mob 0   393 51  2   0   0
SC  0   427 12  7   0   0
Act 0   386 45  15  0   0
Pain    0   379 62  5   0   0
Anx 0   355 73  18  0   0", header = TRUE)

data\$row <- seq_len(nrow(data))
data2 <- melt(data, id.vars ="row")

ggplot(data2, aes(x = variable, y = value, fill = row)) +
geom_bar(stat = "identity") +
xlab("\nHealthState") +
ylab("Count\n") +
theme_bw()



Would appreciate all feedback.

Thank you for providing a good reproducible code, I can't resist answering the question :)

Hope the following code helps:

data <- read.table(text = "0    1   2   3   4   5
MR  155 211 64  14  1   1
Mob 0   393 51  2   0   0
SC  0   427 12  7   0   0
Act 0   386 45  15  0   0
Pain    0   379 62  5   0   0
Anx 0   355 73  18  0   0", header = TRUE)

#data$$row <- seq_len(nrow(data)) data$$row <- row.names(data)
data2 <- melt(data, id.vars ="row")
data2$$variable <- sub("X",as.character(data2$$variable),replacement="",fixed=TRUE)

ggplot(data2, aes(x = variable, y = value, fill = row)) +
geom_bar(stat = "identity") +
xlab("HealthState") +
ylab("Count") +
theme_bw()

• Thank you Erwan - truly appreciated :) Apr 29, 2021 at 7:36