0

I have a dataset like this, extracted from a large and complex data frame:

data_set <- data.frame("Name" = c("Mr X", "Mr Y", "Mr Z", "Mr X", "Mr Z"), "Score" = c(88, 93, 87, 89, 90))

I want to create a list plot, ordered by Score, but with each Name appearing multiple times when needed. The following code does not produce the desired output because I want the two Scores of "Mr X" and the two scores of "Mr Z" to appear on different rows, instead of being grouped by default. What is cleanest way to do this?

data_set$Name <- reorder(data_set$Name, data_set$Score, min)
ggplot(data_set) + geom_point(aes(x = Score, y = Name)) 

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

2 Answers2

1

I found this solution by adding a new factor without duplicates, and by mapping the labels to the old variable:

data_set$ID <- as.factor(seq(1:nrow(data_set)))
ggplot(data_set) + geom_point(aes(x = Score, y = ID)) +  scale_y_discrete(labels = function(x) data_set$Name[match(x, data_set$ID)])

enter image description here

It is rather ugly, but I could not think of a cleaner solution.

0

You need to create different y-axis value if you want them in different rows. Try :

library(dplyr)
library(ggplot2)

data_set %>%
  group_by(Name) %>%
  mutate(Name = paste0(Name, row_number())) %>%
  ggplot() + geom_point(aes(x = Score, y = Name)) 

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks for the reply. I tried something similar before posting, but I do not want the names to be written differently ("Mr X1", "Mr X2", ...) because this could be misinterpreted by people who will ultimately look at the final graph. I really want two copies of "Mr X". – Hugues Mercier Apr 26 '21 at 13:54
  • How about `ggplot(data_set, aes(x = Score, y = Name)) + geom_point() + geom_jitter()` ? – Ronak Shah Apr 26 '21 at 13:57
  • Not really. I can sort the first graph you suggested, but I do not want the numbers appended to the names. The y-axis should be "Mr Z", "Mr X", "Mr X", "Mr Z", "Mr Y", and not "Mr Z1", "Mr X1", "Mr X2", "Mr Z2", "Mr Y1". – Hugues Mercier Apr 26 '21 at 14:07