我想添加彩色箭头(轴的全长)以显示向一个方向移动的时间(这可以假设但是对于此图而言没有数值,所以我希望箭头显示方向)。我可以使用geom_segment
绘制它,但缺少绘图区域之外的部分。
我已经看过这篇文章:R & ggplot2: How to get arrows under the axis label?但是这个解决方案是轴标题的黑客。这篇文章:https://stackoverflow.com/a/10542622/1000343显示文本区域之外的行,但不是彩色箭头。
MWE
library(ggplot2); library(grid); library(scales)
dat <- data.frame(Time=0:5, y=0:5)
ggplot(dat, aes(x=Time, y=y)) +
geom_area(alpha=.1) + theme_bw() +
scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(expand = c(0, 0)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()
)
我试过了:
ggplot(dat, aes(x=Time, y=y)) +
geom_area(alpha=.1) + theme_bw() +
scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(expand = c(0, 0)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()
) +
geom_segment(aes(x=0, xend = 5 , y=0, yend = 0), size=1.5,
arrow = arrow(length = unit(0.6,"cm")))
给予
但我想要
答案 0 :(得分:8)
您可以定义自己的轴grob,
library(ggplot2)
element_grob.element_custom <- function(element, ...) {
grid::segmentsGrob(0,1,1,1, arrow = arrow())
}
## silly wrapper to fool ggplot2
axis_custom <- function(...){
structure(
list(...), # this ... information is not used, btw
class = c("element_custom","element_blank", "element") # inheritance test workaround
)
}
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_line() +
theme(axis.line = axis_custom(),
axis.line.y=element_blank())
答案 1 :(得分:7)
问题似乎只是裁剪区域(回答here)。尝试:
p1<-ggplot(dat, aes(x=Time, y=y)) +
geom_area(alpha=.1) + theme_bw() +
scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(expand = c(0, 0)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()
) +
geom_segment(aes(x=0, xend = 5 , y=0, yend = 0), size=1.5,
arrow = arrow(length = unit(0.6,"cm")))
gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
获取
答案 2 :(得分:0)
您还可以添加coord_cartesian(clip = "off")
:
ggplot(dat, aes(x=Time, y=y)) +
geom_area(alpha=.1) + theme_bw() +
scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(expand = c(0, 0)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()
) +
geom_segment(aes(x=0, xend = 5 , y=0, yend = 0), size=1.5,
arrow = arrow(length = unit(0.6,"cm"))) +
coord_cartesian(clip = "off")