two legends based on different datasets with ggplo

2019-04-28 03:25发布

Is it possible to have two legends with ggplot2 but based on different datasets ? For instance, in the code below I would like to get both the legend of the first situation and the legend of the second situation in the same graphic. My attempt (third situation) does not work.

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

标签: r ggplot2
1条回答
霸刀☆藐视天下
2楼-- · 2019-04-28 04:09

In general, once I start getting to more complicated plots, its almost always better to stop using qplot and use ggplot instead. I find it easier to think about how I'm building the plot up piece by piece:

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)")

This gives:

plot

查看更多
登录 后发表回答