用ggplot和plotly子图显示图例

时间:2018-12-20 23:14:31

标签: r ggplot2 legend subplot r-plotly

我对R还是比较陌生,并且一直在尝试使用R创建交互式绘图,并用它来代替枯燥的Excel绘图。

我正在制作一个由4个子图组成的情节,除了图例外,其他所有内容我都想得到。对于我的一生,我找不到传说。理想情况下,我希望在每列的底部都有一个图例,但我无法绘制基本的ggplot图例。

p1 <- ggplot(ks,aes(x=date)) +
  geom_point(aes(y=ks$sdtw)) +
  geom_hline(yintercept=ks$avgs, color="red") +
  geom_hline(yintercept=ks$maxs, color="blue") +
  geom_hline(yintercept=ks$mins, color="green") +
  scale_x_date(expand = c(0,0)) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_reverse(breaks = seq(8,11, by = 0.5)) 

p2 <- ggplot(ks, aes(x = date)) +
  geom_point(aes(y=ks$ddtw)) +
  geom_hline(yintercept=ks$avgd, color="red") +
  geom_hline(yintercept=ks$maxd, color="blue") +
  geom_hline(yintercept=ks$mind, color="green") +
  scale_x_date(expand = c(0,0)) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_reverse(breaks=seq(8,10, by = 0.5)) 

p3 <- ggplot(ks, aes(x = date)) +
  geom_ribbon(aes(ymin = mins_h, ymax = maxs_h), 
          fill = "wheat2",
          color="black") +
  geom_line(aes(x=date, y=avgs_h), size=1,color="red") +
  geom_line(aes(x=date, y=avgsm_h), size=1.5, color="green")+
  coord_cartesian(xlim = c(hstart, hend)) +
  scale_x_date(expand = c(0,0)) +
  scale_y_reverse(breaks = seq(8,11, by = 0.5)) +
  theme(axis.text.x = element_text(angle = 45)) 

p4 <- ggplot(ks, aes(x = date)) +
  geom_ribbon(aes(ymin = mind_h, ymax = maxd_h), 
           fill = "wheat2",
           color="black") +
  geom_line(aes(x=date, y=avgd_h ), size=1,color="red") +
  geom_line(aes(x=date, y=avgdm_h), size=1.5, color="green") +
  coord_cartesian(xlim = c(hstart, hend)) +
  scale_x_date(expand = c(0,0)) +
  scale_y_reverse(breaks=seq(8,10, by = 0.5)) +
  theme(axis.text.x = element_text(angle = 45)) 

subplot(p1, p3, p2, p4,
    nrows = 2, shareX = TRUE, shareY = TRUE, heights = c(0.47, 0.47)) %>%
  layout(title = "Plot")

为简洁起见,我对代码进行了一些编辑,以下是我得到的内容。关于我缺少传奇的情况有什么建议吗?

Link to plot

0 个答案:

没有答案