Bob
Bob

Reputation: 1459

Control relative sizes of discrete scale in ggplot2

I'm trying to generate a polar violin plot with ggplot2. I'd like to control the relative size of each category (the width of each category of the factor on the x axis, which then translates to angle once I make the coordinates polar).

Is there any way to do this?

Example code:

means <- runif(n = 10, min=0.1, max=0.6)
sds <- runif(n = 10, min=0.2, max=0.4)
frame <- data.frame(
  cat = sample(1:10, size=10000, replace=TRUE), 
  value = rnorm(10000)
) %>%
  mutate(
    mn = means[cat], 
    sd = sds[cat],
    value = (value * sd) + mn,
    cat = factor(cat)
  )
frame %>%
  ggplot(aes(x = cat, y = value)) + geom_violin() +
  coord_polar()

Any help or advice is appreciated.

Alternatively (and perhaps better), I'd like to be able to make a polar coordinates chart that isn't centered. Where the angles are the same for each discrete category, but the points converge, say, 1/3 of the way from the bottom of the circle, rather than in the center of the circle.

Upvotes: 0

Views: 227

Answers (1)

camille
camille

Reputation: 16871

Based on comments, I'm redoing my previous answer. If what you want is a fan/weed leaf shape, you can add dummy data for additional cat values. In this example, I just doubled the number of levels in cat, but you could change this. Then I set the x breaks to only show the values that actually have data, but let the dummy values take up space to change the shape. Still not sure if this is what you meant but it's interesting to try.

library(tidyverse)

means <- runif(n = 10, min=0.1, max=0.6)
sds <- runif(n = 10, min=0.2, max=0.4)
frame <- data.frame(
    cat = sample(1:10, size=10000, replace=TRUE), 
    value = rnorm(10000)
) %>%
    mutate(
        mn = means[cat], 
        sd = sds[cat],
        value = (value * sd) + mn,
        cat = factor(cat)
    )
frame %>%
    mutate(cat = as.integer(cat)) %>%
    bind_rows(tibble(cat = 11:20, value = NA)) %>%
    ggplot(aes(x = as.factor(cat), y = value)) + 
    geom_violin(scale = "area") +
    coord_polar(start = -pi / 2) +
    scale_x_discrete(breaks = 1:10)
#> Warning: Removed 10 rows containing non-finite values (stat_ydensity).

Created on 2018-05-08 by the reprex package (v0.2.0).

Upvotes: 1

Related Questions