如何以编程方式在ggplot2中传递参数aes()函数?

时间:2019-06-25 02:35:40

标签: r ggplot2 tidyr

我正在开发一个函数,以便在同一日期轴上绘制多个时间序列,并且我想添加一个图例,以显示每个时间序列的名称和线条颜色。

该函数需要通用化,以便时间序列的数目及其名称是任意的。

多个时间序列位于我通过从网络上下载信息而建立的数据框中的列中。压缩版本如下:

if (Session["LoggedUser"] != null) HttpContext.Current.Response.Redirect("appHunt_IndexPage.html"); else HttpContext.Current.Response.Redirect("login.html");

然后我创建一个列名的字符向量,我在 Date IVV_Price IWO_Price IEMG_Price 1 2012-10-24 141.59 92.22 48.22 2 2012-10-25 142.02 92.54 48.54 3 2012-10-26 141.93 92.06 48.19 4 2012-10-31 141.48 92.53 48.23 5 2012-11-01 143.46 93.76 49.00 6 2012-11-02 142.10 92.07 48.56 7 2012-11-05 142.41 92.82 48.93 8 2012-11-06 143.51 93.45 49.27 9 2012-11-07 140.25 91.49 48.55 10 2012-11-08 138.58 90.11 48.06 循环中使用该向量来索引到该向量中以获得每个列名。

这是列名向量的样子:

for()

这是我用来构建ggplot对象的代码,该问题的相关代码部分是Browse[2]> plot_names [1] "Date" "IVV_Price" "IWO_Price" "IEMG_Price" 注释行之后显示的for()循环:

#Include each of the columns in the plot

如果我省略了color参数,那么这部分都可以正常工作,但是当我添加color参数时,它将引发以下错误:

  

grDevices :: col2rgb(colour,TRUE)中的错误:     无效的颜色名称“ IVV_Price”

实际上,在 p.plot <- ggplot(plot.df, aes(x = Date)) + scale_x_date( date_breaks = "1 year", date_labels = "%e/%m/%y", date_minor_breaks = "1 month" ) + theme(panel.grid.major = element_line(colour = "grey85", size = 0.75)) + scale_color_brewer(palette = "Set1") + labs( title = p.name, subtitle = "Initialized to $1,000", y = "Value", color = "Legend" ) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + if (isTRUE(log_scale)) { scale_y_log10() } else { scale_y_continuous() } #Include each of the columns in the plot for (i in 1:(length(column_vector) - 1)) { p.plot <- p.plot + geom_line(aes_string(y = plot_names[i + 1]), color = plot_names[i + 1]) } print(p.plot) 函数中,color参数似乎根本不起作用。

因此,我似乎一直坚持寻找一种方法来使代码使用aes_string()而不是aes()进行工作,并且最近几天我一直在花很多时间试图了解Tidy用引号,准引号等rlang概念进行评估,以查看是否可以找到一种方法将基于字符的列名放入aes_string()中。

如果我使用aes()手动构建图并插入每个列名,则可以使此工作正常进行:

aes()

我需要一种在 ggplot(My_Portfolio, aes(x = Date)) + geom_line(aes(y = IVV_Price, color = "IVV")) + geom_line(aes(y = IWO_Price, color = "IWO")) + geom_line(aes(y = IEMG_Price, color = "IEMG")) + scale_x_date(date_breaks = "1 year", date_labels = "%e/%m/%y", date_minor_breaks = "1 month") + theme(panel.grid.major = element_line(colour = "grey85", size = 0.75)) + scale_color_brewer(palette = "Set1") + scale_y_log10() + labs(title = "My Stocks", subtitle = "Initialized to $1,000", y = "Value", color = "Legend") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) 循环中执行此操作并索引到字符向量中以获得每个连续列名的方法。

0 个答案:

没有答案