r - 双 y 轴 - 右 y 轴的标签和背景网格线
问题描述
我需要在ggplot2
. 我曾尝试遵循此处发布的@kohske 解决方案:http ://rpubs.com/kohske/dual_axis_in_ggplot2但是,仍有两件事是不受欢迎的,我不知道如何解决它们。1. 在下面的图中,右 y 轴的标签不存在,而我想让它出现 2. 右 y 轴的网格线显示在条形图的顶部,而它应该在背景中。这是情节:
和代码:
library(ggplot2)
library(grid)
library(gtable)
grid.newpage()
p1 <- ggplot(ex,
aes(factor(subgroups, levels = c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday')),
y_left)) +
geom_bar(fill = rgb(16/255, 72/255, 128/255), stat = 'identity') +
theme_bw() +
labs(x = 'weekday')
p2 <- ggplot(ex, aes(factor(subgroups,
levels = c('Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday')), y_right)) +
geom_line(colour = rgb(237/255, 165/255, 6/255), group = 1) +
geom_point(color = rgb(237/255, 165/255, 6/255), size = 3) +
scale_y_continuous(limits = c(0, 180)) +
labs(y = 'name for y_left axis') +
theme_bw() %+replace%
theme(panel.background = element_rect(fill = NA))
# 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)
解决方案
他们不久前为 ggplot 添加了辅助轴选项。尝试将两个geom
s 放在一个图上并添加scale_y_continuous(sec.axis = sec_axis(~.-280), name = "My Second Axis")
.
您可以计算比率,而不是简单的减法。这可以使用类似的东西内联完成sec.axis = sec_axis(~. * max(myData$y) / max(myData$y2))
,或者您可以提前计算它并将其应用于第二个轴和您打算在第二个轴上读取的数据,如下所示:
library(ggplot2)
# Create Sample Data
myData <- data.frame(x = seq(1, 10, length.out = 10),
y = seq(0, 20, length.out = 10),
y2 = seq(0, 100, length.out = 10))
myData.ratio <- max(myData$y) / max(myData$y2)
ggplot(myData, (aes(x=x, y=y))) +
geom_bar(stat="identity", aes(y=y2 * myData.ratio), fill = "lightblue") +
geom_line(color="red") +
geom_point(color="red") +
scale_y_continuous(sec.axis = sec_axis(~. / myData.ratio, name = "My Second Axis"))
请注意,在计算轴时,我们将实际值乘以 中的比率geom
并除以它。
输出:
推荐阅读
- angular - 角度 10 - 如何使用 RouterModule
- r - 使用 R 中的 mutate 和 case_when() 语句用 unite() 填充列,整洁的诗句
- tinymce - TinyMCE 可以去掉周围的 html - doctype、html 和 body 标签吗?
- discord.py - discord.py 如何向特定用户发送私人消息
- asp.net - 如何通过 twitter api 按 screenName 检索推文,以便我可以获得推文创建日期、推文和推文媒体?
- c++ - 如何在 std::function 上使用模板扩展
- sql-server - 用于批量插入的文本文件的行终止符
- python - 如何处理 insert_format.format 中的元字符?
- audio - 使用 ffmpeg 连接多个视频时声音丢失
- json - 如何从json数组中提取字符串值并存储它