2016-04-14 20 views
1

これはかなり基本的な質問のようですが、私はggplot2には比較的新しいので、これを理解できないようです。私がここで誤解している「文法」について何か基本的なものがある場合、誰かが私を正しい方向に向けることができれば素晴らしいだろう。折れ線グラフggplot2のマニュアル凡例ラベルR

#colour palette (colorblind-friendly) 
cbb <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") 
#plot 
avgTermsplot <- ggplot(data=avgTerms, aes(itNum, avgTerms[,2])) 
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,2], colour=cbb[2])) 
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,3], colour=cbb[3])) 
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,4], colour=cbb[4])) 
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,5], colour=cbb[5])) 
avgTermsplot <- avgTermsplot + labs(x="Iteration Number", y="Avg # of Tags Applied") 

print(avgTermsplot) 
:私はそうのようなそれとの基本的なラインプロットを作る

avgTerms <- data.frame(itNum = seq(1,15), 
        i15 = runif(15,5,7), 
        i20 = runif(15,5.5,7.5), 
        i25 = runif(15,4,7), 
        i30 = runif(15,6,8)) 

:それとも、これらのラベルを変更する方法を私に言ってすることは素晴らしいことだ...

は、私はこの(偽の)データを持っていると言います

ご覧のとおり、凡例のラベルはカラーコードです。役に立たない。私はそれらをdata.frameの列名にします。 (i15i20などである必要があります)ベクトルnames(avgTerms)[2:5]から割り当てようとしているものを試してみましたが、これらのものはどれもうまく動作していないと思われます。文字ベクトルから凡例ラベルを割り当てる簡単な方法はありますか?

ありがとうございました。

答えて

0

ggplot2のために、長い形式のデータを使用することをお勧めしますので、最初にデータを溶かしています:

library(reshape2) 
avgTerms.m <- melt(avgTerms, id.vars = "itNum") 

をそしてvariableに基づいて色を割り当てる:

ggplot(data = avgTerms.m, aes(itNum, value, colour = variable)) + 
    geom_line() + 
    labs(x = "Iteration Number", y = "Avg # of Tags Applied") + 
    scale_colour_manual(values = cbb) 

enter image description here

+0

パーフェクト。それが私が望んだ正確な結果です。しかし、将来の参照のために、凡例にラベルを手動で設定する方法はありますか? – seth127

+0

はい、 '?scale_colour_manual'を見ると、' scale_colour_manual(values = cbb、labels = c( "label1"、 "label2"、 "label3"、 "label4")) '' – beetroot

関連する問題