如何在函数中自动化ggplot图? - R.

时间:2017-02-03 13:10:15

标签: r function ggplot2 automation

ggplot 如何自动化(在函数中?),以便可以选择要绘制的列。即: 给出以下数据:

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

我想举个例子:首先将 Y对抗X ,然后 Y对Z 我已尝试过下面的(简单)代码,但没有成功:

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")

1 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

# 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")

您可以进一步自定义绘图,创建灵活的标题,轴旋转等。