如何在函数中自动执行ggplot图?-R [英] how to automatize ggplot plots in a function? - R

查看:71
本文介绍了如何在函数中自动执行ggplot图?-R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何自动 ggplot (在函数中)(这样),以便人们可以选择要绘制的列.IE.:给出以下数据:

How can ggplot be automatized (in a function?) such that one can choose which columns to plot. i.e.: given the following data:

DT <- data.frame(y=seq(0,10,1),x=seq(0,20,2),z=seq(0,30,3))

例如,我想:首先将 Y对X绘制,然后对 Y对Z绘制我已经尝试过下面的(简单)代码,但是没有成功:

I would like to for example: firstly plot Y against X and then Y against Z I have tried the (simple) code below, but with no success:

fun<- function (y,x){
    Yaxis=paste(y)
    Xaxis=paste(x)

    Plot <- ggplot() + geom_point(data = DT,
                            aes(x=Yaxis, y=Xaxis))
return(Plot)
}
fun("y","x")
fun("y","z")

推荐答案

您的意思是这样的吗?

# create the dataset
DT <- data.frame(y=seq(0,10,1),x=seq(0,20,2),z=seq(0,30,3))

# plot data as categorical
fun<- function (df, xaxis, yaxis){
  # convert numeric to character
  Yaxis=paste(df[, yaxis])
  Xaxis=paste(df[, xaxis])
  # create the plot object
  Plot <- ggplot() + geom_point(data = df,
                                aes(x=Yaxis, y=Xaxis))
  # plot it
  return(Plot)
}
# plot y on horizontal, x on vertical
fun(DT,"y","x")
fun(DT,"y","z")

# plot data as numeric
fun2 <- function (df, xaxis, yaxis){
  Yaxis=df[, yaxis]
  Xaxis=df[, xaxis]

  Plot <- ggplot() + geom_point(data = df,
                                aes(x=Yaxis, y=Xaxis))
  return(Plot)
}
# plot y on horizontal, x on vertical
fun2(DT,"y","x")
# plot y on horizontal, z on vertical
fun2(DT,"y","z")

您显然可以进一步自定义绘图,创建灵活的标题,轴注释等.

You can obviously customize the plot further, creating flexible title, axis anotation etc.

这篇关于如何在函数中自动执行ggplot图?-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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