我正在尝试用不同的颜色填充下图中的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。
现在让我们详细说明一下:如especially in this GitHub thread中所述,不可能访问geom_curve
生成的坐标(它使用CurveGrob
进行绘图,并且“这些值都是在绘制时计算的” [@ thomasp85])。其“绘制时行为的计算”的一种效果可以在下面看到-如果添加coord_plot
或不添加geom_spline
,它都会有所不同。这与coord_fixed
不同:添加geom_curve
不会更改坐标。
参见下面的图一和图二:红色曲线是使用ggforce
创建的-它与geom_segment线失去了联系...
@ thomasp85在GitHub线程中建议,可以改用他的软件包coord_fixed
。现在,要真正控制曲率,需要使用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()
不使用ojit_code 红色曲线不触及线段,但黑色曲线仍触及线段
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 package(v0.3.0)创建于2019-12-05
关于r - 如何填充由直线和曲线创建的几何图形?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59113375/