- R Graphs Cookbook Second Edition
- Jaynal Abedin Hrishi V. Mittal
- 357字
- 2021-08-05 17:30:31
Setting plot background colors
The default background color of all plots in R is white, which is usually the best choice as it is least distracting for data analysis. However, sometimes, we might wish to use another color. We will see how to set background colors in this recipe.
Getting ready
All you need to try out in this recipe is to run R and type the recipe in the command prompt. You can also choose to save the recipe as a script so that you can use it again later on.
How to do it...
To set the plot background color to gray, we use the bg
argument in the par()
command:
par(bg="gray") plot(rnorm(100))

How it works...
The bg
argument of the par()
command sets the background color for the entire plotting area, including the margins for any subsequent plots on the same device. Until the plotting device is closed or a new device is initiated, the background color stays the same.
There's more...
It is more likely that we want to set the background color only for the plot region (within the axes) but there is no straightforward way to do this in R. We must draw a rectangle of the desired color in the background and then create our graph on top of it:
plot(rnorm(1000),type="n") x<-par("usr") rect(x[1],x[3],x[2],x[4],col="lightgray ") points(rnorm(1000))
First, we draw the plot with the type
parameter set to n
so that the plotted elements are invisible. This does not show the graph points or lines but sets the axes up, which we need for the next step.
The par("usr")
part gets us the coordinates of the plot region in a vector of form c(xleft,
xright,
ybottom,
ytop)
. We then use the rect()
function to draw a rectangle with a fill color that we wish to use for the plot background. Note that rect()
takes a set of arguments that represent the xleft
, ybottom
, xright
, and ytop
coordinates. So, we must pass the values we obtained from par("usr")
in the correct order. Then, finally, we redraw the graph with the correct type (points or lines). The redrawn graph looks like the following figure:

- 筆記本電腦使用、維護與故障排除實戰(zhàn)
- Instant uTorrent
- 深入淺出SSD:固態(tài)存儲核心技術(shù)、原理與實戰(zhàn)
- 電腦常見故障現(xiàn)場處理
- Rapid BeagleBoard Prototyping with MATLAB and Simulink
- 單片機技術(shù)及應(yīng)用
- 電腦橫機使用與維修
- 單片機原理與技能訓(xùn)練
- FPGA實戰(zhàn)訓(xùn)練精粹
- Drupal Rules How-to
- Instant Website Touch Integration
- 從企業(yè)級開發(fā)到云原生微服務(wù):Spring Boot實戰(zhàn)
- The Machine Learning Workshop
- Hands-On One-shot Learning with Python
- Nagios系統(tǒng)監(jiān)控實踐(原書第2版)