且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ggplot2中按日期颜色点

更新时间:2022-12-15 13:52:08

members %>% 
  select(population, votes_previous_election, seats_previous_election, members, 
         date, recent_election) %>% 
  mutate(., members_per_capita=members/population, 
         members_votes=members/votes_previous_election, 
         members_seats=members/seats_previous_election) %>% 
  gather(Variable, Value, c(members_per_capita,members_votes, 
                            members_seats))%>% 
  ggplot(., aes(x=date, y=Value, 
                group=recent_election))+
  geom_point()+
  geom_vline(data=members, aes(xintercept=as.numeric(recent_election), col=factor(recent_election)), show.legend=T)+
  facet_wrap(~Variable, scales='free') +
  scale_color_discrete(name = "Recent Election") + xlim(as.Date("1984-01-01"), NA)

我将 geom_vline 中的 col ="red" 更改为 col = factor(recent_election),以便垂直线用 recent_election . factor()确保将 recent_election 视为离散的而不是连续的. scale_color_discrete 设置图例标题.请注意,选举日期"1984-09-04"超出了您的得分的x范围,因此我添加了 xlim(as.Date("1984-01-01"),NA)还包括该选举日期. NA 自动设置上限.

I changed the col="red" in geom_vline to col=factor(recent_election) so that the vertical lines are colored by recent_election. The factor() makes sure that recent_election is treated as discrete instead of continuous. scale_color_discrete sets the legend title. Note that the election date "1984-09-04" is going out of the x range of your points, so I added a xlim(as.Date("1984-01-01"), NA) to also include that election date. NA sets the upper limit automatically.