Ошибка в plot new figure margins too large

I’m new to R but I’ve made numerous correlation plots with smaller data sets. However, when I try to plot a large dataset (2gb+), I can produce the plot just fine, but the legend doesn’t show up. Any advice? or alternatives?

library(gplots)
r.cor <- cor(r)
layout(matrix(c(1,1,1,1,1,1,1,1,2,2), 5, 2, byrow = TRUE))
par(oma=c(5,7,1,1))
cx <- rev(colorpanel(25,"yellow","black","blue"))
leg <- seq(min(r.cor,na.rm=T),max(r.cor,na.rm=T),length=10)
image(r.cor,main="Correlation plot Normal/Tumor data",axes=F,col=cx)
axis(1, at=seq(0,1,length=ncol(r.cor)), labels=dimnames(r.cor)[[2]], 
    cex.axis=0.9,las=2)
axis(2,at=seq(0,1,length=ncol(r.cor)), labels=dimnames(r.cor)[[2]],
     cex.axis=0.9,las=2)
image(as.matrix(leg),col=cx,axes=T)     

Error in plot.new() : figure margins too large

tmp <- round(leg,2)
axis(1,at=seq(0,1,length=length(leg)), labels=tmp,cex.axis=1)

In this article, we will discuss how to fix the “figure margins too large” error in plot.new() function of the R programming language.

The error that one may face in R is:

Error in plot.new() : figure margins too large

The R compiler produces this error when the plot panel of Rstudio is small for the dimensions of the plot that we are trying to create.

When this error might occur:

Consider that want to create a plot using the plot() function in R. The syntax of this function is given below:

Syntax:

plot(start : end)

Parameters:

  • start: The starting point ( 1 for (x, y) = (1, 1) etc)
  • end: The ending point ( 5 for (x, y) = (5, 5) etc)

Return Type:

Draws dots in a sequence on both x and y axis

Example:

R

Output:

The R compiler produces the error (you can see the panel window is quite small at the right).

How to fix this error:

There are three ways to fix this error in R:

Method 1: Increasing the size of the panel

One way is to increase the panel size so that it can accommodate the plot across its dimensions:

R

Output:

Method  2: Using par() function

The par() function in R is used to set the margins of a plot. This function has the following syntax:

Syntax:

 par(mfrow)

Parameter:

mfrow:  It represents a vector with row and column values for the grid

By default a plot has the following margins:

  • Top: 4.1 and Bottom: 5.1
  • Left: 4.1 and Right: 2.1

We need to explicitly set the margins of the plot as:

R

par(mar = c(1, 1, 1, 1))

plot(1 : 40)

Output:

The plot was projected easily in the panel window because we reduced the margin to accommodate the created plot.

Method 3: Turn off the plotting device

If neither of the previous methods was able to fix the error then you can shut down the current plotting device by the following command:

R

Output:

Last Updated :
28 Mar, 2022

Like Article

Save Article

  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Одна ошибка, с которой вы можете столкнуться в R:

Error in plot.new() : figure margins too large

Эта ошибка возникает, когда панель графика в RStudio слишком мала для полей графика, который вы пытаетесь создать.

В этом руководстве рассказывается, как именно исправить эту ошибку.

Как воспроизвести ошибку

Предположим, мы пытаемся создать следующий график в R:

#attempt to create scatterplot
plot(1:30)

Получаем следующую ошибку:

Error in plot.new() : figure margins too large

Мы получаем эту ошибку, потому что панель графика очень мала (обратите внимание, насколько мала панель в нижнем левом углу), и поэтому поля графика не могут отображаться на такой маленькой панели.

Метод № 1: исправить ошибку, увеличив размер панели графика

Самый простой способ исправить эту ошибку — увеличить размер панели построения в RStudio:

plot(1:30)

Обратите внимание, что мы не получаем сообщение об ошибке, потому что панель построения графика была достаточно большой, чтобы отобразить поля графика.

Способ № 2: исправить ошибку с помощью функции par()

По умолчанию функция par() в R устанавливает поля графика следующим образом:

  • Нижнее поле: 5,1
  • Левое поле: 4,1
  • Верхнее поле: 4,1
  • Правое поле: 2,1

Однако мы можем использовать следующий синтаксис, чтобы уменьшить поля:

#adjust plot margins
par(mar = c(1, 1, 1, 1))

#create scatterplot
plot(1:30) 

График успешно отображается на панели построения в RStudio, потому что мы сильно уменьшили поля.

Метод № 3: исправить ошибку, выключив текущее устройство для рисования

Если ни один из предыдущих методов не может исправить ошибку, вам может потребоваться использовать следующий код для выключения текущего устройства печати:

dev. off ()

В некоторых случаях это может исправить ошибку, поскольку удаляет все настройки графика, которые использовались для предыдущих графиков и могут мешать вашему текущему графику.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные функции построения графиков в R:

Как использовать функцию par() в R
Как накладывать графики в R
Как сохранить несколько графиков в PDF в R

Table of Contents
Hide
  1. What is error in plot.new() : figure margins too large?
  2. How to fix error in plot.new() : figure margins too large?
    1. Solution 1 – Increase the plot panel size
    2. Solution 2 – Use the par() function
    3. Solution 3- Using dev.off() method

The error in plot.new() : figure margins too large occur if the plot panel in the RStudio is too small for the margins you are trying to create.

In this tutorial, we will learn how to resolve error in plot.new() : figure margins too large issue using several ways

Let us create a simple plot to demonstrate this issue.

# Draw a simple scatter plot
plot(1:40)

Output

Error in plot.new() : figure margins too large

When we run the above code in our R Studio, we will be getting an error in plot.new() : figure margins too large.

Image 2

Method  2: Using par() function

The par() function in R is used to set the margins of a plot. This function has the following syntax:

Syntax:

 par(mfrow)

Parameter:

mfrow:  It represents a vector with row and column values for the grid

By default a plot has the following margins:

  • Top: 4.1 and Bottom: 5.1
  • Left: 4.1 and Right: 2.1

We need to explicitly set the margins of the plot as:

R

par(mar = c(1, 1, 1, 1))

plot(1 : 40)

Output:

The plot was projected easily in the panel window because we reduced the margin to accommodate the created plot.

Method 3: Turn off the plotting device

If neither of the previous methods was able to fix the error then you can shut down the current plotting device by the following command:

R

Output:

Last Updated :
28 Mar, 2022

Like Article

Save Article

  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Одна ошибка, с которой вы можете столкнуться в R:

Error in plot.new() : figure margins too large

Эта ошибка возникает, когда панель графика в RStudio слишком мала для полей графика, который вы пытаетесь создать.

В этом руководстве рассказывается, как именно исправить эту ошибку.

Как воспроизвести ошибку

Предположим, мы пытаемся создать следующий график в R:

#attempt to create scatterplot
plot(1:30)

Получаем следующую ошибку:

Error in plot.new() : figure margins too large

Мы получаем эту ошибку, потому что панель графика очень мала (обратите внимание, насколько мала панель в нижнем левом углу), и поэтому поля графика не могут отображаться на такой маленькой панели.

Метод № 1: исправить ошибку, увеличив размер панели графика

Самый простой способ исправить эту ошибку — увеличить размер панели построения в RStudio:

plot(1:30)

Обратите внимание, что мы не получаем сообщение об ошибке, потому что панель построения графика была достаточно большой, чтобы отобразить поля графика.

Способ № 2: исправить ошибку с помощью функции par()

По умолчанию функция par() в R устанавливает поля графика следующим образом:

  • Нижнее поле: 5,1
  • Левое поле: 4,1
  • Верхнее поле: 4,1
  • Правое поле: 2,1

Однако мы можем использовать следующий синтаксис, чтобы уменьшить поля:

#adjust plot margins
par(mar = c(1, 1, 1, 1))

#create scatterplot
plot(1:30) 

График успешно отображается на панели построения в RStudio, потому что мы сильно уменьшили поля.

Метод № 3: исправить ошибку, выключив текущее устройство для рисования

Если ни один из предыдущих методов не может исправить ошибку, вам может потребоваться использовать следующий код для выключения текущего устройства печати:

dev. off ()

В некоторых случаях это может исправить ошибку, поскольку удаляет все настройки графика, которые использовались для предыдущих графиков и могут мешать вашему текущему графику.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные функции построения графиков в R:

Как использовать функцию par() в R
Как накладывать графики в R
Как сохранить несколько графиков в PDF в R

Table of Contents
Hide
  1. What is error in plot.new() : figure margins too large?
  2. How to fix error in plot.new() : figure margins too large?
    1. Solution 1 – Increase the plot panel size
    2. Solution 2 – Use the par() function
    3. Solution 3- Using dev.off() method

The error in plot.new() : figure margins too large occur if the plot panel in the RStudio is too small for the margins you are trying to create.

In this tutorial, we will learn how to resolve error in plot.new() : figure margins too large issue using several ways

Let us create a simple plot to demonstrate this issue.

# Draw a simple scatter plot
plot(1:40)

Output

Error in plot.new() : figure margins too large

When we run the above code in our R Studio, we will be getting an error in plot.new() : figure margins too large.

Plot Panel

If you observe the plot window in the screenshot, it is too small to plot the figure in the given space.

How to fix error in plot.new() : figure margins too large?

There are several ways to fix the issue. Let us look at each of these solutions in detail.

Solution 1 – Increase the plot panel size

The quickest and easiest way to resolve the issue is to increase the size of the plot panel in RStudio.

Since it is not a code issue and has something to do with the plot panel size, after increasing the panel size, you can run the code once again and see that issue is fixed.

Error In Plot.new() : Figure Margins Too Large

RStudio Plot Panel

Solution 2 – Use the par() function

The par() method sets the margin for the plots as shown below.

Syntax –

par(mar=c(5.1, 4.1, 4.1, 2.1), mgp=c(3, 1, 0), las=0)

Parameters – 

  • mar – A numeric vector of length 4, which sets the margin sizes in the following order: bottom, left, top, and right. The default is c(5.1, 4.1, 4.1, 2.1).

These are the default values; however, we can tweak these values to make the margin much smaller so the plot can fit properly.

#adjust plot margins
par(mar = c(1, 1, 1, 1))

# Draw a simple scatter plot
plot(1:40)

Solution 3- Using dev.off() method

The dev.off() method will remove any plot settings used earlier and create a graphics device with default settings.

Alternatively, you can also execute the below command in the R Console to shut down all open graphics devices.

graphics.off()

The broomstick icon in the plot panel will help you to Clear All Plots in the Plots tab, and you can run the code once again.

Image 4

Broomstick Icon RStudio to Clear all Plots

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

In this tutorial, I’ll explain how to handle the error message “Error in plot.new() : figure margins too large” in the R programming language.

The tutorial will contain this:

Here’s how to do it!

Example 1: Increasing Plot Window in RStudio

First, let’s reproduce the error message “Error in plot.new() : figure margins too large” in R. Let’s assume that we want to draw the following plot:

plot(1:10)                      # Trying to create plot in RStudio

Then it might happen that the following error message appears in the RStudio console:

r graph figure 1 error new figure margins too large r

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

In this tutorial, I’ll explain how to handle the error message “Error in plot.new() : figure margins too large” in the R programming language.

The tutorial will contain this:

Here’s how to do it!

Example 1: Increasing Plot Window in RStudio

First, let’s reproduce the error message “Error in plot.new() : figure margins too large” in R. Let’s assume that we want to draw the following plot:

plot(1:10)                      # Trying to create plot in RStudio

Then it might happen that the following error message appears in the RStudio console:

r graph figure 1 error new figure margins too large r

A very common solution for the error message “Error in plot.new() : figure margins too large” is to increase the plotting panel in RStudio. Let’s do this and then we are running the same plot() function code again:

plot(1:10)                      # Creating plot in RStudio

r graph figure 2 error new figure margins too large r

The error is not occurring anymore. Nice!

However, to increase the plot window in RStudio is not always solving the error message “Error in plot.new() : figure margins too large”. For that reason, I’ll show to other possible fixes in the following examples…

Example 2: Shutting Down Current Plotting Device

It might happen that we have specified some R options for a previous plot that are now causing the error message for our new plot. The following R syntax illustrates how to reset the plotting options for our new plot using the dev.off() function:

dev.off()                       # Shut down current plotting device

After running the dev.off function, the error might be solved.

Example 3: Decreasing Plot Area Margins

Another possible reason for the error message “Error in plot.new() : figure margins too large” are too large area margins around our plot. You can decrease those area margins using the par function and the mar argument:

par(mar = c(1, 1, 1, 1))        # Changing area margins

Try to run the plotting code again. Eventually it works now!

The previously shown fixes do usually solve the error message “Error in plot.new() : figure margins too large”. However, in case you still have problems you may have a look at this thread on Stack Overflow.

Note that the previous examples have illustrated some error solutions based on a scatterplot. However, we can apply the same R syntax to other types of plots such as boxplots, barcharts, histograms, density plots, and so on…

Video, Further Resources & Summary

Do you need more explanations on the R code of this tutorial? Then I can recommend to watch the following video of my YouTube channel. In the video, I show the R syntax of this tutorial.

Furthermore, you might want to read some of the other tutorials on this website. You can find some related tutorials about error messages in R below:

  • Drawing Plots in R
  • All R Programming Examples

In summary: In this tutorial you learned how to fix the issue “Error in plot.new() : figure margins too large” in the R programming language. Let me know in the comments section below, if you have further comments or questions.

Понравилась статья? Поделить с друзьями:
  • Ошибка в ini файле парус
  • Ошибка в phpmyadmin index of
  • Ошибка в includes file inc
  • Ошибка в php знаки вопроса
  • Ошибка в imazing при скачивании сбербанк онлайн