firmo23
firmo23

Reputation: 8404

How to skip the empty space before and after the limits of the x-axis

I have the dataframe below:

Year<-c("2015","2016","2017")
Total<-c(60,70,80)
key=c(1,2,3)
df<-data.frame(Year,Total,key)
levs<-c("2015","2016","2017")
df$Year <- factor(df$Year, levels = levs)

and I want to create a line chart with specific limits on x axis (from 2015 to 2017). The same logic should follow the range slider even thias is not a priority. My code is:

library(ggplot2)
library(plotly)
ggplotly(ggplot(data = df, aes(x = Year, y = Total, key = key, text = paste('Year:', Year, '<br>Total headcount:', Total))) +
  scale_x_discrete(limits=c("2015", "2016", "2017"))  + 
  geom_line(aes(group = 1), colour="#00A0BD")  + 
  xlab("Year") + ylab("Total Headcount") + 
  ylim(0, 80), tooltip = "text") %>%
rangeslider(#start = "2015", end = "2017"
)

Even when Im using scale_x_discrete(limits=c("2015", "2016", "2017")) the limits are not the requested. Here is the plot with the empty space at the end and at the beginning even without the range slider.

enter image description here

Upvotes: 1

Views: 303

Answers (1)

TheSciGuy
TheSciGuy

Reputation: 1196

Try coord_cartesian(xlim = c(0.95:3.05), expand = FALSE) and rangeslider(start = 0.95, end = 3.05)

ggplotly(ggplot(data = df, aes(x = Year, y = Total, key = key, text = paste('Year:', Year, '<br>Total headcount:', Total))) +
       scale_x_discrete(limits=c("2015","2016","2017"))  + 
       coord_cartesian(xlim = c(0.95:3.05), expand = FALSE)+
       geom_line(aes(group = 1), colour="#00A0BD")  + 
       xlab("Year") + ylab("Total Headcount") + 
       ylim(0, 80), tooltip = "text") %>%
rangeslider(start = 0.95, end = 3.05)

enter image description here

Upvotes: 1

Related Questions