2017-08-30 68 views
1

大家好:我努力在ggplot2中按日期着色點。這裏有兩個結果對我有用。 1)通過變量recent_elections對點進行着色,並且只添加代表每個點最近一次選舉日期的直線。目前的代碼是這樣做的。 2)最好,但更難,只需添加線條,爲每次選舉着色不同,顯示一個印有最近聯邦選舉日期的圖例。在ggplot2中的日期顏色點

我目前的數據和嘗試如下。

library(dplyr) 
library(tidyr) 
library(ggplot2) 

members <- structure(list(date = structure(c(6209, 6574, 7305, 14984, 15339, 
15341, 17169, 17174), class = "Date"), members = c(180835, 193225, 
200010, 86545, 95000, 128351, 41000, 124000), population = c(26449000, 
26798000, 27512000, 33476688, 33476688, 33476688, 35151728, 35151728 
), votes_previous_election = c(2359915, 2685263, 2685263, 4508474, 
4508474, 4508474, 3470350, 3470350), vote_percent = c(18.8, 20.4, 
20.4, 30.6, 30.6, 30.6, 19.7, 19.7), seats_previous_election = c(32, 
43, 43, 103, 103, 103, 44, 44), recent_election = structure(c(5360, 
6899, 6899, 15096, 15096, 15096, 16727, 16727), class = "Date")), .Names = 
c("date", 
"members", "population", "votes_previous_election", "vote_percent", 
"seats_previous_election", "recent_election"), class = "data.frame", 
row.names = c(NA, 
-8L)) 

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(aes(fill=recent_election))+ 
    facet_wrap(~Variable, scales='free')+ 
    geom_vline(data=members, aes(xintercept=as.numeric(recent_election), col='red'), show.legend=F) 

enter image description here

回答

0
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) 

enter image description here

我在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自動設置上限。