首页 > 解决方案 > 在 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')

谢谢你。

标签: rggplot2smoothing

解决方案


根据这篇文章(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')

推荐阅读