I have the following dataframe:
set.seed(2)
a<-sample(c(paste0("Id_",1:20)), size = 1000, replace = T)
b<-sample(c("preso","libre","proceso"), size = 1000, replace = T)
df<-data.frame(a,b)
If I make the table between column a and b. I get the following:
resumen<-round(prop.table(table(df$a,df$b), 1)*100,2)
libre preso proceso
Id_1 39.47 36.84 23.68
Id_10 50.00 29.55 20.45
Id_11 32.08 43.40 24.53
Id_12 41.51 39.62 18.87
Id_13 42.37 25.42 32.20
Id_14 42.86 34.69 22.45
Id_15 30.51 22.03 47.46
Id_16 42.86 26.19 30.95
Id_17 22.92 37.50 39.58
Id_18 33.90 30.51 35.59
Id_19 34.15 31.71 34.15
Id_2 40.00 30.00 30.00
Id_20 39.66 25.86 34.48
Id_3 30.61 38.78 30.61
Id_4 31.48 31.48 37.04
Id_5 32.00 38.00 30.00
Id_6 36.67 31.67 31.67
Id_7 44.00 30.00 26.00
Id_8 18.00 42.00 40.00
Id_9 40.74 27.78 31.48
If I want to make the graph only of those that are free and I want to order it in decreasing order, I use the following syntax:
resumen<-resumen[,1]
resumen<-sort(resumen, F)
And I get the following graph. With the following syntax:
resumen_g<-barplot(resumen, horiz = T, las=2, xlim = c(0,65))
text(resumen+3, resumen_g, format(resumen), cex = 0.8)
Here the graph:
So far so good, but I need to add a label where the values of being free between the total of each individual are shown in nominal values.
To do this I make the following code
text_1<-addmargins(table(df$a,df$b),2)
The result of this is:
libre preso proceso Sum
Id_1 15 14 9 38
Id_10 22 13 9 44
Id_11 17 23 13 53
Id_12 22 21 10 53
Id_13 25 15 19 59
Id_14 21 17 11 49
Id_15 18 13 28 59
Id_16 18 11 13 42
Id_17 11 18 19 48
Id_18 20 18 21 59
Id_19 14 13 14 41
Id_2 12 9 9 30
Id_20 23 15 20 58
Id_3 15 19 15 49
Id_4 17 17 20 54
Id_5 16 19 15 50
Id_6 22 19 19 60
Id_7 22 15 13 50
Id_8 9 21 20 50
Id_9 22 15 17 54
That is, I want the label of the first individual to be free between the sum, for example for the first 15/38 for the second 22/44 and so on:
To do this I perform the following syntax:
text_p<-text_1[,1]
text_s<-text_1[,4]
text_f<-paste(text_p, text_s, sep = "/")
And now I add it to the image, with the following code:
resumen_g<-barplot(resumen, horiz = T, las=2, xlim = c(0,65))
text(resumen+3, resumen_g, format(resumen), cex = 0.8)
text(resumen-5, resumen_g, format(text_f), cex = 0.8)
Which results in the following image:
But as you can see, this last label has not been ordered. That is, 22/54 is not 50%.
I don't know how to order this tag based on my previous order.
Some help... Maybe some command to simplify my explanation.
Thank you very much in advance
The problem is that you have ordered the labels in the variable
text_f
and in the variable differentlyresumen
. Code: