Menno Van Dijk
Menno Van Dijk

Reputation: 903

ggplot2 geom_dotplot() does not show all dots

I'm trying to show a number of dots per id equal to count, split by name in the following dataframe:

df <- data.frame(name = c("name1", "name1", "name1", "name1", "name2", "name2", "name2"),
                 id = c(0, 1, 2, 3, 0, 1, 2),
                 count = c(2, 4, 3, 2, 2, 2, 3))

What I currently have is this.

ggplot(data = df, aes(x = name, y = id)) +
  geom_dotplot(stackdir = "center", binaxis = 'y', dotsize = 0.5, binwidth = 1) +
  scale_y_continuous(breaks = seq(0, 3, 1), minor_breaks = seq(0, 3, 1))

enter image description here

However, this does not seem to show me all the dots per id (it only shows me 1 dot for each id, even though id 0 for name1 has a count of 2).

How would I go about fixing this?

Upvotes: 2

Views: 934

Answers (1)

lroha
lroha

Reputation: 34291

I don't know of a way to pass summarised data to geom_dotplot(). Instead, you can uncount() it first:

library(ggplot2)
library(tidyr)

df <- data.frame(name = c("name1", "name1", "name1", "name1", "name2", "name2", "name2"),
                 id = c(0, 1, 2, 3, 0, 1, 2),
                 count = c(2, 4, 3, 2, 2, 2, 3)) %>%
  uncount(count)

ggplot(data = df, aes(x = name, y = id)) +
  geom_dotplot(stackdir = "center", binaxis = 'y', dotsize = 0.5, binwidth = 1) +
  scale_y_continuous(breaks = seq(0, 3, 1), minor_breaks = NULL)

enter image description here

Upvotes: 3

Related Questions