我正在尝试用不同的颜色填充下图中的3个三角形。
data = data.frame(x=c(125), y=c(220)) #this data is just to be able to use gplot to draw figures
ggplot(data, aes(x = x, y = y)) +
xlim(0,250) +
ylim(-250, 0) +
geom_curve(x = 33, xend = 223, y = -100, yend = -100, curvature = -.65) +
geom_segment(x=128, xend = 33, y=-208, yend = -100) +
geom_segment(x=128, xend = 223, y=-208, yend = -100) +
geom_segment(x=128, xend = 159.67, y=-208, yend = -45) +
geom_segment(x=128, xend = 96.33, y=-208, yend = -45) +
coord_fixed()
我怎样才能做到这一点?
简短的答案:这是一个非常邪恶的hack。
现在让我们详细说明一下:正如在此GitHub线程中特别讨论的那样,不可能访问由此产生的坐标geom_curve
(它CurveGrob
用于绘图和“这些值都是在绘制时计算的” [@ thomasp85])。其“绘制时行为的计算”的效果可以在下面看到-如果添加coord_plot
或不添加,都会有所不同。这与geom_spline
:有所不同:添加coord_fixed
不会更改坐标。
参见下面的图一和图二:红色曲线的创建方式geom_curve
-与geom_segment线失去联系...
@ thomasp85在GitHub线程中建议人们可以改用他的软件包ggforce
。现在,要真正控制曲率,需要使用geom_bspline并使用曲率。
一旦找到曲率,就可以使用ggplot_build对象中的坐标。我们可以根据这些坐标来计算多边形(这也不是一件容易的事,因为需要创建切口并为正确的“边”添加点)。见下文。
library(tidyverse)
library(ggforce)
mydata = data.frame(x = 128, xend = c(33, 223, 159.67, 96.33), y = -208, yend = c(-100,-100,-45,-45))
#for spline control points.
my_spline <- data.frame(x = c(33, 128, 223), y = c(-100, 24,-100))
接下来,我演示“绘制时间(红色曲线)上的计算”与“直接计算”之间的区别:
用coord_fixed
红色和黑色曲线触摸线段
ggplot(mydata) +
geom_curve(aes(x = 33, xend = 223, y = -100, yend = -100), curvature = -.65, color = 'red') +
geom_segment(aes(x = x, xend = xend, y = y, yend = yend)) +
geom_bspline(data = my_spline, aes(x, y )) +
coord_fixed()
不coord_fixed
使用红色曲线不会触及线段,但黑色曲线仍会触及线段。
ggplot(mydata) +
geom_curve(aes(x = 33, xend = 223, y = -100, yend = -100), curvature = -.65, color = 'red') +
geom_segment(aes(x = x, xend = xend, y = y, yend = yend)) +
geom_bspline(data = my_spline, aes(x, y ))
# Final hack
# Get x/y coordinates from ggplot_build
p <- ggplot(mydata) +
geom_bspline(data = my_spline, aes(x, y ))
pb <- ggplot_build(p)$data[[1]]
#create groups for fill
data_polygon <- data.frame(x = pb[['x']], y = pb[['y']]) %>%
mutate(cut_poly = cut(x, c(-Inf, 96.33, 159.67, Inf), labels = letters[1:3]))
#add corner points - repeat extremes from b, otherwise there will be a gap
data_add <- data_polygon %>%
filter(cut_poly == 'b') %>%
slice(which.min(x), which.max(x)) %>%
mutate(cut_poly = letters[c(1,3)]) %>%
bind_rows(data.frame(x = 128, y = -208, cut_poly = letters[1:3], stringsAsFactors = FALSE)) %>%
arrange(x) #important to arrange, otherwise you get irregular polygons
data_plot <- rbind(data_polygon,data_add)
ggplot(data_plot) +
geom_polygon(aes(x, y, fill = cut_poly), color = 'black')
由reprex软件包(v0.3.0)创建于2019-12-05
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句