Home > Software engineering >  Sorting barplot based on multi-categories in r
Sorting barplot based on multi-categories in r

Time:05-31

I am trying to get a bar plot for sentiment scores corrected as per the following order and put into two separate colors:

(NEGATIVE) anger, disgust, fear, sadness, negative --- (POSITIVE) anticipation, joy, surprise, trust, positive.

Below is the code which only gives a decreasing plot.

barplot(sort(colSums(s), decreasing = TRUE),
        las = 2,
        col = rainbow(2),
        ylab = 'Count',
        main = 'User Synergies')

barplot

> dput(head(s))
structure(list(anger = c(1, 0, 0, 0, 0, 0), anticipation = c(0, 
0, 5, 0, 0, 0), disgust = c(0, 0, 0, 0, 0, 0), fear = c(1, 0, 
2, 1, 0, 0), joy = c(1, 0, 1, 0, 0, 0), sadness = c(1, 0, 2, 
1, 0, 0), surprise = c(0, 0, 2, 1, 0, 0), trust = c(4, 2, 3, 
1, 0, 1), negative = c(2, 0, 3, 2, 1, 1), positive = c(4, 4, 
7, 1, 0, 2)), row.names = c(NA, 6L), class = "data.frame")

CodePudding user response:

Another way:

positive <- c("anticipation", "joy", "surprise", "trust", "positive")
negative <- c("anger", "disgust", "fear", "sadness", "negative")
barplot(colSums(s[,c(negative, positive)]),
        las = 2,
        col = c(rep("red", length(negative)), rep("cyan", length(positive))),
        ylab = 'Count', ylim = c(0, 20),
        main = 'User Synergies')

The result:

enter image description here

CodePudding user response:

Try this ,

df <- structure(list(anger = c(1, 0, 0, 0, 0, 0), 
                     anticipation = c(0, 0, 5, 0, 0, 0),
                     disgust = c(0, 0, 0, 0, 0, 0),
                     fear = c(1, 0,2, 1, 0, 0), 
                     joy = c(1, 0, 1, 0, 0, 0),
                     sadness = c(1, 0, 2, 1, 0, 0), 
                     surprise = c(0, 0, 2, 1, 0, 0), 
                     trust = c(4, 2, 3, 1, 0, 1),
                     negative = c(2, 0, 3, 2, 1, 1),
                     positive = c(4, 4,7, 1, 0, 2)),
                row.names = c(NA, 6L), class = "data.frame")

pn <- rainbow(2)   # "#FF0000" "#00FFFF" one for positive and the other for negative
s <- sort(colSums(df) , decreasing = TRUE)

names(s) 
#>  [1] "positive"     "trust"        "negative"     "anticipation" "fear"        
#>  [6] "sadness"      "surprise"     "joy"          "anger"        "disgust"
# arrange colors based on names of sorted columns
col <- c(pn[1] , pn[1] , pn[2] , pn[1] , pn[2] ,
         pn[2] , pn[1] , pn[1] , pn[2] , pn[2])

barplot(s ,
        las = 2,
        col = col,
        ylab = 'Count',
        main = 'User Synergies')

Created on 2022-05-31 by the enter image description here

  •  Tags:  
  • r
  • Related