R find number of rows in a group and plot

I have a table of Tennis matches. I want to group by winner_ids and plot them against height, basically to check if the taller players have won more matches. The data looks like this.

 m_id winner_id winner_height
    1         21    166
    2         21    166
    3         22    167
    4         21    166
    5         23    170
    6         24    163
    7         22    167
    8         25    164

Here m_id is the match_id. I want to plot number of matches a person has won against his height

example: 21 has won 3 matches and her height is 166 cm

how can I acheive this in ggplot?

my following code doesn't seem to be working

matches %>% group_by(winner_id) %>%
  ggplot(., aes(x = winner_ht, y = nrow((winner_id)))) + geom_point()

Can anyone help?

728x90

1 Answers R find number of rows in a group and plot

Do you mean something like this?

library(tidyverse)
df %>%
    group_by(winner_id, winner_height) %>%
    summarise(n = n()) %>%
    ggplot(aes(winner_height, n, label = winner_id)) +
    geom_point() +
    geom_text(position = position_nudge(y = -0.1))

enter image description here

Explanation: We count the number of games n per winner_id and winner_height and pass the summarised data to ggplot where we plot winner_height vs. n. We can also add labels to indicate the winner_id.


Sample data

df <- read.table(text =
    "m_id winner_id winner_height
    1         21    166
    2         21    166
    3         22    167
    4         21    166
    5         23    170
    6         24    163
    7         22    167
    8         25    164", header = T)

2 weeks ago