我需要使用下面的数据框在右侧(inflation_rate)和左侧的另一个y轴(价格)上绘制y轴。
我的数据框架包含10年以来的价格和通货膨胀率:
Year Price inflation_rate
1 59424 9
2 64344 7
3 73200 6
4 72072 5
5 76104 4
6 84444 -2
7 90792 3
8 94464 0
9 99504 8
10 103992 1
生成上述代码的代码是:
library(dplyr)
set.seed(300)
Price<-c(
59424,
64344,
73200,
72072,
76104,
84444,
90792,
94464,
99504,
103992
)
year<-data.frame(c(seq(1:10)))
names(year)<-"Year"
priceinflation<-cbind(year, Price)
priceinflation<-priceinflation%>%
mutate(inflation_rate=c(sample(c(-2:10),10)))
我使用下面的代码绘制了我的双轴图表:
library(ggplot2)
library(gtable)
library(grid)
grid.newpage()
# two plots
#just do the normal plots here
p1 <- ggplot(priceinflation, aes(Year, Price)) +
geom_line(colour = "blue") +
theme(panel.background = element_blank())+
scale_y_continuous(labels=comma) +
scale_x_discrete(limits=(-3:10))
p2 <- ggplot(priceinflation, aes(x=Year,y=inflation_rate)) +
geom_line(colour = "red") +
theme(panel.background = element_blank())+
scale_y_discrete(limits=(-3:10))
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))
# 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.15, "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)
# draw it
grid.draw(g)
这里有各种各样的问题:
1. x轴是偏移的,0不在图表中
2.次y轴不显示到10,它在9处切换
折线图有许多白色网格线
4.没有传说来区分2个图表
请寻求解决我上述4个问题的建议。