如何使用barplot函数在R中的绘图窗口中使barplot条形图具有相同的大小 [英] how to make barplot bars same size in plot window in R using barplot function

查看:74
本文介绍了如何使用barplot函数在R中的绘图窗口中使barplot条形图具有相同的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一窗口中绘制3个图.每个都有不同数量的条形图.我怎么能使它们大小相同并且彼此靠近(彼此相同的距离),而不必在较小的条形图中进行NA定位呢?下面的示例代码.我确实要指出,我的真实数据将绘制来自dataframes $ columns的数字,而不是如下所示的数字向量.我敢肯定有一种神奇的方法可以做到这一点,但似乎无法在网上找到有用的信息.谢谢

I would like to plot 3 plots in the same window. Each will have a different amount of bar plots. How could I make them all the same size and close together (same distance from each other) without doing NAs in the smaller barplots. example code below. I do want to point out my real data will be plotting numbers from dataframes$columns not a vector of numbers as shown below. I am sure there is magic way to do this but cant seem to find helpful info on the net. thanks

pdf(file="PATH".pdf");
par(mfrow=c(1,3));
par(mar=c(9,6,4,2)+0.1);
barcenter1<- barplot(c(1,2,3,4,5));
mtext("Average Emergent", side=2, line=4);
par(mar=c(9,2,4,2)+0.1);
barcenter2<- barplot(c(1,2,3));
par(mar=c(9,2,4,2)+0.1);
barcenter3<- barplot(c(1,2,3,4,5,6,7));

还是有一种方法可以代替使用par(mfrow ....)来创建绘图窗口,我们可以将条形图上的中心数据分组到单个图上,并且在条形图之间留有空白吗?这样所有东西都隔开并且看起来一样吗?

Or would there be a way instead of using the par(mfrow....) to make a plot window, could we group the barcenter data on a single plot with an empty space between the bars? This way everything is spaced and looks the same?

推荐答案

使用参数 xlim width :

par(mfrow = c(1, 3))
    par(mar = c(9, 6, 4, 2) + 0.1)
    barcenter1 <- barplot(c(1, 2, 3, 4, 5), xlim = c(0, 1), width = 0.1)
    mtext("Average Emergent", side = 2, line = 4)
    par(mar = c(9, 2, 4, 2) + 0.1)
    barcenter2 <- barplot(c(1, 2, 3), xlim = c(0, 1), width = 0.1)
    par(mar = c(9, 2, 4, 2) + 0.1)
    barcenter1 <- barplot(c(1, 2, 3, 4, 5, 6, 7), xlim = c(0, 1), width = 0.1)

引入零:

df <- data.frame(barcenter1 = c(1, 2, 3, 4, 5, 0, 0), 
                 barcenter2 = c(1, 2, 3, 0, 0, 0, 0), 
                 barcenter3 = c(1, 2, 3, 4, 5, 6, 7))
barplot(as.matrix(df), beside = TRUE)

使用 ggplot2 ,您可以获得以下内容:

With ggplot2 you can get something like this:

df <- data.frame(x=c(1, 2, 3, 4, 5,1, 2, 3,1, 2, 3, 4, 5, 6, 7),
y=c(rep("bar1",5), rep("bar2",3),rep("bar3",7)))
library(ggplot2)
ggplot(data=df, aes(x = x, y = x)) +
  geom_bar(stat = "identity")+
  facet_grid(~ y)

对于您在第二条评论中提到的选项,您需要:

For the option you mentioned in your second comment you would need:

x <- c(1, 2, 3, 4, 5, NA, 1, 2, 3, NA, 1, 2, 3, 4, 5, 6, 7)
barplot(x)

这篇关于如何使用barplot函数在R中的绘图窗口中使barplot条形图具有相同的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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