我正在尝试在图例中添加误差线和中位数。 我添加了误差线和中位数,但我未能在相同的图例(例如颜色或形状)下添加图例,因此它们将在一起。我在此link中尝试了legend.spacing.y和其他方法,但仅获得了有限的成功。我也想在图例中垂直显示带有误差线的误差线。 这是我的代码:
library(tidyverse)
date <- sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 500,replace=TRUE)
flow <- rnorm(500)
df <- data.frame(date,flow)
monthOrder <- c('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
df$Month <- factor(format(df$date, "%b"), levels = monthOrder)
df.bar <- df %>% count(Month)
med_IQR <- function(x) {
# Change x below to return the instructed values
data.frame(y = median(x), # Median
ymin = quantile(x,0.05), # 1st quartile
ymax = quantile(x,0.95)) # 3rd quartile
}
p <- ggplot()+
geom_bar(data=df.bar,aes(Month,n/sum(n)),stat="identity",alpha=0.7,width=0.75)+
geom_point(data=df,aes(x=Month,y=flow/10),stat="identity",
position=position_jitter(width=0.25),alpha=0.7,col="orangered3")+
stat_summary(data=df,aes(x=Month,y=flow/10,shape="Median"),geom="point",fun.y = median,
size = 2,color="blue3")+
stat_summary(data=df,aes(x=Month,y=flow/10,color = "CI"),geom="errorbar",fun.data = med_IQR,
width = 0.2)+
scale_shape_manual(values=c("Median"=16))+
scale_color_manual(values=c("CI"="blue3"))+
guides(shape=guide_legend(title="",override.aes = list(color=c("blue3"))),
color=guide_legend(title=""))
p
答案 0 :(得分:1)
为减少图例键之间的间距,我认为您已经被指向正确的方向。您是否也尝试过像这样的负值?
p <- p + theme(legend.spacing.y = unit(-1,"cm"))
如果我理解正确,则需要翻转描述误差线的线。可以使用grid
软件包功能以骇人听闻的方式完成此操作:
library(grid)
# Transform to a grob tree
g <- ggplotGrob(p)
# Helpful to check the structure of the grob Tree
View(g$grobs)
# Edit the specific line from the legend key
g$grobs[[15]][["grobs"]][[1]][["grobs"]][[4]][["x0"]] <- unit(0.5, "npc")
g$grobs[[15]][["grobs"]][[1]][["grobs"]][[4]][["y0"]] <- unit(0.1, "npc")
g$grobs[[15]][["grobs"]][[1]][["grobs"]][[4]][["x1"]] <- unit(0.5, "npc")
g$grobs[[15]][["grobs"]][[1]][["grobs"]][[4]][["y1"]] <- unit(0.9, "npc")
# Draw the edited grob tree
grid.newpage(); grid.draw(g)
如果您想进一步了解grid
软件包并进行更细粒度的编辑,请检查browseVignettes(package="grid")
和/或查看带有文档here的作者页面。由grid
的作者Paul Murrell撰写的Debugging grid Graphics和Velvet Ly也很有用,也很不错。
保存已编辑的grob树可与通常的ggsave
:ggsave(plot = g, filename = "edited-plot.png")