Home > front end >  How to display all columns on X axis on Barplot?
How to display all columns on X axis on Barplot?

Time:04-14

I am trying to create a simple barplot showing years (2008-2022) on the x axis, and number of tweets on y axis.

However, R is automatically "skipping" certain years. Is there a way to have each year present on the x-axis under it's corresponding bar? I tried playing with "theme(axis.text.x = element_text(angle = 0, size = 10))", but nothing changed.

Here is my code:

ggplot(data, aes(x=created_at)) 
  geom_bar(fill="steelblue") 
  theme_minimal()  
  labs(title="Number of Tweets per year", x="Year", y="Counts")


enter image description here

CodePudding user response:

Here's two ways you could achieve that:

  • option 1: add scale_x_continuous(breaks = 2008:2022) as mentioned by @Axeman
  • option 2: change "created_at" to factor, which can be done directly within ggplot().

Some sample data

set.seed(1)
n = sample(10:140, 15)
data <- tibble("created_at" = rep(2008:2022, n))

Option 1

ggplot(data, aes(x = created_at))  
  geom_bar(fill = "steelblue")  
  theme_minimal()  
  labs(title = "Number of Tweets per year", x = "Year", y = "Counts")  
  scale_x_continuous(breaks = 2008:2022)

Option 2

ggplot(data, aes(x = factor(created_at)))  
  geom_bar(fill = "steelblue")  
  theme_minimal()  
  labs(title = "Number of Tweets per year", x = "Year", y = "Counts")

enter image description here

  • Related