2017-05-26 53 views
1
定性变量延长限

大家好,感谢您的考虑,在ggplot

的目标是提供在那里有很多很多的x轴标签的情况下更多的空间。注意我不在乎标签本身是否在图上可见(我已经在下面的代码中将它们排除在外)。我想要改变的是,当一个典型的geom_point图中有〜1000个x轴标签和1000个数据点时,与这些第一个和最后几个x轴标签相关的左边和右边的点被压制绘图区域的边缘。我想填补一些空间,所以这些点不会被挤压。

我不知道是否有改变的情况下xixii是不是数字,而是,字符串的scale-x-discrete(limits=c(xi,xii)) type命令的方式。一个例子,使这个(希望)明确:

在这第一种情况下,灰点阴影图的最右点和边缘之间的间距是相当大的,这样的点不会正确地流血靠在绘图区域的边缘。我想要这种效果,在最后一点和剧情边缘之间有一些空间。

library(ggplot2) 
set.seed(10) 
lessVals = sample(1:100000, 10, replace = T) 
lessIDs = as.character(sample(1:100000, 10, replace = T)) 
df.less <- data.frame(lessIDs, lessVals) 
df.less$lessIDs <- as.character(df.less$lessIDs) 
lessDat <- ggplot(df.less) 
lessDat + geom_point(aes(lessIDs, lessVals)) + theme(axis.text.x = 
element_blank()) 

但是,在以下情况下有成千上万的x轴点,而可视化的身份本身是无关的标签,我想避免的左边和最右边的点被压扁了到绘图区域的边缘。注意我并不在意图中的点被压缩在一起 - 这是不可避免的,而过度绘图可以通过一个alpha参数或其他东西来解决。我想要解决的是让绘图边缘上的点(最好是左边和右边)在水平面之间有一些缓冲区,其中左侧是y轴刻度,右侧是此刻没有什么(但可能是,例如,一个传奇)。

manyIDs = as.character(sample(1:100000, 1000, replace = T)) 
manyVals = sample(1:100000, 1000, replace = T) 
df.many <- data.frame(manyIDs, manyVals) 
df.many$manyIDs <- as.character(df.many$manyIDs) 
manyDat <- ggplot(df.many) 
manyDat + geom_point(aes(manyIDs, manyVals)) + theme(axis.text.x = 
element_blank()) 

我很想知道究竟可以做些什么来为这些点的水平边缘提供一点缓冲。

感谢您分享您的天才。

回答

0

因为你的x变量是字符,ggplot2创建一个'离散'的x轴。当类别数量相当小(2 - 25)时,离散轴的默认绘图限制很有意义。您可以使用scale_x_discreteexpand参数来手动调整绘图限制。视觉外观将取决于点和图形设备的大小,因此您可能需要进行相应的调整。

例如,scale_x_discrete(expand=c(0.1, 0))将展开该图的每一边10%的数据范围。虽然scale_x_discrete(expand=c(0, 2))会将每边扩展2(无论单位x是多少)。另请参阅http://ggplot2.tidyverse.org/reference/scale_discrete.html

p1 <- ggplot(df.less, aes(x=lessIDs, y=lessVals)) + 
     geom_point() + 
     theme(axis.text.x=element_blank()) + 
     labs(title="Default x-axis limits") 

# Added x-axis space with expand. 
p2 <- ggplot(df.less, aes(x=lessIDs, y=lessVals)) + 
     geom_point() + 
     theme(axis.text.x=element_blank()) + 
     scale_x_discrete(expand=c(0, 2)) + 
     labs(title="expand=c(0, 2)") 

p3 <- ggplot(df.many, aes(x=manyIDs, y=manyVals)) + 
     geom_point() + 
     theme(axis.text.x=element_blank()) + 
     theme(panel.grid.major.x=element_blank()) + 
     theme(axis.ticks.x=element_blank()) + 
     labs(title="Default x-axis limits") 

# Added x-axis space with expand. 
p4 <- ggplot(df.many, aes(x=manyIDs, y=manyVals)) + 
     geom_point() + 
     theme(axis.text.x=element_blank()) + 
     theme(panel.grid.major.x=element_blank()) + 
     theme(axis.ticks.x=element_blank()) + 
     scale_x_discrete(expand=c(0.1, 0)) + 
     labs(title="expand=c(0.1, 0)") 

library(gridExtra) 

ggsave("plots.png", plot=arrangeGrob(p1, p2, p3, p4, nrow=2), 
     height=4, width=6, dpi=150) 

enter image description here

+0

非常感谢您@bdemarest –