如何用2 y轴R(网格绘制)修改绘图

时间:2017-02-09 12:55:49

标签: r ggplot2 shiny

这是我的数据:

dput(Data)

structure(list(DATE = c(2015L, 2016L, 2017L, 201601L, 201602L, 201603L,201604L, 201701L), Z = c("Single", "Single", "Single", "Single", "Single", "Single", "Single", "Single"), Y = c(6.59, 6.6, 6.22, 6.96, 6.82, 6.41, 6.19, 6.22), A = c(43.9, 41.69, 47.23, 41.73, 40.31, 42.01, 42.83, 47.23), Period = c("Y", "Y", "Y", "Q", "Q", "Q", "Q", "Q"), X = structure(1:8, .Label = c("2015", "2016", "2017", "Q1-2016", "Q2-2016", "Q3-2016", "Q4-2016", "Q1-2017"), class = c("ordered", "factor")), Obj = c(6.97, 6.39, 6.53, 6.41, 6.42,6.36, 6.36, 6.53)), .Names = c("DATE", "Z", "Y", "A", "Period", "X","Obj"), row.names = c(81L, 80L, 79L, 53L, 51L, 50L, 49L, 52L), class = "data.frame")

我用过:

library(ggplot2)
library(gtable)

#Fonction pourle Plot superpose, comme ca on peut la reutiliser
plot1 <- ggplot(data = Data, aes(x = X, y = Y)) + geom_bar(stat="identity",fill ="#3090C7")+geom_errorbar(aes(y=Obj,ymin=Obj,ymax=Obj),colour="darkblue",size=3)+ggtitle("Graphique")+xlab("Time")+ylab("% Downtime")+scale_y_continuous(breaks=seq(0,round(max(as.numeric(Data$Y)))))+theme(plot.title = element_text(hjust = 0.5))
plot2 <- ggplot(Data, aes(x=X, y=A, group=1, colour=A))+geom_point(colour = "MediumVioletRed")+ geom_line(colour = "MediumVioletRed",size=1.5)+ labs(y = "Y_axix", x = NULL)+theme_bw() %+replace% theme(panel.background = element_rect(fill = NA))
# extract gtable
g1 <- ggplot_gtable(ggplot_build(plot1))
g2 <- ggplot_gtable(ggplot_build(plot2))

# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, 
                 pp$l, pp$b, pp$l)

# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.02, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

grid.draw(g)

我得到以下情节:

enter image description here

我会获得相同的情节,除了:

  • 修改第二个Y轴刻度:有36-52在线后面留空间。我希望这条线位于条形图的中间高度

  • 删除网格图案

要获得这样的情节: enter image description here

感谢您的帮助!

我刚刚找到了第二个问题的答案,我必须在2 ggplot语句中添加“+ theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank())”。

0 个答案:

没有答案