Home > Blockchain >  Plot all the years mentioned in a dataframe in R
Plot all the years mentioned in a dataframe in R

Time:01-30

I have a dataframe with a column of year and another column which consists of the frequency count of the years. My dataframe looks like the following

year <- c(2013,2014,2015,2016,2017,2018,2019,2020,2021,2022)
freq <- c(3, 12, 16, 11, 36, 32, 20, 30 ,41, 33)
df <- data.frame(year, freq)

I am trying to plot a line graph using ggplot. But all the years are not getting plotted on x-axis. I want all the years in the "year" column to get plotted on the x-axis and their respective frequencies on the y-axis. Please give me a solution to this problem

Thank you.

CodePudding user response:

If you have a wider range of years or need to reuse the code for other plots, then you can use max and min on years.

library(tidyverse)

ggplot(df, aes(x = year, y = freq))   
  geom_line()   
  scale_x_continuous(breaks = c(min(df$year):max(df$year)))  
  theme_bw()  
  xlab("Year")  
  ylab("Frequency")

Or as @r2evans suggested, you can also directly provide the years too.

ggplot(df, aes(x = year, y = freq))   
  geom_line()   
  scale_x_continuous(breaks = c(2013:2022))  
  theme_bw()  
  xlab("Year")  
  ylab("Frequency")

Output

enter image description here

  •  Tags:  
  • Related