我正在尝试使用 ggplot 绘制双 y 轴图表。首先我要说的是,我并不是在寻找关于这样做是否是良好做法的优点的讨论。我发现它们在查看基于时间的数据来识别两个离散变量的趋势时特别有用。我认为对此进行进一步讨论更适合交叉验证。
Kohske https://rpubs.com/kohske/dual_axis_in_ggplot2提供了一个很好的例子来说明如何做到这一点,到目前为止我已经使用了它,效果很好。然而,我无法为两个 y 轴添加图例。我也看到过类似的问题here https://stackoverflow.com/questions/3099219/how-to-use-ggplot2-make-plot-with-2-y-axes-one-y-axis-on-the-left-and-another and here https://stackoverflow.com/questions/22701606/how-to-plot-bars-and-one-line-on-two-y-axes-in-the-same-chart-with-r-ggplot/22734987#comment42005315_22734987但似乎没有人解决包含图例的问题。
我有一个使用 ggplot 中的钻石数据集的可重现示例。
Data
library(ggplot2)
library(gtable)
library(grid)
library(data.table)
library(scales)
grid.newpage()
dt.diamonds <- as.data.table(diamonds)
d1 <- dt.diamonds[,list(revenue = sum(price),
stones = length(price)),
by=clarity]
setkey(d1, clarity)
Charts
p1 <- ggplot(d1, aes(x=clarity,y=revenue, fill="#4B92DB")) +
geom_bar(stat="identity") +
labs(x="clarity", y="revenue") +
scale_fill_identity(name="", guide="legend", labels=c("Revenue")) +
scale_y_continuous(labels=dollar, expand=c(0,0)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1),
axis.text.y = element_text(colour="#4B92DB"),
legend.position="bottom")
p2 <- ggplot(d1, aes(x=clarity, y=stones, colour="red")) +
geom_point(size=6) +
labs(x="", y="number of stones") + expand_limits(y=0) +
scale_y_continuous(labels=comma, expand=c(0,0)) +
scale_colour_manual(name = '',values =c("red","green"), labels = c("Number of Stones"))+
theme(axis.text.y = element_text(colour = "red")) +
theme(panel.background = element_rect(fill = NA),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(fill=NA,colour="grey50"),
legend.position="bottom")
# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))
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)
问题:有人对如何显示图例的第二部分有一些建议吗?
以下是按顺序 p1、p2、组合 p1&p2 生成的图表,您会注意到组合图表中没有显示 p2 的图例。
p1
p2
合并 p1 和 p2