2017-06-24 7 views
1

私はggplotで> 741行をプロットするのに助けが必要です。カラーラインggplot最終値r

  1. 特定の1行の色は変更しないでください。カラーラインはeciの最終値によってのみ割り当てられるべきです。 700行を超えるもちろん
  2. 先頭に各ラインの私は(コード例では、「単位」)の名前を表示したい
  3. 、各行の終わり
  4. は肉眼で区別するのは難しいが、いずれかでありますラインをより区別しやすくする方法を提案しますか?あなたの望ましい結果を達成するために

    df <- data.frame(unit=rep(1:741, 4), 
           year=rep(c(2012, 2013, 2014, 2015), each=741), 
           eci=round(runif(2964, 1, 741), digits = 0)) 
    
    g = ggplot(data = df, aes(x=year, y=eci, group=unit)) + 
         geom_line(aes(colour=eci), size=0.01) + 
         scale_colour_gradientn(colours = terrain.colors(10)) + 
         geom_point(aes(colour=eci), size=0.04) 
        # The colour of the line should be determined by all eci for which year=2015 
    
+0

私は申し訳ありません - どういうわけか、私は今、適切な形式にコードをフォーマットすることはできません。 – BeSeLuFri

答えて

1

わかりやすくするため、私はdirectlabels-packageを使用して10行の例を選択しました。

library(ggplot2) 
library(dplyr) 
library(directlabels) 

set.seed(95) 


l <- 10 

df1 <- data.frame(unit=rep(1:l, 4), 
       year=rep(c(2012, 2013, 2014, 2015), each=l), 
       eci=round(runif(4*l, 1, l), digits = 0)) 


df2 <- df1 %>% filter (year == 2015) %>% select(-year, end = eci) 

df <- left_join(df1,df2, by = "unit") 

g <- 
    ggplot(data = df, aes(x=year, 
          y=eci, 
          group=unit)) + 
    geom_line(aes(colour=end), size=0.01) + 
    scale_colour_gradientn(colours = terrain.colors(10)) + 
    geom_point(aes(colour=eci), size=0.04) + 
    geom_dl(aes(label = unit,color = end), method = list(dl.combine("first.points", "last.points"), cex = 0.8)) 

g 
+0

素晴らしい1ラインソリューション!残念ながら、geom_dlは200を超える値の処理には非常に時間がかかります。 – BeSeLuFri

1

一つの方法は、ggplot2をプロットするときに使用する追加の情報を新しい列を作成しています。

dplyrでは、単位でデータをグループ化して並べ替えるので、最後のeciの値を格納する列と、最初と最後の年のラベルが付いた2つの列を作成して追加できますプロットへのテキストとして。

df_new <- df %>% 
    group_by(unit) %>% 
    arrange(unit, year, eci) %>% 
    mutate(last_eci = last(eci), 
     first_year = ifelse(year == 2012, unit, ""), 
     last_year = ifelse(year == 2015, unit, "")) 

次に、プロットします。結果のプロットを見ている。もちろん、

ggplot(data = df_new, 
     aes(x = year, y = eci, group = unit, colour = last_eci)) + 
    geom_line(size = 0.01) + 
    geom_text(aes(label = first_year), nudge_x = -0.05, color = "black") + 
    geom_text(aes(label = last_year), nudge_x = 0.05, color = "black") + 
    scale_colour_gradientn(colours = terrain.colors(10)) + 
    geom_point(aes(colour = eci), size = 0.04) 

、それは単一のプロットに>異なる色の700行と> 1400枚のラベルをプロットしようとすることは非常に賢明ではないことを確認するのは簡単です。

私はdfという関連するサブセットを使用していますので、データをよりよく理解するのに役立つプロットを作成します。

df_new %>% 
    filter(unit %in% c(1:10)) %>% 
    ggplot(data = ., 
     aes(x = year, y = eci, group = unit, colour = last_eci)) + 
    geom_line(size = 0.01) + 
    geom_text(aes(label = first_year), nudge_x = -0.05, color = "black") + 
    geom_text(aes(label = last_year), nudge_x = 0.05, color = "black") + 
    scale_colour_gradientn(colours = terrain.colors(10)) + 
    geom_point(aes(colour = eci), size = 0.04)