6

ggplot2 で 2 つの凡例を持つことは可能ですが、異なるデータセットに基づいていますか? たとえば、以下のコードでは、最初の状況の凡例と 2 番目の状況の凡例の両方を同じグラフィックで取得したいと考えています。私の試み (3 番目の状況) が機能しません。

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
4

1 に答える 1

13

一般に、より複雑なプロットに取り掛かり始めたら、ほとんどの場合、使用をやめて代わりに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)")

これは与える:

プロット

于 2012-07-27T13:22:17.523 に答える