在同一y轴上绘制多个条形图,但每个条形图在ggplot2中的单独x轴上绘制计数数据

时间:2017-11-16 01:00:09

标签: r ggplot2 bar-chart

我有一些计数变量,我想在同一个y轴上制作条形图,但我没有分组变量。类似下面的情节

enter image description here

B <- 25

iter_M1  
[1] 5 13 14 11  7  8 10 14 10  5  7 13 10 12  4  5  9  6  5 12  8  8  7 11  9 

max_M1 <- max(iter_M1)

count_M1 <- integer(max_M1) 
for(i in 1:max_M1)
 {  
    for(j in 1:B)
     {       
        if(iter_M1[j] == i)  
        count_M1[i] = count_M1[i] +1      
     }  
 }  

 count_M1 
 [1] 0 0 0 1 4 1 3 3 2 3 2 2 2 2  

 df <- data.frame(x = 1:max_M1, y = count_M1)  
 p_M1 <-ggplot(data=df, aes(x=x, y=y)) +  geom_bar(stat="identity")  
 p_M1

这会产生这样的情节

enter image description here

和另一个类似的变量

iter_M2  
[1] 3 1 3 2 6 3 4 4 3 7 4 2 2 3 4 3 4 4 1 3 7 3 2 4 2

max_M2 <- max( iter_M2) 
count_M2  <- integer(max_M2) 
for(i in 1:max_M2)
{   
 for(j in 1:B)
 {          
 if(iter_M2[j] == i)    
 count_M2[i] = count_M2[i] +1   
 }
} 

count_M2
[1] 2 5 8 7 0 1 2 df1 <- data.frame(x1 = 1:max_M2, y1 = count_M2)

p_M2 <-ggplot(data=df1, aes(x=x1, y=y1)) +  
geom_bar(stat="identity") p_M2

导致第二个图为

enter image description here

和类似的变量......如何并排绘制这些数据。此外,我当前生成数据的方式,所有x轴都没有共同的y轴。是否有一些建议以其他格式生成这样的情节或数据集以获得所需的情节。

1 个答案:

答案 0 :(得分:0)

正如评论中所建议的那样,制作一个因子(类)是最简单的方法,让你能够面对情节。

但你似乎只是希望拥有相同的y轴。这可以通过比例限制来实现。例如,生成具有基于Gatherer的限制的向量,然后在图中使用此向量。

max