ggplot2:如何交换y轴和右小平面条以及如何排序小平面值

nev*_*int 9 r ggplot2

使用以下代码:

library(ggplot2)
set.seed(6809)
diamonds <- diamonds[sample(nrow(diamonds), 1000), ]
diamonds$cut <- factor(diamonds$cut,
         levels = c("Ideal", "Very Good", "Fair", "Good", "Premium"))

# Repeat first example with new order
p <- ggplot(diamonds, aes(carat, ..density..)) +
        geom_histogram(binwidth = 1)
p + facet_grid(color ~ cut)
Run Code Online (Sandbox Code Playgroud)

我可以创建下图:

在此输入图像描述

我的问题是:

  1. 如何根据我想要的顺序对正确的条排序,例如(G,F,D,E,I,J,H)?
  2. 如何将正确的条带与y轴(密度)交换?

eip*_*i10 13

更新ggplot2 2.2.1

使用ggplot2版本2,您可以切换轴标签和构面标签的位置.所以这里是利用这些功能的更新代码:

# Reorder factor levels
diamonds$color = factor(diamonds$color, levels=c("G","F","D","E","I","J","H"))

ggplot(diamonds, aes(carat, ..density..)) +
  geom_histogram(binwidth=1) +
  facet_grid(color ~ cut, switch="y") +   # Put the y facet strips on the left
  scale_y_continuous("density", position="right") +   # Put the y-axis labels on the right
  theme(strip.text.y=element_text(angle=180))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

原始答案

正如@joran所说,如果你想完全控制在哪里,你必须修改网格对象.那很痛苦.

这是另一种方法,仍然是一个麻烦,但比修改网格对象更容易(至少对我来说).基本思想是我们定向各种小平面和轴标签,以便我们可以将绘图逆时针旋转90度(以获得左侧的小平面标签),同时仍然使所有标签正确定向.

要使这项工作,你需要以几种方式修改图形:注意我添加coord_flip,所有的theme东西,和scale_x_reverse.另请注意,我已经切换了facet变量的顺序,因此color从顶部开始(在我们旋转图形后它将在左侧).

# Reorder factor levels
diamonds$color = factor(diamonds$color, levels=rev(c("G","F","D","E","I","J","H")))

p <- ggplot(diamonds, aes(carat, ..density..)) +
  geom_histogram(binwidth = 1) +
  facet_grid(cut ~ color) + coord_flip() +
  theme(strip.text.x=element_text(angle=-90),
        axis.text.y=element_text(angle=-90, vjust=0.5, hjust=0.5),
        axis.text.x=element_text(angle=-90, vjust=0.5, hjust=0),
        axis.title.x=element_text(angle=180),
        axis.title.y=element_text(angle=-90)) +
  scale_x_reverse()
Run Code Online (Sandbox Code Playgroud)

一种选择是保存图形,然后在另一个程序中旋转它(如预览,如果你在Mac上).然而,在这个SO答案的帮助下,我能够在R内旋转绘图.它需要一些试验和错误(我对如何操作网格对象的知识有限)才能获得视口的正确大小.我将其保存为PNG,以便在SO上发布,但您当然可以将其保存为PDF,这样看起来会更好.

png("example.png", 500,600)
pushViewport(viewport(width = unit(8, "inches"), height = unit(7, "inches"))) 
print(p, vp=viewport(angle=90))
dev.off()
Run Code Online (Sandbox Code Playgroud)

这是结果:

在此输入图像描述