如何更改使用 ggplot2 绘制的图的背景颜色
默认情况下,ggplot2 生成带有灰色背景的图。如何更改绘图背景的颜色?
例如,由以下代码生成的图:
library(ggplot2)
myplot<-ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + geom_line()
myplot
By default, ggplot2 produces plots with a grey background. How do I change the color of the background of the plot?
For example, a plot produced by the following code:
library(ggplot2)
myplot<-ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + geom_line()
myplot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要更改面板的背景颜色,请使用以下代码:
要更改绘图的颜色(但不更改面板的颜色),您可以执行以下操作:
请参阅此处了解更多主题详细信息 图例、轴和主题的快速参考表。
To change the panel's background color, use the following code:
To change the color of the plot (but not the color of the panel), you can do:
See here for more theme details Quick reference sheet for legends, axes and themes.
为了避免弃用
opts
和theme_rect
使用:定义您自己的自定义主题,基于 theme_gray 但进行一些更改和一些添加的附加功能,包括网格线颜色/大小的控制(更多选项可用于在ggplot2.org):
使您的自定义主题成为ggplot时的默认主题将来调用,无需屏蔽:
如果要更改当前设置主题的元素:
将当前默认主题存储为对象:
请注意,
theme_pink
是一个列表,而theme_jack< /code> 是一个函数。因此,要将主题返回到 theme_jack,请使用
theme_set(theme_jack())
,而要返回 theme_pink,请使用theme_set(theme_pink)
。如果您愿意,可以在
theme_jack
的定义中将theme_gray
替换为theme_bw
。让您的自定义主题类似于theme_bw
但关闭所有网格线(x、y、主要和次要):最后一个更激进的主题在绘制 choropleths 或 ggplot 中的其他地图,基于讨论 此处但已更新以避免弃用。这里的目的是删除灰色背景以及任何其他可能分散地图注意力的功能。
To avoid deprecated
opts
andtheme_rect
use:To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):
To make your custom theme the default when ggplot is called in future, without masking:
If you want to change an element of the currently set theme:
To store the current default theme as an object:
Note that
theme_pink
is a list whereastheme_jack
was a function. So to return the theme to theme_jack usetheme_set(theme_jack())
whereas to return to theme_pink usetheme_set(theme_pink)
.You can replace
theme_gray
bytheme_bw
in the definition oftheme_jack
if you prefer. For your custom theme to resembletheme_bw
but with all gridlines (x, y, major and minor) turned off:Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.
这是一个自定义主题,可将 ggplot2 背景设为白色,并进行一系列其他更改,这些更改有利于出版物和海报。只需添加+mytheme即可。如果您想在 +mytheme 之后通过 +theme 添加或更改选项,它只会替换 +mytheme 中的选项。
Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.