为条形图的子集创建图例

时间:2013-09-13 07:11:38

标签: r ggplot2

如何为下面的情节和边距创建图例?我搜索了?theme,但我不知道。

library(ggplot2)
data <- data.frame(col1 = c(1, 2, 2, 3, 3, 4), col2 = c(1, 2, 2, 1, 2, 1), z = rnorm(6))

p1 <- ggplot(data, aes(col1, y = ..count..,fill=col2))
p1 <- p1 + geom_bar()

p2 <- ggplot(data, aes(x = z))
p2<-p2 + geom_density()
p2

gt1 <- ggplot_gtable(ggplot_build(p1))
gt2 <- ggplot_gtable(ggplot_build(p2))

获取x轴和y轴标题和文字的最大宽度和高度

maxWidth = unit.pmax(gt1$widths[2:3], gt2$widths[2:3])

为gt1,gt2和gt3

设置gtables中的最大值
gt1$widths[2:3] <- as.list(maxWidth)
gt2$widths[2:3] <- as.list(maxWidth)

将散点图与两个边缘箱图结合起来 创建一个新的gtable

gt <- gtable(widths = unit(c(7, 2), "null"), height = unit(c(2, 7), "null"))

Instert gt1,gt2和gt3进入新gtable

gt <- gtable_add_grob(gt, gt1, 2, 1)
gt <- gtable_add_grob(gt, gt2, 1, 1)

渲染情节

grid.newpage()
grid.draw(gt)

1 个答案:

答案 0 :(得分:0)

只是说清楚。 带有循环的初始代码产生了稍微不同的结果,而不是填充选项

1)如果您想添加图例,您应该为 制图 添加颜色:

ggplot(data,aes(col1,group=col2,fill="id"))+
geom_bar(position="identity",alpha=0.5)+
scale_fill_manual(name="id",values="blue")

enter image description here

如果您有更大的数据,则无法将每个叠加的颜色添加到图例中,因为会有很多选项。每个条形图的黑暗显示每个col1与col2 id的强度,但不显示哪个

2)“填充”选项有点不同

ggplot(data,aes(col1,fill=as.factor(col2)))+geom_bar(position="dodge")

enter image description here

它只显示每个col1的col2 id。这个想法略有不同。

3)您可以通过添加以下内容手动更改图例:

guides(fill=guide_legend(title="Col2",
                       direction = "vertical",title.position="top",
                       title.vjust = 0.5)) # just example

使用scale_fill_discrete()选项

创建图例键

4)不确定密集图中你想要什么样的传说,但让我们假设如下:

ggplot(data, aes(x = z,colour="id"))+ 
geom_density()+
scale_colour_manual(name="id",values="blue")

enter image description here

然后你只需将情节加在一起。顺便说一句,检查this教程,将多个图表添加到一起,希望您发现它很有用:)

P.S。你可以混合填充= col2,位置=“身份”和alpha = 0.5,这将是一个难以解释的糟糕情节,没有规模酿造者可以帮助:)

enter image description here

UPD:在代码中使用gtable。 让例1为p1图,例4为p2。 只需复制粘贴代码后,您将获得以下内容: enter image description here

如果您查看我提到的教程,您可以获得以下内容: enter image description here

再次,请澄清您真正想要传说的内容。当你得到绘图的大小时,你的情节也包含了图例。

如果您至少可以尝试我展示的示例,您可以看到ggtables中的差异。图例为guide-box(您可以通过编辑图例的选项猜测)。所以,你问过如何创建传说 - ta-da。 ggtable中的传说在哪里?当当。如果你还有其他问题,我担心它们超出了SO的能力

相关问题