如何为Plotly散点图的首个、末尾及指定数据点添加注释?
R语言Plotly散点图注释添加解决方案
核心需求实现(2006/2021年指定点加注释)
直接用逻辑条件筛选行替代极值定位函数,即可精准匹配目标年份的数据点:
- 2006年第一个点定位规则:匹配
Year == 2006的行 - 2021年最后一个点定位规则:匹配
Year == 2021的行
次要需求实现
1. 任意指定点加注释
你可以通过多条件组合筛选定位任意数据点,示例定位方式如下:
# 示例:定位2013年、学历为BA、岗位为Valet的点 target_point <- Earnings_Year[Earnings_Year$Year == 2013 & Earnings_Year$Degree == "BA" & Earnings_Year$Job == "Valet", ] # 后续直接将target_point$Year、target_point$Month_USD传入add_annotations的x/y参数即可
2. 每个点悬浮展示Job信息
修改plot_ly中text参数的拼接内容,把Job字段加入悬浮提示即可。
完整可运行代码
首先导入你提供的数据集:
Earnings_Year <- structure(list(Year = 2006:2021, Month_USD = c(1160L, 1240L, 1360L, 1480L, 1320L, 1320L, 375L, 1600L, 2000L, 2000L, 1600L, 2240L, 1900L, 2300L, 2900L, 2300L), Degree = c("High School", "High School", "High School", "High School", "High School", "High School", "High School", "High School", "High School", "BA", "BA", "BA", "BA", "BA", "M.Ed", "M.Ed"), Country = c("USA", "USA", "USA", "USA", "USA", "USA", "DE", "USA", "USA", "USA", "USA", "USA", "PRC", "PRC", "PRC", "HK"), Job = c("Disher", "Prep", "Prep", "Prep", "Prep", "Prep", "Au Pair", "CSA", "Valet", "Valet", "Intake", "CM", "Teacher", "Teacher", "Teacher", "Student"), Median_Household_Income_US = c(4833L, 4961L, 4784L, 4750L, 4626L, 4556L, 4547L, 4706L, 4634L, 4873L, 5025L, 5218L, 5360L, 5725L, NA, NA), US_Home_Price_Index = c(183.24, 173.36, 152.56, 146.69, 140.64, 135.16, 143.88, 159.3, 166.5, 175.17, 184.51, 195.99, 204.9, 212.59, 236.31, NA)), class = "data.frame", row.names = c(NA, -16L))
绘图代码:
library(plotly) pal <- c("Red", "Blue", "Green") plot_ly(data = Earnings_Year, x=~Year, y=~Month_USD, type='scatter', mode='markers', symbol = ~as.factor(Degree), symbols=c("star-open-dot","hexagon-open-dot","diamond-open-dot"), color = ~as.factor(Degree), colors = pal, hoverinfo="text", # 新增Job、学历、国家字段到悬浮提示 text= ~paste("年份: ", Year, "<br>", "月收入(美元): ", Month_USD, "<br>", "学历: ", Degree, "<br>", "岗位: ", Job, "<br>", "国家/地区: ", Country), size=10) %>% # 原有极值点注释 add_annotations( x=~Year[which.min(Month_USD)], y=~Month_USD[which.min(Month_USD)], text = "德国互惠生岗位", showarrow = T, arrowhead = 2 ) %>% add_annotations( x=~Year[which.max(Month_USD)], y=~Month_USD[which.max(Month_USD)], text = "中国最后一份教师岗位", showarrow = T, arrowhead = 2 ) %>% # 新增2006年第一个点注释 add_annotations( x=~Year[Year == 2006], y=~Month_USD[Year == 2006], text = "2006年第一份洗碗工岗位", showarrow = T, arrowhead = 2 ) %>% # 新增2021年最后一个点注释 add_annotations( x=~Year[Year == 2021], y=~Month_USD[Year == 2021], text = "2021年香港学生身份", showarrow = T, arrowhead = 2 ) %>% layout(legend= list(x=1,y=0.5), title="收入随学历变化趋势", xaxis=list(title="年份"), yaxis=list(title="月收入(美元)"))
如果不需要注释显示箭头,只需在add_annotations中添加参数showarrow = F即可,注释文本内容可根据需求自行调整。
内容的提问来源于stack exchange,提问作者Shawn Hemelstrand
相关产品推荐
相关产品推荐

