天道酬勤,学无止境

Remove white space (i.e., margins) ggplot2 in R

I'm trying to plot a pie chart using GGPLOT2 in R. I want to do this in such a way as to omit the extra margin space.

What I'm doing is similar to what sharoz did in this post here except I want to include a legend.

Here is what I'm doing:

ggplot(DATA, aes(x=factor(0),fill=factor(LABELS),weight=VALUES)) +
   geom_bar(width=1) +
   coord_polar(theta='y') +
   guides(fill=guide_legend(title='LEGEND')) 

enter image description here

评论

Assuming you are talking about the extra white space above and below the figure, the easiest solution is just to tweak the size of the graphics device. Here is aspect ratio is the key. If the aspect ratio of the graphics device matches that of the plot, you get rid of a lot of the whitespace.

What I use to save the plot is ggsave, in code:

ggplot(DATA, aes(x=factor(0),fill=factor(LABELS),weight=VALUES)) +
   geom_bar(width=1) +
   coord_polar(theta='y') +
   guides(fill=guide_legend(title='LEGEND')) 
ggsave("plot.png", width = 10, height = 5)

Just play around with width and height in ggsave until you are happy with the result.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • R ggplot, remove white margins in ggsave/ggplot
    How can I remove the white margins in ggsave? My question is exactly the same as Remove white space (i.e., margins) ggplot2 in R. However, the answer there isn't ideal for me. Instead of trial and error for a fixed but unknown aspect ratio, I would like to give ggsave a height and weight and want my plot (ie top of title to bottom of x-label) to automatically expand to that configuration without white margin. How can I remove the strange white margin around my .png (plotted with r, ggplot)? gives a way to make the margin transparent, but they are still there and the plot is smaller than height
  • gpplot2水平图例元素之间的空间(Space between gpplot2 horizontal legend elements)
    问题 我有一个ggplot2图,如下所示: library(ggplot2) ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) + geom_bar() + coord_flip() + theme(legend.position = 'top') + guides(fill = guide_legend(title=NULL)) 我想在fill元素之间添加间距,如下所示: 回答1 看起来确实像theme(legend.text = element_text(margin = margin(r = 2, unit = 'in')))是完成任务的正确方法,但这根本没有做任何事情。 相反,(并且不是第一次)我回到了Microsoft Word风格的对齐攻击,即仅添加空格: ggplot(mtcars, aes(factor(cyl), fill=factor(paste(cyl, ' ')))) + geom_bar() + coord_flip() + theme(legend.position = 'top') + guides(fill = guide_legend(title=NULL)) 因为8上也有空格,所以它有点偏离中心,但是如果将它们粘贴到以前的标签上,则可以根据需要微调它们。 对于造成平面设计师的噩梦,我们深表歉意。
  • 图标作为 R 中的 x 轴标签 - ggplot2(Icons as x-axis labels in R - ggplot2)
    问题 (这是问题图标作为 R 中的 x 轴标签的扩展。它寻找ggplot解决方案而不是绘图解决方案。由于ggplot基于网格而plot基于图形,因此方法非常不同) 我想绘制这样的图(来自本文),其中图标(在本例中为小图)用作刻度标签。 原始问题的公认答案是: library(igraph) npoints <- 15 y <- rexp(npoints) x <- seq(npoints) # reserve some extra space on bottom margin (outer margin) par(oma=c(3,0,0,0)) plot(y, xlab=NA, xaxt='n', pch=15, cex=2, col="red") lines(y, col='red', lwd=2) # graph numbers x = 1:npoints # add offset to first graph for centering x[1] = x[1] + 0.4 x1 = grconvertX(x=x-0.4, from = 'user', to = 'ndc') x2 = grconvertX(x=x+0.4, from = 'user', to = 'ndc') for(i in x){ print(paste(i, x1[i], x2[i], sep='; '
  • 如何删除.png周围奇怪的白色边距(用r,ggplot绘制)?(How can I remove the strange white margin around my .png (plotted with r, ggplot)?)
    问题 我将ggplot的图另存为.png。 背景必须是黑色的,但始终有一个小的白色边距(仅顶部,左侧,不右侧)。 如何删除该保证金? 谢谢! 这是我的代码 library(ggplot2) require(grid) dat <- data.frame("xvar"=runif(500, 1, 10), "yvar"=runif(500, 1, 10)) n <- 1 for(i in 1:n){ png(file=paste("green", i, ".png", sep=""), width=400, height=400) x <- sample(500, 50) i <- ggplot(data=dat[x,], aes(x=xvar, y=yvar))+ geom_point(col="green", size=3,shape=15)+ theme(panel.background=element_rect(fill="black"), panel.grid.minor=element_blank(), panel.grid.major=element_blank(), axis.text.x=element_blank(), axis.text.y= element_blank(), axis.title.x=element_blank(), axis.title.y
  • 有没有办法改变ggplot2中图例项之间的间距?(Is there a way to change the spacing between legend items in ggplot2?)
    问题 有没有办法改变ggplot2中图例项之间的间距? 我目前有 legend.position ="top" 它会自动生成一个水平图例。 但是,这些项目的间距非常接近,我想知道如何将它们分开得更远。 回答1 2018年7月发布的ggplot2 v3.0.0具有可修改legend.spacing.x , legend.spacing.y和legend.text工作选项。 示例:增加图例键之间的水平间距 library(ggplot2) ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + geom_bar() + coord_flip() + scale_fill_brewer("Cyl", palette = "Dark2") + theme_minimal(base_size = 14) + theme(legend.position = 'top', legend.spacing.x = unit(1.0, 'cm')) 注意:如果只想扩大图例文本右侧的间距,请使用stringr :: str_pad() 示例:将图例键标签移至底部并增加垂直间距 ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + geom_bar() + coord_flip() + scale
  • How can I remove the strange white margin around my .png (plotted with r, ggplot)?
    I save plots with ggplot as .png. The background has to be black, but there is allways a small white margin (only top, down an left; not right). How can I remove this margin? Thank you! Here is my Code library(ggplot2) require(grid) dat <- data.frame("xvar"=runif(500, 1, 10), "yvar"=runif(500, 1, 10)) n <- 1 for(i in 1:n){ png(file=paste("green", i, ".png", sep=""), width=400, height=400) x <- sample(500, 50) i <- ggplot(data=dat[x,], aes(x=xvar, y=yvar))+ geom_point(col="green", size=3,shape=15)+ theme(panel.background=element_rect(fill="black"), panel.grid.minor=element_blank(), panel.grid
  • 如何设置使用ggplot2映射栅格(How to set use ggplot2 to map a raster)
    问题 我想使用与下面的工作室相似的R Studio进行绘制(在Arc Map中创建) 我尝试了以下代码: # data processing library(ggplot2) # spatial library(raster) library(rasterVis) library(rgdal) # test <- raster(paste(datafold,'oregon_masked_tmean_2013_12.tif',sep="")) # read the temperature raster OR<-readOGR(dsn=ORpath, layer="Oregon_10N") # read the Oregon state boundary shapefile gplot(test) + geom_tile(aes(fill=factor(value),alpha=0.8)) + geom_polygon(data=OR, aes(x=long, y=lat, group=group), fill=NA,color="grey50", size=1)+ coord_equal() 该代码的输出如下所示: 需要注意的几件事。 首先,R版本缺少分水岭的shapefile。 那样就好。 其次,R图中较深的灰色背景是“无数据”值。 在Arc中,不显示它们,但是在R中
  • R setting space between graphs on a multiplot
    Following a previous R post Specifying ggplot2 panel width, I have been able to produce this plot: with this code. You can find the output of dput(datos) at http://ubuntuone.com/0Nlb97mOeDhSbFrbFKCeEG Now my question is how can I remove/reduce the white space between the graphs. I have found examples with ggExtra package, ggplot and facet, multiplots with options as plot.margin or panel.margin but couldn't find how to apply to my case. Thanks for your help. EDIT: I have just noticed that plots have not the same width. It is needed they have the same width so they can share x axis labels from
  • r中选定区域的双向密度图与单向密度图的组合(two-way density plot combined with one way density plot with selected regions in r)
    问题 # data set.seed (123) xvar <- c(rnorm (1000, 50, 30), rnorm (1000, 40, 10), rnorm (1000, 70, 10)) yvar <- xvar + rnorm (length (xvar), 0, 20) myd <- data.frame (xvar, yvar) # density plot for xvar upperp = 80 # upper cutoff lowerp = 30 # lower cutoff x <- myd$xvar plot(density(x)) dens <- density(x) x11 <- min(which(dens$x <= lowerp)) x12 <- max(which(dens$x <= lowerp)) x21 <- min(which(dens$x > upperp)) x22 <- max(which(dens$x > upperp)) with(dens, polygon(x = c(x[c(x11, x11:x12, x12)]), y = c(0, y[x11:x12], 0), col = "green")) with(dens, polygon(x = c(x[c(x21, x21:x22, x22)]), y = c(0, y
  • Set the height of the graphs y-axis in grid.arrange, but not of the entire plot area
    When using grid arrange I encountered the following problem : I want all my panels (a,b,c) to have the same size, but as I have removed the labels and tickmarks from panel a and b (to have only a single x-axis) the size of the graphs a and b is bigger and equals the size of graph c + space for the lable and tick-marks of c. I cannot make use of ggplot2::facet_grid either, since I want to specify the y-axis limits independently (eg. of a until 40 and of b and c until 15). Below you can find the working example used to generate this plot, based upon this post to align the plots vertically, but I
  • ggplot2中具有边际直方图的散点图(Scatterplot with marginal histograms in ggplot2)
    问题 是否有一种方法可以像下面的ggplot2中的示例一样使用边际直方图创建散点图? 在Matlab中,它是scatterhist()函数,并且也存在R的等效项。 但是,我还没有在ggplot2上看到它。 我通过创建单个图形开始尝试,但是不知道如何正确排列它们。 require(ggplot2) x<-rnorm(300) y<-rt(300,df=2) xy<-data.frame(x,y) xhist <- qplot(x, geom="histogram") + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 5/16, axis.text.y = theme_blank(), axis.title.y=theme_blank(), background.colour="white") yhist <- qplot(y, geom="histogram") + coord_flip() + opts(background.fill = "white", background.color ="black") yhist <-
  • ggplot2和gridExtra:完全删除facet_grid中的条带-不仅不可见(ggplot2 and gridExtra: completely remove strip in facet_grid - not just invisible)
    问题 我有两个图形,它们以下列方式放置在另一个之上: library(ggplot2) library(gridExtra) p1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p2 <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p2 <- p2 + facet_grid(cyl ~ .) grid.arrange(p1, p2, ncol=1) 为此,我需要顶部图和底部图的x轴对齐,但是由于左侧的条带,多面图比顶部图更窄。 我可以使用以下方法使该条不可见: theme(strip.text.y = element_blank()) theme(strip.background = element_blank()) 但是,这并不能消除带材占用的空间。 因此,我要么需要一种方法来完全摆脱该条带,要么有一种方法可以将我的多面图拆分成单独的图,但又要在它们之间共享相同的y轴标签。 在我的图表中,我有两个不太高的多面面板,并且没有足够的空间容纳每个面板的y轴大小。 有什么建议么? 回答1 我的解决方案是找到条带的宽度,然后将两个图的边距设置为零,但将没有条带的那一条的边距缩小一些(条带的宽度),使它们看起来大小相同。 通过反复试验,该条带似乎宽约0.5行(但我想您可以通过编程来解决此问题)。
  • 在R中使用ggplot时,如何删除绘图区域周围的边距?(When using ggplot in R, how do I remove margins surrounding the plot area?)
    问题 我正在尝试生成一些分形,并且对R中的ggplot有一个关于边距的问题。我正在使用以下代码来生成分形。 library(ggplot2) library(grid) max_iter=25 cl=colours() step=seq(-2,0.8,by=0.005) points=array(0,dim=c(length(step)^2,3)) t=0 for(a in step) { for(b in step+0.6) { x=0;y=0;n=0;dist=0 while(n<max_iter & dist<4) { n=n+1 newx=a+x^2-y^2 newy=b+2*x*y dist=newx^2+newy^2 x=newx;y=newy } if(dist<4) { color=24 # black } else { color=n*floor(length(cl)/max_iter) } t=t+1 points[t,]=c(a,b,color) } } df=as.data.frame(points) ggplot(data=df, aes(V1, V2, color=cl[V3]))+ geom_point() + theme(panel.background=element_blank(), panel.grid.major=element_blank(
  • 在grid.arrange中设置图形y轴的高度,但不设置整个绘图区域的高度(Set the height of the graphs y-axis in grid.arrange, but not of the entire plot area)
    问题 使用网格排列时,我遇到以下问题: 我希望所有面板(a,b,c)具有相同的大小,但是因为我从面板a和b(仅具有一个x轴)中删除了标签和刻度线,所以图表a和b的大小大于并等于图形c的大小+ c的标记和刻度线的空间。 我也不能使用ggplot2::facet_grid ,因为我想独立指定y轴限制(例如a直到40,b和c直到15)。 在下面您可以找到用于生成此图的工作示例,该示例基于此帖子以垂直对齐图,但是对于如何分别确保每个图的高度相同,我一无所知。 欢迎任何指针。 library(ggplot2) library(gridExtra) # generate data data <- data.frame(values=c(runif(20,0,40),runif(40,0,15)),product=c(rep("a",20),rep("b",20),rep("c",20)),treat=c("e","f","g","h","i"),time=c(0,6,24,48)) my_labeller <- function(var, value){ value <- as.character(value) value <- c("a","b","c") return(value) } #subset data data_a <- data[1:20,] data_b <- data[21
  • How to remove the margin between plot region and panel in ggplot2?
    I am creating some maps and want to remove all margins between the plot region and panel border. This is the minimal example to reproduce my question library(ggplot2) library(grid) df <- expand.grid(list(x = seq(1, 10), y = seq(1, 10), z = seq(1, 2))) p <- ggplot(df) + geom_tile(aes(x, y)) + facet_wrap(~z) p <- p + theme_minimal() + xlab('') + ylab('') p <- p + theme(axis.text = element_blank(), panel.grid = element_blank(), axis.ticks = element_blank(), panel.border = element_rect(colour = 'black', fill = 'transparent'), panel.margin = unit(0, 'mm')) p + ylim(2, 6) + xlim(2, 6) This is the
  • 如何删除ggplot2中绘图区域和面板之间的边距?(How to remove the margin between plot region and panel in ggplot2?)
    问题 我正在创建一些地图,并希望删除绘图区域和面板边框之间的所有边距。 这是重现我的问题的最小示例 library(ggplot2) library(grid) df <- expand.grid(list(x = seq(1, 10), y = seq(1, 10), z = seq(1, 2))) p <- ggplot(df) + geom_tile(aes(x, y)) + facet_wrap(~z) p <- p + theme_minimal() + xlab('') + ylab('') p <- p + theme(axis.text = element_blank(), panel.grid = element_blank(), axis.ticks = element_blank(), panel.border = element_rect(colour = 'black', fill = 'transparent'), panel.margin = unit(0, 'mm')) p + ylim(2, 6) + xlim(2, 6) 这是我的代码的结果。 如何删除上图中的所有白色区域? 感谢您的任何建议。 回答1 (好的,这是我的评论。) 只需将以下内容添加到绘图中: + scale_y_continuous(expand = c(0,0)) + scale
  • 使用grid和ggplot2使用R创建连接图(using grid and ggplot2 to create join plots using R)
    问题 我想知道该怎么做才能修复网格图。 这些图以阵列形式排列,以使一行中的所有图具有相同的Y轴变量,而一列中的所有图具有相同的X轴变量。 当在网格中连接在一起时,将创建多图。 我禁用大多数图上的标签,但外面的标签除外,因为内部的标签具有相同的变量和比例。 但是,由于外部图具有标签和轴值,因此它们导致的尺寸与其他图不同。 我当时正在考虑为变量名和轴范围值向网格中再添加2列和行...然后仅在相应的网格空间上绘制变量名称,在另一个网格空间上绘制轴值,因此仅绘制指向剩余空间并获得相等的大小。 编辑1:感谢rcs将我指向align.plot 编辑align.plot以接受空值(用于不需要轴上的标题/文本时) 现在我离目标越来越近了,但是由于标签的原因,第一个columun图的宽度仍然小于其余的宽度。 示例代码: grid_test <- function () { dsmall <- diamonds[sample(nrow(diamonds), 100), ] #-----/align function----- align.plots <- function(gl, ...){ # Obtained from http://groups.google.com/group/ggplot2/browse_thread/thread/1b859d6b4b441c90 # Adopted
  • Icons as x-axis labels in R - ggplot2
    (This is an extension to the question Icons as x-axis labels in R. It looks for a ggplot solution instead of a plot one. Since ggplot is based on grid and plot is based on graphics, the approach is very different) I would like to plot something like this (from this paper) where icons, in this case small graphs, are used as tick labels. The accepted answer from the original question is: library(igraph) npoints <- 15 y <- rexp(npoints) x <- seq(npoints) # reserve some extra space on bottom margin (outer margin) par(oma=c(3,0,0,0)) plot(y, xlab=NA, xaxt='n', pch=15, cex=2, col="red") lines(y, col
  • 将x轴放在ggplot2图表的顶部(Putting x-axis at top of ggplot2 chart)
    问题 我觉得这应该是显而易见的...我要做的就是从图形底部移除x轴并将其添加到顶部。 这是一个可重现的示例。 数据加代码以制作下图: library(reshape2) library(ggplot2) data(mtcars) dat <- with(mtcars, data.frame(mpg, cyl, disp, hp, wt, gear)) cor.matrix <- round(cor(dat, use = "pairwise.complete.obs", method = "spearman"), digits = 2) diag(cor.matrix)<-NA cor.dat <- melt(cor.matrix) cor.dat <- data.frame(cor.dat) cor.dat <- cor.dat[complete.cases(cor.dat),] ggplot(cor.dat, aes(Var2, Var1, fill = value)) + geom_tile(colour="gray90", size=1.5, stat="identity") + geom_text(data=cor.dat, aes(Var2, Var1, label = value), color="black", size=rel(4.5)) + scale_fill
  • ggplot2:使用gtable将标签条移动到facet_grid的面板顶部(ggplot2: Using gtable to move strip labels to top of panel for facet_grid)
    问题 我正在使用facet_grid创建图形,以在y轴上进行分类变量。 我决定不使用facet_wrap因为我需要space = 'free'和labeller = label_parsed 。 我的标签很长,右边有一个图例,因此我想将标签从面板的右侧移动到面板的顶部。 这是显示我陷入困境的示例。 library(ggplot2) library(gtable) mt <- ggplot(mpg, aes(x = cty, y = model)) + geom_point() + facet_grid(manufacturer ~ ., scales = 'free', space = 'free') + theme_minimal() + theme(panel.margin = unit(0.5, 'lines'), strip.text.y = element_text(angle = 0)) 现在,我想将带状文本从每个面板的右侧移到每个面板的顶部。 我可以存储带状标签的杂项并将其从图中删除: grob <- ggplotGrob(mt) strips.y <- gtable_filter(grob, 'strip-right') grob2 <- grob[,-5] 但是,现在我在进行rbind时陷入困境-将grobs放回原处,以便标签移到面板的顶部。