对数转换将做到这一点:
require('data.table')
require('ggplot2')
library(scales)
test <- data.table(x=1:10,y=c(seq(1,9),100))
ggplot(test, aes(x=x,y=y)) +
geom_point(size=5) +
scale_y_log10(breaks=c(1,3,10,30,100))
UPDATE:没有简单的方法可以用 ggplot2 来制作断轴(因为 ggplot2 不允许您(轻松)做被认为是不好的做法的事情),但这里有一种方法可以得到您正在寻找的东西。 (只是不要告诉哈德利是我告诉你的。)
library(data.table)
library(ggplot2)
library(scales)
library(grid)
library(gridExtra)
test <- data.table(x=1:10,y=c(seq(1,9),100))
总体策略是制作两张单独的图,一张用于 y>=10,一张用于 y
底部图(y
p1 = ggplot(test[test$y<10,], aes(x=x,y=y)) +
geom_point(size=5) +
scale_x_continuous(limits=c(0,10)) +
coord_cartesian(ylim=c(-0.1,10)) +
scale_y_continuous(breaks=0:10) +
theme(plot.margin=unit(c(0,0.5,0,0),"lines"))
顶部图 (y >= 10)。对于这一点,我们去掉了 x 轴标签和刻度线:
p2 = ggplot(test[test$y>=10,], aes(x=x,y=y)) +
geom_point(size=5) +
scale_x_continuous(limits=c(0,10)) +
coord_cartesian(ylim=c(10.0,110)) +
scale_y_continuous(breaks=c(50,100)) +
theme(plot.margin=unit(c(0,0.5,-0.5,0), "lines"),
axis.title.x=element_blank(),
axis.ticks.x=element_blank(),
axis.text.x=element_blank()) +
labs(y="")
将两个图左对齐(基于这个答案 https://stackoverflow.com/a/13295880/496488):
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
将两个图排列在一起。这heights
参数决定分配给每个图的垂直空间的比例:
grid.arrange(gB, gA, ncol=1, heights=c(0.15,0.85))
更新2:要包含图例,同时还要确保绘图正确右对齐,请执行以下操作:
1)运行更新问题中的代码来创建绘图p1
and p2
,其中仅p1
有一个传说。
2)使用下面的函数将图例提取为单独的grob(来自这个答案 https://stackoverflow.com/a/12539820/496488).
3)删除图例p1
.
4)使用布局图和图例grid.arrange
and arrangeGrob
.
# Function to extract the legend as a stand-alone grob
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
# Extract the legend from p1
leg = g_legend(p1)
# Remove the legend from p1
p1 = p1 + theme(legend.position="none")
# Left justify the two plots
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
# Lay out the plots and the legend
grid.arrange(arrangeGrob(gB, gA, ncol=1, heights=c(0.15,0.85)),
leg, ncol=2, widths=c(0.9,0.1))