R ggplot2:如何交换y轴和右侧镶嵌条以及如何排列镶嵌条值

R ggplot2:如何交换y轴和右侧镶嵌条以及如何排列镶嵌条值,r,ggplot2,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 <

使用以下代码:

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)
库(ggplot2)
种子集(6809)

ggplot2.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))

原始答案

正如@joran所说,如果你想完全控制什么东西去哪里,你必须修改网格对象。那很痛苦

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

要实现这一点,您需要以几种方式修改图形:注意我添加的
coord\u flip
、所有
主题
内容和
scale\u x\u reverse
。还要注意,我已经切换了facet变量的顺序,因此
color
从顶部开始(旋转图形后它将位于左侧)

结果如下:


facet\u grid具有属性“switch

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


(1) 与“剪切”相同:指定因子级别的顺序。(2) 如果不直接修改网格对象,你真的不可能。这是一个不错的新特性,但不幸的是Y轴仍然在同一侧。
# 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()
png("example.png", 500,600)
pushViewport(viewport(width = unit(8, "inches"), height = unit(7, "inches"))) 
print(p, vp=viewport(angle=90))
dev.off()
 facet_grid(cut ~ color, switch = "y")