我正在尝试绘制一条末端带有箭头的线段,并使其出现在图例中。我可以使用以下代码来做到这一点:
library(ggplot2)
# sample data
dat <- data.frame(
x = as.factor(1:10),
y = c(20,30,13,37,12,50,31,2,40,30),
z = rep('a', 10)
)
# basic plot
ggplot(dat) +
geom_segment(
aes(x = x, xend = x, y = 0, yend = y+15, linetype = z),
arrow = arrow(length = unit(0.25, 'cm'), type = 'closed'),
size = 0.7
)
Run Code Online (Sandbox Code Playgroud)
输出:
问题:
我的问题是图例中的箭头没有像情节那样牢固地填充。我尝试过使用guide_legend(override.aes = aes(fill='black'))andguide_legend(override.aes = aes(type='closed'))但都没有对图例产生任何影响。
有谁知道如何使三角形填充并纯黑?
编辑:
我有一个类似的问题,geom_label不包括图例中标签周围的黑线。我设法通过geom_rect在我想要的确切位置添加 a 来解决这个问题,但希望这不是最好的解决方案:P
任何解决方案都会非常有帮助!
从ggplot2 3.2.0开始,可以提供自定义图例绘制功能。因此,如果图例看起来不太正确,您始终可以从 ggplot2 代码库复制相应的图例绘图函数,然后根据需要进行修改。
library(ggplot2)
library(grid)
library(rlang)
# legend drawing function, copied from ggplot2
draw_key_segment_custom <- function(data, params, size) {
if (is.null(data$linetype)) {
data$linetype <- 0
} else {
data$linetype[is.na(data$linetype)] <- 0
}
segmentsGrob(0.1, 0.5, 0.9, 0.5,
gp = gpar(
col = alpha(data$colour %||% data$fill %||% "black", data$alpha),
# the following line was added relative to the ggplot2 code
fill = alpha(data$colour %||% data$fill %||% "black", data$alpha),
lwd = (data$size %||% 0.5) * .pt,
lty = data$linetype %||% 1,
lineend = "butt"
),
arrow = params$arrow
)
}
# sample data
dat <- data.frame(
x = as.factor(1:10),
y = c(20,30,13,37,12,50,31,2,40,30),
z = rep('a', 10)
)
# basic plot
ggplot(dat) +
geom_segment(
aes(x = x, xend = x, y = 0, yend = y+15, linetype = z),
arrow = arrow(length = unit(0.25, 'cm'), type = 'closed'),
size = 0.7,
key_glyph = "segment_custom"
)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2019-07-25 创建
| 归档时间: |
|
| 查看次数: |
1469 次 |
| 最近记录: |