簡體   English   中英

如何在ggplot2中為組合圖添加內部圖例

[英]How to add inside legend for a combined plot in ggplot2

我有以下df和ggplot2代碼制作散點圖,但未能在圖內添加圖例。 謝謝 :)

x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6

df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x=x1, y = y1),col='red') + geom_point(aes(x = x2, y = y2),col='black')

嘗試:

x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6

df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x=x1, y = y1, col = "1")) + 
geom_point(aes(x = x2, y = y2, col = "2")) + scale_colour_manual(values = c("red", "black"))

在上面的代碼中,通過將col =“ 1”和col =“ 2” 放在美學aes()內,您是在告訴ggplot向繪圖添加顏色尺寸(而不僅僅是對點“ red”和“黑色”)。 因此,您現在看到一個圖例。 然后,通過將顏色設置為等於“ 1”和“ 2”,您就是說將它們用作標簽。 scale_colour_manual允許您將這些顏色更改為紅色和黑色,而不是默認的“紅色和藍色”。

無論何時要向繪圖添加任何尺寸,都適用相同的規則。 但是, scale_colour_manual使用colscale_colour_manual ,您還可以使用shapescale_shape_manual類的替代scale_shape_manual

這是長格式數據輸入的一種方法

#data into long format
x1 = 1:5 
x2 = 6:10
y1 = 3:7
y2 = 2:6
df <- data.frame(x=c(x1, x2), y=c(y1, y2), group=rep(c("x1", "x2"), c(5, 5)))
#plot it
library(ggplot2)
ggplot(df) + 
  geom_point(aes(x=x, y = y, colour=group))+
  scale_colour_manual(values=c("red", "black"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM