for bar for barplots更改par(mfrow)和标题位置

问题描述 投票:0回答:2

对于报告,我将由小组汇总数据。由于版权问题,我在下面创建了一些虚拟数据(第一列是组,然后是值):

  X   A   B  C D
1   1  12   0 12 0
2   2  24   0 15 0
3   3  56   0 48 0
4   4  89   0 96 0
5   5  13   3 65 0
6   6  11  16  0 0
7   7  25  19  0 0
8   8  24  98  0 0
9   9  18 111  0 0
10 10 173 125  0 0
11 11  10  65  0 0

我想用循环为每个组(1:11)创建一个条形图:

for(i in 1:11){x<-dummyloop[i,]
  barplot(as.matrix(x), main=paste("Group", i), ylim=c(0,200))}

这是有效的,我得到了每个循环的条形图,但是它们最终在一个4中用于绘制窗口,就好像我使用了par(mfrow = c(4,4))。我需要单独的条形图。

所以我使用了par(mfrow = c(1,1)),由于某种原因修复了这个问题(我没有使用par EVER,因为我只是出口一个包含单个图形的科学报告),但是“主要”在顶部切断。

我也希望每个酒吧都是不同的颜色,所以我用过:

 for(i in 1:11){x<-dummyloop[i,]
      barplot(as.matrix(x), main=paste("Group", i), col=c(1:5), 
ylim=c(0,200))}

意识到着色向量然后只使用第一种颜色,我尝试了以下变体:

for(i in 1:11){x<-dummyloop[i,]
  barplot(as.matrix(x), main=paste("Group", i), col=c(4:10)[1:ncol(x)], 
ylim=c(0,200))}

这不是诀窍......

我好像错过了for循环中的一些关键细节,感谢您的帮助。由于这里的人们,我每天都会变得越来越好;)。

r
2个回答
1
投票

不知道,为什么那是基础情节。这是ggplot2的另一种方式。


for(i in 1:11){x<- gather(data[i,])
print(ggplot(data = x, aes(x = key, y = value, fill = cols)) +
  geom_bar(stat = "identity", show.legend = FALSE) + 
    ggtitle(paste("Group ", i)) + theme(plot.title = element_text(hjust = 0.5)) +
    ylim(0,200))  
  }

那么你的mainstill切断了吗?

然后在图的顶部扩展边距。执行:


par(mar = c(2, 2, 3 , 2)) # c(bottom, left, top, right)

在绘图之前。您可以在试验时使用dev.off()重置您的规格。


0
投票

保持基础R,您可以根据小组使用by并设置col

colors <- rainbow(length(unique(dat$X)))  # define colors, 11 in your case

by(dat, dat$X, function(x) 
  barplot(as.matrix(x), main=paste("Group", x$X), ylim=c(0, 200), col=colors[x$X]))

数据

dat <- structure(list(X = 1:11, A = c(12L, 24L, 56L, 89L, 13L, 11L, 
25L, 24L, 18L, 173L, 10L), B = c(0L, 0L, 0L, 0L, 3L, 16L, 19L, 
98L, 111L, 125L, 65L), C = c(12L, 15L, 48L, 96L, 65L, 0L, 0L, 
0L, 0L, 0L, 0L), D = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10", "11"))
© www.soinside.com 2019 - 2024. All rights reserved.