r - ggplot有两个data.frames,图例错误的标识符

时间:2017-04-13 15:25:24

标签: r ggplot2

我正在使用ggplot,我能够得到我想要的情节。 但是当我试图添加一个传奇时,出了点问题。传说有不同的形状,大小和线型;唯一正确的匹配是颜色。

以下是带有模拟数据的代码:

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

您会注意到图例上的两个项目都有一个圆圈和一个三角形,大小和线型相同。

也许情节代码是完全错误的,所以我愿意接受任何建议并准备好学习:)

1 个答案:

答案 0 :(得分: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 )