如何在ggplot2图的末尾删除间隙

时间:2012-12-04 20:18:44

标签: r ggplot2

我的输入文件是here on PasteBin

我目前的图表代码是:

 #Input and data formatting
 merg_agg_creek<-read.table("merged aggregated creek.txt",header=TRUE)
 library(ggplot2)
 library(grid)
 source("http://egret.psychol.cam.ac.uk/statistics/R/extensions/rnc_ggplot2_border_themes.r")

 CombinedCreek<-data.frame(merg_agg_creek)
 Combined<-CombinedCreek[order(CombinedCreek[,2]),]
 Combined$Creek <- factor(rep(c('Culvert Creek','North Silcox','South Silcox','Yucca Pen'),c(32,57,51,31)))  
 Combined$Creek<-factor(Combined$Creek,levels(Combined$Creek)[c(1,4,3,2)])

 #The Graph Code

 creek <-ggplot(Combined,aes(Month,Density,color=factor(Year),shape=factor(Year)))+scale_color_discrete("Year")+scale_shape_discrete("Year")
 creek<-creek + facet_grid(Creek~. ,scales = "free_y")
 creek <- creek + geom_jitter(position = position_jitter(width = .3))
 creek<-creek+scale_color_grey("Year",end=.6)+theme_bw()
 creek<-creek+scale_y_continuous(expression("Number of prey captured " (m^2) ^-1))
 creek<-creek+opts( panel.border = theme_L_border() )+ opts(axis.line = theme_segment())
 creek<-creek+opts(panel.grid.minor = theme_blank())+opts(panel.grid.major = theme_blank())
 creek<-creek+scale_x_discrete("Month",breaks=c(2,5,8,11),labels=c("February","May","August","November"))
 creek

结果图是: Graph
graph

我的问题是,通过在“scale_x_discrete”中创建中断和标签,在图表的右侧,12月的数据和构面标签之间存在较大的间隙。我尝试通过在“scale_x_discrete:”命令中添加“limits = c(0,13)”来消除这种差距,但resulting graph会破坏x标签。

如何消除这种差距?我的情节创作中是否存在根本缺陷?

谢谢!

编辑:Didzis回答了以下问题。我只需要从scale_x_discrete更改为scale_x_continuous

2 个答案:

答案 0 :(得分:4)

由于数据中的月份是数字,请尝试替换

 scale_x_discrete("Month",breaks=c(2,5,8,11),labels=c("February","May","August","November")) 

 scale_x_continuous("Month",breaks=c(2,5,8,11),labels=c("February","May","August","November"))

将所有其他参数保持不变

答案 1 :(得分:0)

您需要在比例中使用expand参数。我认为额外的空间可能是由于抖动造成的,但是如果你给它一个-2它会一直到边缘。几乎看起来像是一个填充这么多的bug。

ggplot(Combined,aes(Month,Density,color=factor(Year),shape=factor(Year))) +
scale_shape_discrete("Year") +
facet_grid(Creek~. ,scales = "free_y") +
geom_jitter(position = position_jitter(width = .3)) +
scale_color_grey("Year",end=.6) +
theme_bw() +
scale_y_continuous(expression("Number of prey captured " (m^2) ^-1))+
scale_x_discrete("Month",breaks=c(2,5,8,11),labels=c("February","May","August","November"), expand= c(0,-2)) +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank()
)