10

ggplot21つに2つのグラフがある単純な古典的なプロットを作成しました。しかし、私は伝説を示すのに苦労しています。伝説を示していません。私は溶けて形を変える方法を使用しませんでした、私はただ古典的な方法を使用します。以下は私のコードです。

df <- read.csv("testDataFrame.csv")

graph <- ggplot(df, aes(A)) + 
  geom_line(aes(y=res1), colour="1") +
  geom_point(aes(y=res1), size=5, shape=12) +
  geom_line(aes(y=res2), colour="2") +
  geom_point(aes(y=res2), size=5, shape=20) +
  scale_colour_manual(values=c("red", "green")) +
  scale_x_discrete(name="X axis") +
  scale_y_continuous(name="Y-axis") +
  ggtitle("Test") 
  #scale_shape_discrete(name  ="results",labels=c("Res1", "Res2"),solid=TRUE) 

print(graph)

データフレームは次のとおりです。

 A,res1,res2
 1,11,25
 2,29,40
 3,40,42
 4,50,51
 5,66,61
 6,75,69
 7,85,75

上記のグラフの凡例を表示する方法について何か提案はありますか?

4

1 に答える 1

12

では、設定した美学 ( )ggplot2ごとに凡例が表示されます。、、aesなど。そのためには、次の形式でデータを取得する必要があります。groupcolourshape

A variable value
1     res1    11
...    ...    ...
6     res1    85
7     res2    75

以下をreshape2使用してこれを実現できます。melt

require(reshape2)
require(ggplot2)

ggplot(dat = melt(df, id.var="A"), aes(x=A, y=value)) + 
      geom_line(aes(colour=variable, group=variable)) + 
      geom_point(aes(colour=variable, shape=variable, group=variable), size=4)

たとえば、ポイントが必要ない場合はcolour、から削除colour=variablegeom_point(aes(.))ます。その他の凡例オプションについては、 に従ってthis linkください。

ここに画像の説明を入力

于 2013-03-14T19:35:09.520 に答える