r - 插值数据以映射渐变 alpha
问题描述
取以下数据
df <- data.frame(ID = c(1, 1, 2, 2, 3, 3),
cond = c(2, 2, 2, 2, 1, 1),
Time = c(1,2,1,2,1,2),
State = c(0, 0, 0, 1, 1, 0),
eyes = c(2, -3, -2, 1, 0, -2),
combination = c("1", "1","2", "2", "3", "3"))
df$cond <- factor(df$cond,levels = c("1", "2"))
ggplot(df, aes(x = Time, y = eyes)) +
ggforce::geom_link2(aes(group=ID, color = cond, alpha = State), size = 5, n = 500, lineend = "round") +
scale_color_manual(values=c("#CC6666", "#9999CC")) +
scale_alpha_continuous(range = c(0.01, 0.9)) +
scale_shape_manual(values=c(13,15)) +
theme(legend.title=element_blank(),
axis.title.x=element_text(size = 12),
axis.title.y=element_text(size = 12),
plot.title = element_text(hjust = 0.5, size = 15),
axis.text.x= element_text(color = "black"),
axis.text.y= element_text(color = "black"),
axis.line = element_line(colour = "black"),
plot.background = element_rect(fill = "white"),
panel.background = element_rect(fill = "white"))
我试图通过 alpha 的连续变化使第 2 行和第 3 行在 x 轴上出现/消失。
第一行(“组合 1”)看起来正确,但我希望“组合 2”(蓝色)线的 alpha = 0 直到 x 轴上的点 1.4,然后逐渐淡入(在 x 上的点 2.00 处达到 alpha 1 -axis)并且我希望“组合 3”(红线)逐渐淡出,并不断降低 alpha,直到点 1.6,之后 alpha 应该 = 0。
我认为问题在于“状态”被映射为 0 和 1,并且需要中间值来指定如何绘制线条/alpha,但我一直无法找到一种方法来做到这一点。
任何帮助深表感谢。
解决方案
为了能够做到这一点,你需要一个渐变。如果使用 atibble
而不是data.frame
与 `tidyr::unnest' 一起使用,则可以轻松生成如下:
ex_data <- tibble::tibble(
x = list(seq(0, 1, .1), seq(1, 0, -.1)),
y = list(seq(-1, 0, .1), seq(0, 1, .1)),
alpha_change = list(seq(0, 1, .1), seq(1, 0, -.1))
)
然后数据看起来像这样:
# A tibble: 2 x 3
x y alpha_change
<list> <list> <list>
1 <dbl [11]> <dbl [11]> <dbl [11]>
2 <dbl [11]> <dbl [11]> <dbl [11]>
可以将其取消嵌套tidyr::unnest
以生成以下内容:
ex_data_unnested <- tidyr::unnest(ex_data, everything())
ex_data_unnested
# A tibble: 22 x 3
x y alpha_change
<dbl> <dbl> <dbl>
1 0 -1 0
2 0.1 -0.9 0.1
3 0.2 -0.8 0.2
4 0.3 -0.7 0.3
5 0.4 -0.6 0.4
6 0.5 -0.5 0.5
7 0.6 -0.4 0.6
8 0.7 -0.3 0.7
9 0.8 -0.2 0.8
10 0.9 -0.1 0.9
# ... with 12 more rows
现在可以使用它来绘制 alpha 的梯度:
ggplot2::ggplot(ex_data_unnested, ggplot2::aes(x, y, alpha = alpha_change)) +
ggplot2::geom_line()
推荐阅读
- apache-spark - 与使用 Pyspark 的另一个表相比,检查数据框中是否存在重复项
- elasticsearch - 在 Kibana 中,如何对嵌套字段求和,然后为每个文档存储桶?
- python - 如何在没有json的python中获取api输出
- xml - 将 Google Analytics 集成到 VAST Preroll XML
- php - PHP __DIR__ 在本地工作但不在生产环境中
- postgresql - 使用 pg:push 到 Heroku PostgreSQL 数据库时出错
- ios - API 未在 Swift for iOS 中显示数据
- css - 如何在没有任何样式问题的情况下链接到另一个页面中的位置?
- python - 告诉 Flask 仅将上传内容存储在内存中,而不使用临时文件
- wordpress - 想在 wordpress 上显示我的世界玩家统计数据吗?