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

时间:2015-04-08 02:31:16

标签: 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)

我可以创建下图:

enter image description here

我的问题是:

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

2 个答案:

答案 0 :(得分:12)

更新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))

enter image description here

原始答案

正如@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()

一种选择是保存图形,然后在另一个程序中旋转它(如预览,如果你在Mac上)。但是,在this SO answer的帮助下,我能够在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()

这是结果:

enter image description here

答案 1 :(得分:3)

facet_grid 的属性为“切换”。

  

开关:默认情况下,标签显示在图表的顶部和右侧。如果为“x”,则顶部标签将显示在底部。如果为“y”,则右侧标签将显示在左侧。也可以设置为“both”。

manual here

 facet_grid(cut ~ color, switch = "y")