【问题标题】:How to make a custom legend when a plot overlays another using ggplot?当一个情节使用ggplot覆盖另一个情节时,如何制作自定义图例?
【发布时间】:2016-01-19 12:15:06
【问题描述】:

我需要绘制一个堆叠直方图来绘制两个不同的变量。有一个名为T1 的变量,还有一个名为T2 的变量。这两个变量有两种不同的状态,一种发生在之前,另一种发生在之后。 我想要一个图,我将在一列中同时显示T1T2,它们之前和之后的状态,但使用两种不同的颜色(一种表示之前的状态,另一种表示之后的状态) .

这是我目前的代码 sn-p:

pre <- as.data.frame( matrix( nrow=2,ncol=2,byrow=TRUE,c(60,"T1",40,"T2") ) )
post <- as.data.frame( matrix( nrow=2,ncol=2,byrow=TRUE,c(70,"T1",50,"T2") ) )
pre$V1 <- as.numeric(as.character(pre$V1))
post$V1 <- as.numeric(as.character(post$V1))

ggplot() +
geom_histogram(stat="identity", fill=c(rep("red",2)), data=post, aes(x=V2, y=V1, fill=V2, colour="Before")) +
geom_histogram(stat="identity", fill=c(rep("green",2)), data=pre, aes(x=V2, y=V1, fill=V2, colour="After")) +
scale_x_discrete("x axis") +
scale_y_continuous("y axis", limits = c(0, 100)) +
scale_colour_manual(values = c("red","green"))

所以情节看起来很神奇,但是我现在的问题是,我怎样才能得到一个合适的传说?所以我需要为"After" 设置一种颜色,为"Before" 设置另一种颜色,但不是线条,而是填充框。

【问题讨论】:

  • 所以您希望红色区域仅类似于“之前”和“之后”值之间的差异?

标签: r plot ggplot2


【解决方案1】:

首先,当您制作条形图时,请使用geom_bar()。然后对于aes()里面的fill=color=使用相同的名字,然后用scale_..函数调整颜色和填充。

ggplot() +
  geom_bar(stat="identity",  data=post, aes(x=V2, y=V1, fill="Before",color="Before")) +
  geom_bar(stat="identity", data=pre, aes(x=V2, y=V1, fill="After",color="After")) +
  scale_x_discrete("x axis") +
  scale_y_continuous("y axis", limits = c(0, 100)) +
  scale_fill_manual("Legend",values = c("green","red"))+
  scale_color_manual("Legend", values = c("red","green"))

【讨论】:

  • 这正是我所追求的!在我的情况下,情节有点不同,图例中的方框上有一条黑线,但是我输入了scale_color_manual("Legend", values = c("black","black")),现在它很完美!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 2012-11-05
  • 2021-11-03
相关资源
最近更新 更多