基于与GGPLOT2不同的数据集两种传说(two legends based on differen

2019-09-20 07:58发布

是否有可能有两个传说与GGPLOT2但基于不同的数据集? 例如,在下面的代码我想获得的第一种情况都传说和在相同的图形第二种情况的传说。 我尝试(第三种情况)不工作。

library(ggplot2)
library(scales)

yrng <- range(economics$unemploy)
xrng <- range(economics$date)
presidential <- presidential[-(1:3), ]

# add a fictive factor to the economics dataset
economics <- cbind.data.frame(economics, col=gl(2, nrow(economics)/2))

#####################
## first situation ##
#####################
# first plot with legend
unemp <- qplot(date, unemploy, data=economics, geom="line",
                 xlab = "", ylab = "No. unemployed (1000s)", colour=col)
# second plot without legend
unemp + geom_vline(aes(xintercept = start), data = presidential)

######################
## second situation ##
######################
# first plot without legend
unemp <- qplot(date, unemploy, data=economics, geom="line",
                 xlab = "", ylab = "No. unemployed (1000s)")
# second plot with legend
unemp + 
  geom_rect(aes(NULL, NULL, xmin = start, xmax = end,
                    fill = party), ymin = yrng[1], ymax = yrng[2],
                    data = presidential) +
  scale_fill_manual(values = alpha(c("blue", "red"), 0.2))


#####################
## third situation ##
#####################
# first plot with legend
unemp <- qplot(date, unemploy, data=economics, geom="line",
                 xlab = "", ylab = "No. unemployed (1000s)", colour=col)
# second plot with legend
unemp + 
  geom_rect(aes(NULL, NULL, xmin = start, xmax = end, fill = party), ymin = yrng[1],
              ymax = yrng[2], data = presidential) + 
  scale_fill_manual(values = alpha(c("blue", "red"), 0.2))

Error in data.frame(xmin = 11342, xmax = 14264, fill = "Republican", colour = function   (x,  : 
  arguments imply differing number of rows: 1, 0

Answer 1:

一般而言,一旦我开始变得更复杂的情节,它几乎总是最好停止使用qplot和使用ggplot代替。 我觉得更容易去思考如何我一块建积起片:

ggplot() +
  geom_line(aes(x=date, y=unemploy, color=col), data=economics) +
  geom_rect(aes(xmin=start, xmax=end, fill=party),
            ymin = yrng[1], ymax = yrng[2], data = presidential) +
  scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) +           
  xlab("") +
  ylab("No. unemployed (1000s)")

这给:



文章来源: two legends based on different datasets with ggplot2
标签: r ggplot2