1

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

5
  • Would you like to adjust the visibility in the y-axis or show all ages in the x-axis? Commented Apr 1, 2018 at 0:09
  • Show all the ages in the x-axis. Commented Apr 1, 2018 at 0:14
  • Are you referring to the geom_text values that are getting trimmed off at the top of the graphic? Commented Apr 1, 2018 at 0:34
  • @42 yes actually. Commented Apr 1, 2018 at 0:37
  • You should be able to extend the y axis with +ylim(0,13) Commented Apr 1, 2018 at 1:48

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly, I think flipping the chart horizontal makes it much more readable. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.