user9580371
user9580371

Reputation:

Adding names to all X axis values using ggplot2 in R

The head of data frame is as follows:

Age number
21      4
22      4
23      5
24      6
25     11
26     10

I am trying to plot the frequency chart using ggplot using the following code

ggplot(data=x2, aes(x=Age, y=number)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=number), vjust=-0.3, size=3.5)+
  theme_minimal()+ labs(x = "Age", y = "Number of users")+ 
ggtitle("Frequency of Age")

and I get the output but not all the values on the X Axis are visible. I am sorry as this might be a very silly question but I am very new to R.

The output This is my Output

Upvotes: 1

Views: 687

Answers (1)

eipi10
eipi10

Reputation: 93811

You can use scale_x_continuous to set the axis breaks. With such a large number of axis labels, this probably works better if the orientation is flipped. Even then, it's still quite crowded.

library(tidyverse)

# Fake data
set.seed(2)
x2 = data_frame(Age=sample(20:70, 1000, replace=TRUE)) %>% 
  group_by(Age) %>% 
  summarise(number=n())

ggplot(data=x2, aes(x=Age, y=number)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=number, y=0.5*number), size=3, colour="white")+
  theme_minimal() + 
  labs(x = "Age", y = "Number of users")+ 
  ggtitle("Frequency of Age") +
  coord_flip() +
  scale_x_continuous(breaks=min(x2$Age):max(x2$Age), expand=c(0,0.1)) +
  scale_y_continuous(expand=c(0,0.2))

enter image description here

Upvotes: 2

Related Questions