R legend() 関数 - 凡例を追加
R legend() 関数はグラフに凡例を追加し、読者が異なるデータ系列を識別するのに役立ちます。
グラフに複数のデータ系列が含まれる場合、凡例は不可欠な要素です。
legend() 関数の構文は次のとおりです:
legend(x, y = NULL, legend, col, pch, lty, lwd, fill, title = NULL)
パラメータの説明:
x, y凡例の位置: "topright"、"bottomleft" などのキーワード、または座標。
legend凡例のテキストラベル。
col各データ系列の色。
pch点記号のタイプ。
lty線の種類。
例
# 3つの製品の月次販売量トレンド
month <- 1:6
product_a <- c(100, 120, 115, 135, 145, 160)
product_b <- c(85, 90, 95, 100, 105, 110)
product_c <- c(60, 70, 80, 75, 90, 88)
# 折れ線グラフを描画
plot(month, product_a, type = "o",
col = "steelblue", lwd = 2, pch = 16,
ylim = c(50, 170),
main = "各製品の月次販売量トレンド",
xlab = "月", ylab = "販売量")
lines(month, product_b, type = "o",
col = "coral", lwd = 2, pch = 17)
lines(month, product_c, type = "o",
col = "seagreen", lwd = 2, pch = 18)
# 凡例を追加
legend("topleft",
legend = c("製品A", "製品B", "製品C"),
col = c("steelblue", "coral", "seagreen"),
pch = c(16, 17, 18),
lwd = 2,
title = "製品カテゴリ")
month <- 1:6
product_a <- c(100, 120, 115, 135, 145, 160)
product_b <- c(85, 90, 95, 100, 105, 110)
product_c <- c(60, 70, 80, 75, 90, 88)
# 折れ線グラフを描画
plot(month, product_a, type = "o",
col = "steelblue", lwd = 2, pch = 16,
ylim = c(50, 170),
main = "各製品の月次販売量トレンド",
xlab = "月", ylab = "販売量")
lines(month, product_b, type = "o",
col = "coral", lwd = 2, pch = 17)
lines(month, product_c, type = "o",
col = "seagreen", lwd = 2, pch = 18)
# 凡例を追加
legend("topleft",
legend = c("製品A", "製品B", "製品C"),
col = c("steelblue", "coral", "seagreen"),
pch = c(16, 17, 18),
lwd = 2,
title = "製品カテゴリ")
上記のコードを実行すると、3本の販売量の折れ線と、色で区別された凡例が表示されます。
その他の拡張
R言語の例