print category multiple times in ggplot (no grouping)

45 Views Asked by At

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

2

There are 2 best solutions below

0
On

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.

3
On

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