C.K.
C.K.

Reputation: 1571

Pan contours in a polar coordinate ggplot2 image?

Question

I have some polar coordinate contours fitted with GAM in R and I plotted the contours and their CIs with ggplot2.

Now I want to horizontally move the whole contours since the left part of my image is almost empty, so that I can locate the contours at the center of the image.

Minimal reproducible example

The example contour plotted via the following codes

library(tidyverse)

data <- "r,t,se,lower_ci,upper_ci
1.40423012015799,0.603135455583192,0.0187221866877187,1.36753463425006,1.44092560606592
1.44036723857092,0.821418134396285,0.00997996474172906,1.42080650767713,1.45992796946471
1.47902612026307,1.03970081320938,0.00930493034574675,1.46078845678541,1.49726378374074
1.47687949454633,1.25798349202247,0.0104734856361405,1.45635146269949,1.49740752639316
1.26551747641932,1.47626617083556,0.0107804759187055,1.24438774361866,1.28664720921998
1.0090472707541,1.69454884964866,0.0107626572995185,0.987952462447043,1.03014207906116
0.841716258389874,1.91283152846175,0.0117961574024935,0.818595789880987,0.864836726898762
0.676039993971795,2.13111420727484,0.0139063079991158,0.648783630293528,0.703296357650062
0.495249767277309,2.34939688608793,0.0175845237050921,0.460784100815329,0.52971543373929"

df <- read_csv(I(data))

ggplot(df, aes(x = t, y = r, ymin = lower_ci, ymax = upper_ci)) +
    geom_line() +
    geom_ribbon(alpha = 0.2) +
    scale_x_continuous(limits = c(0, pi)) +
    coord_radial(theta = "x", direction = -1, start = -pi / 2, end = pi / 2, expand = F)

Some considerations

Upvotes: 0

Views: 44

Answers (1)

C.K.
C.K.

Reputation: 1571

I'm the OP, and for anyone looking for this, I temporarily solved this problem with a coordinate transformation and geom_polygon:

df.xy <- df %>%
    mutate(
        x = r * cos(t), y = r * sin(t),
        x_lower = lower_ci * cos(t), y_lower = lower_ci * sin(t),
        x_upper = upper_ci * cos(t), y_upper = upper_ci * sin(t)
    )
df.lower <- dfxy %>%
    select(x_lower, y_lower, t) %>%
    rename(x = x_lower, y = y_lower) %>%
    arrange(desc(t))
df.upper <- dfxy %>%
    select(x_upper, y_upper, t) %>%
    rename(x = x_upper, y = y_upper) %>%
    arrange(t)
df.ci <- bind_rows(df.lower, df.upper)

ggplot() +
    geom_polygon(data = df.ci, mapping = aes(x = x, y = y), fill = "grey", alpha = .8) +
    geom_path(data = df.xy, mapping = aes(x = x, y = y))

And the output will be like this:

Cartesian image

You can also easily encapsulate these code to a ggplot2 stat_* function to make the plotting codes more elegant.

I believe this is not the best solution, so I'll wait for a better solution. But for anyone who need a temporary solution, that's it.

Upvotes: 0

Related Questions