user3711502
user3711502

Reputation: 412

R - How to make stacked bar chart with labels for all values, or a table of text that can be formatted

I have some data that consists of three columns - a code, a result, and a category. I want to create a stacked bar chart that has one 'bar' for each unique category, with the 'bar' actually being a list of the codes, color coded by result. Essentially a stacked bar chart with text instead of bars. If this is not possible, I'd like to create tables of the codes, color-coded by result (which also may not be possible in R).

Data ex:

 code<-c("ABC1","ABC2","ABC3","DEF1","DEF2","ABC2","ABC2","XYZ5")
 result<-c("Correct","Incorrect","Correct","Blank","Out of date","Correct","Incorrect","Blank")
 category<-c("Cat","Cat","Cat","Cat","Dog","Dog","Dog","Fish")
 x<-cbind(code,result,category)
 x
 code   result        category
[1,] "ABC1" "Correct"     "Cat"   
[2,] "ABC2" "Incorrect"   "Cat"   
[3,] "ABC3" "Correct"     "Cat"   
[4,] "DEF1" "Blank"       "Cat"   
[5,] "DEF2" "Out of date" "Dog"   
[6,] "ABC2" "Correct"     "Dog"      
[7,] "ABC2" "Incorrect"   "Dog"   
[8,] "XYZ5" "Blank"       "Fish"  

edit: here's a poorly done example of what I'm thinking. (where green is correct, red is incorrect, grey is blank, purple is out of date) example

Upvotes: 0

Views: 217

Answers (1)

Heroka
Heroka

Reputation: 13139

In ggplot, attempts a 'bar-chart' like approach with 'stacked' , color-coded codes.

#create a dataframe, easier for plotting
x <- data.frame(code,result,category)

#create y-variable
x <- x %>% group_by(category) %>% mutate(y = 1:n())

p1 <- ggplot(x[order(x$code),], aes(x = category, y = y)) +
  geom_text(aes(label = code, color = result)) +
  theme_bw() + theme(
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank()
  )
p1

enter image description here

Upvotes: 4

Related Questions