web-dev-qa-db-ja.com

ggplotで凡例(テキスト)ラベルを編集する

私はドキュメンテーションとStackOverflowを調べるのに何時間も費やしました、しかし私の問題を解決するような解決策はないようです。 ggplotを使うとき、たとえそれが私のデータフレームの中にあったとしても、私は凡例の中に正しいテキストを得ることができません。私は、c("T999", "T888")", "cols"のようにscale_colour_manualの値を変えてscale_fill_manuallabels=を試しました。

これが私のコードです:

T999 <- runif(10, 100, 200)
T888 <- runif(10, 200, 300)
TY <- runif(10, 20, 30)
df <- data.frame(T999, T888, TY)


ggplot(data = df, aes(x=T999, y=TY, pointtype="T999")) + 
       geom_point(size = 15, colour = "darkblue") + 
       geom_point(data = df, aes(x=T888, y=TY), colour = 'red', size = 10 ) + 
       theme(axis.text.x = element_text(size = 20), axis.title.x =element_text(size = 20),   axis.text.y = element_text(size = 20)) +
       xlab("Txxx") + ylab("TY [°C]") + labs(title="temperatures", size = 15) + 
       scale_colour_manual(labels = c("T999", "T888"), values = c("darkblue", "red")) +    theme(legend.position="topright")

助けていただければ幸いです。

102
user3633161

@Henrikが説明したチュートリアルは、ggplot2パッケージでプロットを作成する方法を学ぶための優れたリソースです。

あなたのデータの例:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

これは次のようになります。

enter image description here

コメントの@ user2739472で述べられているように:ggplotのデフォルトパレットから色を変えずに凡例のテキストラベルを変えたいだけなら、scale_color_hue(labels = c("T999", "T888"))の代わりにscale_color_manual()を使うことができます。

109
Jaap

凡例のタイトルは、特定の審美的でラベル付けできます。

これはggplot2guides()またはlabs()関数(more here および here )を使って実現できます。審美的なマッピングを使用してガイド/凡例のプロパティを追加できます。

mtcarsデータセットとlabs()を使った例です。

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

guides()を使用してOPの質問に答える:

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

32
Megatron