简体   繁体   中英

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!

Here's a hacky way: make a dummy data frame of the minimum and maximum values at each of the factor levels, then use it to draw bars filling up that space. Setting width = 1 with polar coordinates would be used to make a pie chart—here it does the same thing, but you aren't distinguishing between pie wedges.

You probably don't actually want to work with the exact maximum of x ; it would make sense to add some amount of padding as you see fit, but this should be a start.

If you were working with data that had a minimum at 0 or somewhere above it, you wouldn't need to repeat the data like I did—that was the best way I could figure out to get bars stacking from 0 to the maximum, which is positive, and from 0 to the minimum, which is negative. geom_rect initially seemed like it made more sense, but I couldn't get it to stretch all the way around to close the circle.

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")

Also worth noting that ggforce has a geom_circle , but I don't know how it would work with polar coordinates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM