Reputation: 741
I want to do some modifications of a geom_boxplot:
Here is an example:
aa <- c(rep("A1",5), rep("A2",3), rep("A3",4), rep("A4",9))
aa <- as.factor(aa)
per <- runif(length(aa), min=0, max=100)
per <- trunc(per)
z <- data.frame(x=aa,y=per)
z$ch <- NA
z[z$x %in% c("A1","A2"), "ch"] <- "string1"
z[z$x %in% c("A3"), "ch"] <- "string2"
z[z$x %in% c("A4"), "ch"] <- "string3"
z$ch <- as.factor(z$ch)
p <- ggplot(z, aes(x, y, fill = ch)) +
geom_boxplot(size = 0.2, position = "dodge", outlier.colour = "red", outlier.shape = 16, outlier.size = 2) +
geom_jitter(size=1) + opts(legend.position = "right") +
scale_colour_hue("variable") +
coord_flip()
print(p)
Upvotes: 1
Views: 738
Reputation: 60924
Reversing the order of the labels on the y-axis can be done by reordering the levels of the factor (z$x):
z$x = with(z, factor(x, rev(levels(x))))
To get the legend inside the plot you can use the legend.position
option. The trick is that when you set it to e.g. "top" or "bottom" the legend is placed outside the plot. When using a vector of two numbers, it places the legend at that position inside the plot. In code:
p + opts(legend.position = c(0.85,0.85),
legend.background = theme_rect("white"))
Which leads to the following plot, which I think is what you wanted:
Note the addition of legend.background to draw a filled rectangle surrounding the legend. Furthermore, I myself do not really like having the legend inside the plot as it can obscure the data. But that is, ofcourse, for you to decide :).
Upvotes: 2