【发布时间】:2016-08-29 08:37:17
【问题描述】:
我正在尝试向使用 ggplot 创建的图添加图例。我从两个 csv 文件中加载数据,每个文件都有两列 8 行(不包括标题)。
我从每个文件构造一个包含累积总数的数据框,因此该数据框包含三列数据(bv、bin_count 和 bin_cumulative),每列 8 行,每个值都是一个整数.
然后将这两个数据集绘制如下。显示很好,但我不知道如何在结果图中添加图例,因为 ggplot 对象本身似乎应该有一个数据源,但我不确定如何构建一个有多列相同的列名字。
library(ggplot2)
i2d <- data.frame(bv=c(0,1,2,3,4,5,6,7), bin_count=c(0,0,0,2,1,2,2,3), bin_cumulative=cumsum(c(0,0,0,2,1,2,2,3)))
i1d <- data.frame(bv=c(0,1,2,3,4,5,6,7), bin_count=c(0,1,1,2,3,2,0,1), bin_cumulative=cumsum(c(0,1,1,2,3,2,0,1)))
c_data_plot <- ggplot() +
geom_line(data = i1d, aes(x=i1d$bv, y=i1d$bin_cumulative), size=2, color="turquoise") +
geom_point(data = i1d, aes(x=i1d$bv, y=i1d$bin_cumulative), color="royalblue1", size=3) +
geom_line(data = i2d, aes(x=i2d$bv, y=i2d$bin_cumulative), size=2, color="tan1") +
geom_point(data = i2d, aes(x=i2d$bv, y=i2d$bin_cumulative), color="royalblue3", size=3) +
scale_x_continuous(name="Brightness", breaks=seq(0,8,1)) +
scale_y_continuous(name="Count", breaks=seq(0,12,1)) +
ggtitle("Combine plot of BV cumulative counts")
c_data_plot
我是 R 的新手,非常感谢任何帮助。
根据 cmets,我已编辑代码以在数据集加载到数据帧后重现数据集。
关于生成单个数据框,我欢迎就如何实现这一点提出建议 - 我仍在为数据框的工作原理而苦苦挣扎。
【问题讨论】:
-
请提供一个可重现的例子。
-
乍一看,请考虑在美学调用中包含您的
size和/或color选项。 -
@Cyrus Mohammadian 没错!您目前的“滥用” ggplot 因为您分开很多。尝试制作一个包含所有信息的数据框,然后在 ggplot() 语句中添加大部分信息,作为开始。
-
这能回答你的问题吗? Add legend to ggplot2 line plot