2017-04-13 62 views
0

我使用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 

以下是圖像:

ggplot df1 and df2 wrong legend

你會發現,在傳說中這兩個項目有一個圓圈,三角形,相同的尺寸和線型。

也許劇情代碼是完全錯誤的,所以我願意接受任何建議,並準備學習:)

+0

將您的數據與標識符變量「綁定」會更簡單,該標識符變量來自哪個數據幀。 '庫(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

+0

感謝您的快速回復@alistaire,它看起來與已編碼的內容非常相似。大拇指! –

回答

0

你將不得不在傳說和主題的變化增加,但這應該得到你想要的位置。

library(ggplot) 
library(dplyr) 
set.seed(5703) 
# DATA 1 
x1 <- seq(1, 100) 
y1 <- rnorm(mean = 50, sd = 10, length(x1)) 
df1 <- data.frame(x = x1, y = y1, group = "A") 
head(df1) 

# DATA 2 
x2 <- seq(1, 100, 5) 
y2 <- rnorm(mean = 50, sd = 2, length(x2)) 
df2 <- data.frame(x = x2, y = y2, group = "B") 
head(df2) 

df <- bind_rows(df1, df2) 

# Plot: DATA 1 and DATA 2 
p101 <- ggplot (df, aes(x = x, y = y, color = group)) + 
    geom_line(aes(linetype = group), size = 0.5) + 
    geom_point(aes(shape = group), size = 4) 
+0

感謝它的魅力! –

+0

爲了獲得預期的結果,我已經看到了很多使用融合或bind_rows的ggplots。我的代碼出了什麼問題?請告訴我我沒有想清楚什麼?任何閱讀建議?謝謝 –