Matt Simonson
Matt Simonson

Reputation: 137

ggplot y axis range ordering not from smallest to largest

Not sure why this is happening it appears to be ordering 1 then 10 then 100, then going to 11?

Here is my code:

library(gtrendsR)
library(tidyverse)


keywords = c("SALT Deduction", "State and Local Tax Deduction")
country = "US"
time = ("2010-01-01 2018-12-31")
channel = "web"
trends = gtrends(keywords, gprop = channel, geo = country, time = time)
time_trend <- trends$interest_over_time
head(time_trend)

plot<-ggplot(data=time_trend, aes(x=date, y=hits,group=keyword,col=keyword))+
  geom_line()+xlab('Time')+ylab('Relative Interest')+ theme_bw()+
  theme(legend.title = element_blank(),legend.position="bottom",legend.text=element_text(size=12))+ggtitle("Google Search Volume")
plot

googlesearchvolume

Upvotes: 1

Views: 253

Answers (1)

Duck
Duck

Reputation: 39613

As mentioned by @starja the proper way to solve your issue is formating hits as factor. Here a way to do that using dplyr:

library(gtrendsR)
library(tidyverse)
#Data
keywords = c("SALT Deduction", "State and Local Tax Deduction")
country = "US"
time = ("2010-01-01 2018-12-31")
channel = "web"
trends = gtrends(keywords, gprop = channel, geo = country, time = time)
time_trend <- trends$interest_over_time
head(time_trend)
#Plot
time_trend %>%
  mutate(hits=factor(hits,levels = c("<1",0:100),ordered = T)) %>%
  ggplot(aes(x=date, y=hits,group=keyword,col=keyword))+
  geom_line()+xlab('Time')+ylab('Relative Interest')+ theme_bw()+
  theme(legend.title = element_blank(),legend.position="bottom",
        legend.text=element_text(size=12))+ggtitle("Google Search Volume")

Output:

enter image description here

Upvotes: 3

Related Questions