Show matrix data in a bar chart horizontally

I have the following matrix:

> mat = matrix(
  c(
    0.5,  0.2,  0.8, 1,
    0.35, 0.49, 0,   0.71
  ),
  dimnames = list(
    c(
      "ratio_1", "ratio_2", "ratio_3", "ratio_4",
      "ratio_5", "ratio_6", "ratio_7", "ratio_8"
    )
  )
)

> mat
        [,1]
ratio_1 0.50
ratio_2 0.20
ratio_3 0.80
ratio_4 1.00
ratio_5 0.35
ratio_6 0.49
ratio_7 0.00
ratio_8 0.71

Then, I want to somehow, show up its data like in the following image:

image

Any idea on how to do this?

Thanks!

library(dplyr)

library(ggplot2)
mat = matrix(
  c(
    0.5,  0.2,  0.8, 1,
    0.35, 0.49, 0,   0.71
  ),
  dimnames = list(
    c(
      "ratio_1", "ratio_2", "ratio_3", "ratio_4",
      "ratio_5", "ratio_6", "ratio_7", "ratio_8"
    )
  )
)
DF <- data.frame(Name = dimnames(mat)[[1]], Value = mat, Dummy = rep(1, 8),
                 Label = c("(50%)", "(20%)", "(80%)", "(100%)", "(35%)", 
                           "(49%)", "(0%)", "(71%)"),
                 LabelPos = 1.1)
DF <- mutate(DF, Name = factor(Name, levels =c(
  "ratio_8", "ratio_7", "ratio_6", "ratio_5",
  "ratio_4", "ratio_3", "ratio_2", "ratio_1") ))


ggplot(data = DF, aes(x=Name, y=Value)) + geom_col(fill = "skyblue") + 
  geom_col(aes(y = Dummy), fill = "white", color = "grey50", alpha = 0) + 
  scale_y_continuous(expand = c(-0.1, .2)) +geom_text(aes(y = LabelPos, label = Label)) +
  labs(x = "", y = "Player Ratios") +
  theme_minimal() + theme(axis.text.x = element_blank(), 
                          panel.grid.major = element_blank(), 
                          panel.grid.minor = element_blank()) + coord_flip()

Created on 2019-09-11 by the reprex package (v0.2.1)

1 Like

I can get a similar chart with the following code (which can be placed right after the code above.
The problem with it is that I don't get the numbers out on the right side of the grid and I also want the format: ( X %).

mydf = data.frame(rownames(mat), mat) %>% `rownames<-`(NULL) %>% `colnames<-`(c("param", "value"))
mydf = arrange(mydf, -row_number())
mydf$param = factor(mydf$param, levels = mydf$param)
mydf$value = 100 * as.double(mydf$value)
str(mydf)
ggplot(mydf, aes(x = param, y = value)) +
  geom_bar(stat = "identity", fill = "#00a2e8") +
  geom_text(aes(label = value, hjust = -0.5)) +
  xlab("") +
  ylab("Player Ratios") +
  coord_flip()

image

Any idea on how to continue from here?

Thanks!

1 Like

thank you @FJCC, that did the trick! :wink:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.