r - ggplot2 theme to color inside of polar plot
问题描述
I am using ggplot2
to make plots with polar coordinates.
I would like to set the background color inside of the circle to be a different color than the background color outside of the circle. (The reason is that I'm going to convert the plot to a raster and make the area outside the circle transparent.)
The ggplot
theme
attribute for plot.background
does what I expect. But I can't seem to find a way to make panel.background
only paint inside the plot. There's no element_circle
analog for element_rect
.
Can anyone advise?
Here's a minimally reproducible example:
data.frame(
x = rnorm(1000),
spoke = factor(sample(1:6, 1000, replace=T))
) %>%
ggplot(aes(x = spoke, fill=spoke, y = x)) +
geom_violin() +
coord_polar() +
theme(
plot.background = element_rect(fill = "darkblue"),
panel.background = element_rect(fill = "lightblue",
colour = "lightblue"))
Thanks in advance!
解决方案
这是一个 hacky 方法:在每个因子水平上制作一个包含最小值和最大值的虚拟数据框,然后用它来绘制填充该空间的条形图。使用极坐标设置width = 1
将用于制作饼图——在这里它做同样的事情,但你没有区分饼楔。
您可能实际上并不想使用 ; 的确切最大值x
。添加一些您认为合适的填充是有意义的,但这应该是一个开始。
如果您正在处理最小值为 0 或高于它的某个数据的数据,则不需要像我一样重复数据——这是我能想到的让条形图从 0 堆叠到最大值的最佳方法,这为正,从 0 到最小值为负。geom_rect
最初似乎它更有意义,但我无法让它一直伸展以关闭圆圈。
library(tidyverse)
set.seed(1234)
df <- data.frame(
x = rnorm(1000),
spoke = factor(sample(1:6, 1000, replace=T))
)
bkgnd_df <- data.frame(spoke = factor(rep(1:6, 2)),
x = c(rep(min(df$x), 6), rep(max(df$x), 6)))
bkgnd_df
#> spoke x
#> 1 1 -3.396064
#> 2 2 -3.396064
#> 3 3 -3.396064
#> 4 4 -3.396064
#> 5 5 -3.396064
#> 6 6 -3.396064
#> 7 1 3.195901
#> 8 2 3.195901
#> 9 3 3.195901
#> 10 4 3.195901
#> 11 5 3.195901
#> 12 6 3.195901
ggplot(df, aes(x = spoke, y = x)) +
geom_col(data = bkgnd_df, width = 1, fill = "skyblue") +
geom_violin(aes(fill = spoke)) +
coord_polar(theta = "x")
还值得注意的是,它ggforce
有一个geom_circle
,但我不知道它如何与极坐标一起工作。
推荐阅读
- django - Django formset is_valid 失败无法分配“u'username'”:“contact”必须是“User”实例
- python - 将 Numpy 矩阵转换为索引为元组的列表
- powershell - 如何在PowerShell中将相对路径转换为绝对路径?
- android - 如何在安卓手机浏览器中显示pdf文档?pdf 文档在我的电脑中正确显示
- ios - MKMapView - 显示可定制的网格线
- ios - 在我自己创建的 pod 中添加 Firebase 作为依赖项
- php - $exception->getTraceAsString() 第一项丢失
- python-3.x - 使用 Python 读取带有分号分隔文本的 TXT 文件
- python - Python:将 xml 文件转换为图像
- python - @pytest.mark.filterwarnings 是如何工作的?