R - 使用ggplot在同一图形上创建三个数据集的图例 [英] R - creating legend for three data sets on same graph using ggplot

查看:492
本文介绍了R - 使用ggplot在同一图形上创建三个数据集的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以为包含使用g中的ggplot的多个系列的图创建图例框。基本上,这就是我正在做的。

I was wondering if it was possible to create a legend box for a graph that contains plots of multiple series using ggplot in R. Essentially, this is what I'm doing.

x <- c(1,2,3,4)
y <- c(1.1,1.2,1.3,1.4)
y2 <- c(2.1,2.2,2.3,2.4)
x3 <- c(4,5,6,7)
y3 <- c(3.1,3.2,3.3,3.2)
p1 <- data.frame(x=x,y=y)
p2 <- data.frame(x=x,y=y2)
p3 <- data.frame(x=x3,y=y3)

ggplot(p1, aes(x,y)) + geom_point(color="blue") + geom_point(data=p2, color="red") + geom_point(data=p3,color="yellow") 

上面的命令会显示所有三个数据集,p1,p2和p3三种不同的颜色。我知道我还没有指定每个数据集的名称,但我将如何创建一个识别不同数据集的图例?换句话说,我只是想要一个传说,说所有的蓝色点都是P1,所有的红色点都是P2,所有的黄色点都是P3。

The command above will make a graph of all three data sets, p1, p2, and p3 in three different colors. I know I haven't as yet specified the names of each data set, but how would I go about creating a legend that identifies the different data sets? In other words, I just want a legend that says that all blue points are P1, all red points are P2, and all yellow points are P3.

推荐答案

您需要将它们转换为单个数据框,并将颜色唯美性映射到点来自哪个数据集。你可以使用 melt 从 reshape 包创建单个data.frame:

You need to turn them into a single data.frame and map the colour aesthetic to which dataset the points come from. You can use melt from reshape package to make the single data.frame:

zz <- melt(list(p1 = p1, p2 = p2, p3 = p3), id.vars = "x")

ggplot(zz, aes(x, value, colour = L1)) + geom_point() +
    scale_colour_manual("Dataset", values = c("p1" = "blue", "p2" = "red", "p3" = "yellow"))

这篇关于R - 使用ggplot在同一图形上创建三个数据集的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆