Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display only a given angular range in a circular histogram

Tags:

r

ggplot2

The following code using R/ggplot

set.seed(123)
require(ggplot2)
n <- 60

df <- data.frame(theta=sample(180,n,replace=TRUE),
                 gp=sample(c("A","B"),n,replace=TRUE ))

p <- ggplot(df)
p <- p + geom_histogram(aes(x=theta,fill=gp),
                        binwidth=5)

p <- p + scale_x_continuous(breaks=seq(0,360,30),
                            limits=c(0,360))

p <- p + coord_polar(theta="x", start=3*pi/2, direction=-1)
p <- p + theme_bw()
print(p)

generates the figure below enter image description here

I just want to display the angular range [0,180] and exclude entirely the range (180,360), so the figure would basically be the upper semi-circle rather than a full circle.

Changing the limits in scale_x_continuous does not do this. Is there a way? Thanks.

EDIT There's a similar problem but with a different package here Creating half a polar plot (rose diagram) with circular package

like image 849
PM. Avatar asked Nov 07 '22 15:11

PM.


1 Answers

It is some kind of a hack, but based on this answer here and adding some code to your ggplot call as well as to the grid, I was able to come close to a solution. Please give it a try. Depending on your desired output format / resolution you might need to adjust the x, y, height and width arguments in the last line which basically recreates the black border around the plot which I deleted from the bw theme. Maybe someone with more profound knowledge of grobs can come up with something better.

library(ggplot2)
library(reshape2)
library(grid)

set.seed(123)

require(ggplot2)
n <- 60

df <- data.frame(theta=sample(180,n,replace=TRUE),
                 gp=sample(c("A","B"),n,replace=TRUE ))

p <- ggplot(df) + geom_histogram(aes(x = theta, fill = gp),
                                 binwidth = 5) +
    scale_x_continuous(
        expand = c(0, 0),
        breaks = seq(180, 0, -30),
        limits = c(0, 360)
    ) +
    coord_polar(theta = "x",
                start = 3 * pi / 2,
                direction = -1) +
    theme_bw() +
    theme(
        panel.border = element_blank(),
        axis.title.y = element_text(hjust = 0.75, vjust = 3),
        legend.position = "top"
    )

g = ggplotGrob(p)

grid.newpage()
pushViewport(viewport(height = 1, width = 1, clip="on"))
grid.draw(g)
grid.rect(x = 0, y = -0.05, height = 1, width = 2, gp = gpar(col="white"))
grid.rect(x = .5, y = .7, width = .6, height = .55, gp = gpar(lwd = 1, col = "black", fill = NA))
like image 166
TimTeaFan Avatar answered Nov 13 '22 18:11

TimTeaFan