【问题标题】:ggplot2 multiple plots keeps old plotsggplot2 多个地块保留旧地块
【发布时间】:2016-06-04 03:26:19
【问题描述】:

我正在尝试从数据框中绘制 30 个直方图

'data.frame':   569 obs. of  32 variables:
 $ ID       : int  842302 842517 84300903 84348301 84358402 843786 844359     84458202 844981 84501001 ...
 $ Diag     : Factor w/ 2 levels "B","M": 2 2 2 2 2 2 2 2 2 2 ...
 $ Radius   : num  5.1 5.84 5.59 3.24 5.76 ...
 $ Text     : num  2.41 4.13 4.94 4.74 3.33 ...
 etc....

我想按诊断(恶性或良性癌症)对所有属性进行分组,并将它们作为多图(30 个单独的直方图)一起保存在一个文件中。

但是,当我按照自己的方式进行操作(遍历列)时,ggplot 似乎会以某种方式保留旧数据,并且不会根据当前列进行更改,除非我手动操作。

这是我的绘图循环,它试图将每个图保存在一个列表中:

graph_att<-function(to=10){
  plots<-vector("list",to)
for (i in 1:to){
  dev.next()
  ind<-i+2
  a<-t[1,i] #data.frame with vertical lines I want in the histograms

  g<-ggplot(dataNorm[,c(2,ind)], aes(dataNorm[,ind]))+geom_histogram(aes(fill=Diag), 
  position="identity", colour="#999999", alpha=0.8, binwidth = 0.25)+
  geom_vline(xintercept = a) + 
  scale_fill_manual(values = c("#0072B2", "#E69F00"))

plots[[i]]<-g
rm(g) #trying to make sure its a new plot
}

return(plots)
}

我正在使用http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ 中的 multiplot 函数将其绘制在一起。 但是我得到了这个输出,它只改变垂直线并且只保留一个直方图。

我还想创建另一个 data.frame 并在每一列中放置 $Diag 和其他变量,但不知道如何迭代它们。因为我认为 ggplot 不会访问我想要的列。

感谢您的帮助。

PS:这就是我得到的

my output

【问题讨论】:

  • aes(dataNorm[,ind]) 由于评估不规范,无法正常工作。也许试试aes_string(names(dataNorm)[ind])。可能还有其他问题。如果您需要更多帮助,请提供可重现的示例。
  • 哦,非常感谢罗兰,太棒了!它工作得很好,而且它保持 xlabel 作为变量的名称,这太棒了!非常感谢。你想把它作为一个正确的答案发布,以便我可以点击它回答吗?

标签: r plot ggplot2 dataframe


【解决方案1】:

aes 进行非标准评估。它需要传递给data 参数的data.frame 的列名(不带引号)。您可以使用aes_string 将列名作为字符串传递:

aes_string(names(dataNorm)[ind])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多