Icewaffle
Icewaffle

Reputation: 19

How to create custom x-axis ticks

Suppose I have the following dataset df

Letter   Number   
A        -3
A        -1
B        2
A        3
B        -3
A        -2
B        2
A        2

And I want to create a barplot with A and B, plotting the frequency of 'Number' along the y-axis and with and x-axis having the values -3, -2, -1, 0, 1, 2, 3

Problem is when I use

library(ggplot2)
ggplot(df, aes(x=factor(Number), fill=Letter) + 
  geom_bar()

The x-axis only has the values -3, -2, -1, 2, 3 because there are no occurrences of 0 & 1.

Is there a way for me to 'fill out' the x-axis ticks to include 0 and 1 (with no bars, since there are no occurrences of 0 & 1 in the column numbers)

Any help is much appreciated

Upvotes: 0

Views: 59

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

Convert Number to factor with levels and use drop=FALSE in scale_x_discrete.

library(dplyr)
library(ggplot2)

df %>%
  mutate(Number = factor(Number, levels = seq(min(Number), max(Number)))) %>%
  ggplot() + aes(x= Number, fill=Letter) + 
  geom_bar() +
  scale_x_discrete(drop=FALSE)

enter image description here

data

df <- structure(list(Letter = structure(c(1L, 1L, 2L, 1L, 2L, 1L, 2L, 
1L), .Label = c("A", "B"), class = "factor"), Number = c(-3L, 
-1L, 2L, 3L, -3L, -2L, 2L, 2L)), class = "data.frame", row.names = c(NA, -8L))

Upvotes: 4

Related Questions