使用ggplot插入图形图例 [英] insert graph legend using ggplot

查看:209
本文介绍了使用ggplot插入图形图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用ggplot的问题。我有以下data.frame和一个常量。我正在使用下面的函数,我设法让我的情节,但我不能打印图例,我做错了什么?

I have a question regarding the use of ggplot. I have the following data.frame, and a constant. I'm using the following function and I managed to make my plot but I can not print the legend, what am I doing wrong?

这个函数将用于获取该图:

this function would I use to get the plot:

LINER_GRAPH_POWER_LIST_VALUES<-function(DF_N_EPC_AND_FOUND_EPC, DF_READ_EXTERNAL_LIST_EPC_TAGS ){
  require(ggplot2)
  ggplot(DF_N_EPC_AND_FOUND_EPC, aes(x=power_value, y=total_epc), colour = variables) +
  geom_line(color="red") +
  geom_point(color="red", shape=20) +
  geom_line(aes(x=power_value, y=found_epc), color="blue") +
  geom_point(aes(x=power_value, y=found_epc), color="blue", shape=20) +
  geom_hline(yintercept=nrow(DF_READ_EXTERNAL_LIST_EPC_TAGS), color="green")+
  scale_colour_manual(values = c("total_epc"="red","epc_found"="blue", "num_of_list_reference_tags"="green"))
}


d data.frame - > DF_N_EPC_AND_FOUND_EPC

And the data.frame -> DF_N_EPC_AND_FOUND_EPC

    power_value total_epc   found_epc
1   31.5    9   5
2   31.0    7   4
3   30.5    6   4
4   30.0    7   4
5   29.5    8   5
6   29.0    9   5
7   28.5    8   5
8   28.0    9   5
9   27.5    8   4
10  27.0    7   4
11  26.5    8   5
12  26.0    7   5
13  25.5    5   4
14  25.0    5   4
15  24.5    5   4
16  24.0    4   3
17  23.5    4   3
18  23.0    4   3
19  22.5    4   3
20  22.0    4   3

正如您所看到的,我正在使用scale_colour_manual,但图表的图例并未出现。

I'm using scale_colour_manual, as you can see, but the legend of the graph does not appear

推荐答案

为了做到这一点,您必须将数据从宽格式转换为长格式。

In order to do that, you will have to transform your data from wide to long format.

# reading the data
df <- read.table(text="nr    power_value total_epc   found_epc
1   31.5    9   5
2   31.0    7   4
3   30.5    6   4
4   30.0    7   4
5   29.5    8   5
6   29.0    9   5
7   28.5    8   5
8   28.0    9   5
9   27.5    8   4
10  27.0    7   4
11  26.5    8   5
12  26.0    7   5
13  25.5    5   4
14  25.0    5   4
15  24.5    5   4
16  24.0    4   3
17  23.5    4   3
18  23.0    4   3
19  22.5    4   3
20  22.0    4   3", header=TRUE)

# from wide to long format
require(reshape2)
df.m <- melt(df, id=c("power_value","nr"), measure=c("total_epc","found_epc"), variable.name="epc")

# creating the plot
ggplot(df.m, aes(x=power_value, y=value, color=epc)) +
  geom_line() +
  geom_point() +
  geom_hline(yintercept=6, color="green")

结果:

这篇关于使用ggplot插入图形图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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