首页 > 解决方案 > 如何跳过x轴限制前后的空白

问题描述

我有下面的数据框:

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)

我想创建一个在 x 轴上有特定限制的折线图(从 2015 年到 2017 年)。即使 thias 不是优先级,也应遵循范围滑块相同的逻辑。我的代码是:

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"
)

即使我使用scale_x_discrete(limits=c("2015", "2016", "2017"))的限制不是要求的。这是在结尾和开头都有空白区域的图,即使没有范围滑块也是如此。

在此处输入图像描述

标签: rggplot2

解决方案


尝试coord_cartesian(xlim = c(0.95:3.05), expand = FALSE)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)

在此处输入图像描述


推荐阅读