我使用ggplot,我能夠得到我想要的情節。 但是當我嘗試添加圖例時,出現了一些問題。傳說有不同的形狀,大小和線型;唯一正確的匹配是顏色。r - ggplot與兩個data.frames,圖例錯誤的標識符
下面是代碼,使用模擬數據:
library(ggplot)
set.seed(5703)
# DATA 1
x1 <- seq(1, 100)
y1 <- rnorm(mean = 50, sd = 10, length(x1))
df1 <- data.frame(x1, y1)
head(df1)
# DATA 2
x2 <- seq(1, 100, 5)
y2 <- rnorm(mean = 50, sd = 2, length(x2))
df2 <- data.frame(x2, y2)
head(df2)
# Plot: DATA 1 and DATA 2
p101 <- ggplot (df1, aes(x = x1, y = y1)) +
geom_point(aes(color="Vals every 1sec - shape circle"), shape = 1, size = 4) +
geom_line (aes(color="Vals every 1sec - shape circle"), size = 0.5, linetype= "dotdash") +
geom_point(data= df2, aes(x = x2, y = y2, color="Vals every 5sec - shape: triangle & bigger, line: thicker"), shape= 2, size= 6) +
geom_line (data= df2, aes(x = x2, y = y2, color="Vals every 5sec - shape: triangle & bigger, line: thicker"), size = 1.25, linetype = "solid") +
scale_colour_manual("", values=c("Vals every 1sec - shape circle" = "#e66101",
"Vals every 5sec - shape: triangle & bigger, line: thicker" = "#5e3c99"))+
theme(legend.position = c(0.7,0.1))+
labs (title = "Graph Nr. 101", x = "Time [s]", y = "Values")
p101
# legend is mixed up, it is not showing the correct shapes and sizes for each data
以下是圖像:
你會發現,在傳說中這兩個項目有一個圓圈,三角形,相同的尺寸和線型。
也許劇情代碼是完全錯誤的,所以我願意接受任何建議,並準備學習:)
將您的數據與標識符變量「綁定」會更簡單,該標識符變量來自哪個數據幀。 '庫(dplyr); bind_rows(setNames(df1,c('x','y')),setNames(df2,c('x','y')),.id ='line')%>%ggplot(aes(x = x,y = y,linetype = line,color = line,shape = line))+ geom_point()+ geom_line()',但您需要清理縮放以符合您的偏好。 – alistaire
感謝您的快速回復@alistaire,它看起來與已編碼的內容非常相似。大拇指! –