r - 在 ggplot2 中的平滑线末端添加一个点(类似棒棒糖)
问题描述
我想在 ggplot2 中一条平滑线的末端添加一个点(类似棒棒糖)。
代码示例:
df.test <- structure(list(Country = c("USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA", "USA"), startDate = structure(c(18622,
18623, 18624, 18625, 18626, 18627, 18628, 18629, 18630, 18631,
18632, 18633, 18634, 18635, 18636, 18637, 18638, 18639, 18640,
18641, 18642), class = "Date"), endDate = structure(c(20332,
20878, 20819, 20666, 20485, 20332, 20209, 20089, 20028, 19997,
20028, 19967, 19875, 19754, 19662, 19509, 19389, 19358, 19297,
19266, 19236), class = "Date")), row.names = c(NA, -21L), class = c("tbl_df",
"tbl", "data.frame"))
ggplot(df.test, aes(x=startDate, y=endDate)) +
geom_line(color='lightgrey') +
geom_smooth(method="auto", se=FALSE, fullrange=FALSE, size = 0.75) +
theme_light() +
ggtitle('title') +
xlab('Start date') +
ylab('Expected end date')
谢谢你。
解决方案
根据这篇文章(https://stackoverflow.com/a/9790803fit
),您可以先通过以下代码获取平滑线作为对象的数据:
ggplot(df.test, aes(x=startDate, y=endDate)) +
geom_smooth(aes(outfit=fit<<-..y..), method="auto")
并使用该fit
对象绘制点:
ggplot(df.test, aes(x=startDate, y=endDate)) +
geom_line(color='lightgrey') +
geom_smooth(method="auto", se=FALSE, fullrange=FALSE, size = 0.75) +
geom_point(data=tibble(startDate=df.test %>% filter(row_number()==n()) %>% .$startDate,
endDate=structure(fit[length(fit)], class="Date")), colour="purple") +
theme_light() +
ggtitle('title') +
xlab('Start date') +
ylab('Expected end date')
推荐阅读
- c++ - 如何修复我的输出的无限循环?
- javascript - Larvel 5.8:从 javascript 但不是从浏览器调用路由时忽略中间件
- java - 在 JDK 1.8 中导入项目时出现 jaxb2-maven-plugin 问题
- swift - 无法赋值:“downloadURL”是一个 let 常量
- neo4j - Neo4j 映射异常
- vue.js - 如何在 vue 环境中更改我的 c3 图表轴颜色
- memory - Pyspark 作业因阶段失败而中止
- react-native - 意外的标记。运行 jest 时的 state = {}
- terraform - Terraform - GCP - 将 IP 地址链接到链接到云存储桶的负载均衡器
- c# - 如何使用C#检查dataGridView中选定行中的单元格是否为空/空?