 Grouped geom_bar with some "0" values

Hi,

Let's imagine that Nicol, Steve, Mary are chatting on a Whatsapp private group in 2020. In 2021, Frank joins the group.

I would like to visualise the number of messages each one has written each year.

Here is the code:

year <- factor(c(rep(c(2020), 11), rep(c(2021), 8)))
author <- c("Mary", "Nicol", "Steve", "Mary", "Nicol", "Mary", "Mary", "Mary", "Steve", "Nicol", "Mary",
"Nicol", "Steve", "Frank", "Mary", "Mary", "Frank", "Nicol", "Nicol")
msg <- rep("blablabla", 19)
df <- data.frame(year, author, msg)

p <- ggplot(df, aes(x = author, group = year, fill = year))
p + geom_bar(position = "dodge2")
labs(x = "", y = "Number of messages", title = "Number of messages by year and by author")

The result is shown here:

There is a problem with Frank: I would like to find a simple way to reduce the width of Frank's bar, so that 2020 remains as = 0.

Thanks,
Cheers

So there are a couple of ways to approach this:

Preserve Single

library(tidyverse)

year <- factor(c(rep(c(2020), 11), rep(c(2021), 8)))
author <- c("Mary", "Nicol", "Steve", "Mary", "Nicol", "Mary", "Mary", "Mary", "Steve", "Nicol", "Mary",
"Nicol", "Steve", "Frank", "Mary", "Mary", "Frank", "Nicol", "Nicol")
msg <- rep("blablabla", 19)
df <- data.frame(year, author, msg)

p <- ggplot(df, aes(x = author, group = year, fill = year))
p + geom_bar(position = position_dodge2(preserve = "single")) +
labs(x = "", y = "Number of messages", title = "Number of messages by year and by author") tidyr::complete

library(tidyverse)

year <- factor(c(rep(c(2020), 11), rep(c(2021), 8)))
author <- c("Mary", "Nicol", "Steve", "Mary", "Nicol", "Mary", "Mary", "Mary", "Steve", "Nicol", "Mary",
"Nicol", "Steve", "Frank", "Mary", "Mary", "Frank", "Nicol", "Nicol")
msg <- rep("blablabla", 19)
df <- data.frame(year, author, msg)

df |>
count(year, author) |>
complete(year, author) |>
ggplot(aes(x = author, y = n, fill = year)) +
geom_col(position = position_dodge2()) +
labs(x = "", y = "Number of messages", title = "Number of messages by year and by author")
#> Warning: Removed 1 rows containing missing values (geom_col). Created on 2021-12-08 by the reprex package (v2.0.1)

2 Likes

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.