r - ggplot2 - 添加具有不同中断和标签的辅助 y 轴

标签 r ggplot2

是否可以使用 ggplot2 手动将中断和标签添加到辅助 y 轴?

enter image description here (见右下角)

我希望在右侧 y 轴上有更紧凑的中断,代表条形。

最佳答案

此图将是基本情况,然后我将展示如何更改辅助 y 轴上的中断和标签:

sapply(c("pipeR", "ggplot2"), require, character.only = TRUE)

data(swiss)
swiss %>>% ggplot() + 
  geom_bar(mapping = aes(x = Agriculture, y = Fertility * 30 / 400), stat = "identity", colour = gray(0.5), fill = gray(0.5)) + 
  geom_line(mapping = aes(x = Agriculture, y = Education)) + 
  geom_point(mapping = aes(x = Agriculture, y = Education), size = 3, shape = 21, fill = "white") + 
  scale_x_continuous() + 
  scale_y_continuous(
    name = expression("Education"), 
    sec.axis = sec_axis(~ . * 400 / 30 , name = "Fertility"), 
    limits = c(0, 30)) + 
  theme_bw() + 
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank()
  )

enter image description here

更改休息时间:
swiss %>>% ggplot() + 
  geom_bar(mapping = aes(x = Agriculture, y = Fertility * 30 / 400), stat = "identity", colour = gray(0.5), fill = gray(0.5)) + 
  geom_line(mapping = aes(x = Agriculture, y = Education)) + 
  geom_point(mapping = aes(x = Agriculture, y = Education), size = 3, shape = 21, fill = "white") + 
  scale_x_continuous() + 
  scale_y_continuous(
    name = expression("Education"), 
    sec.axis = sec_axis(~ . * 400 / 30 , name = "Fertility", breaks = seq(1,1000,10)), 
    limits = c(0, 30)) + 
  theme_bw() + 
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank()
  )

enter image description here

更改标签:
swiss %>>% ggplot() + 
  geom_bar(mapping = aes(x = Agriculture, y = Fertility * 30 / 400), stat = "identity", colour = gray(0.5), fill = gray(0.5)) + 
  geom_line(mapping = aes(x = Agriculture, y = Education)) + 
  geom_point(mapping = aes(x = Agriculture, y = Education), size = 3, shape = 21, fill = "white") + 
  scale_x_continuous() + 
  scale_y_continuous(
    name = expression("Education"), 
    sec.axis = sec_axis(~ . * 400 / 30 , name = "Fertility", breaks = seq(1,1000,10), labels=rep("x",length(seq(1,1000,10)))), 
    limits = c(0, 30)) + 
  theme_bw() + 
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank()
  )

enter image description here

有用链接:https://whatalnk.github.io/r-tips/ggplot2-secondary-y-axis.nb.html

关于r - ggplot2 - 添加具有不同中断和标签的辅助 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46039176/

相关文章:

r - 如何将多个 ggplot2 元素组合到函数的返回中?

r - 使用 ggplot2 对数正态刻度进行漂亮的刻度(动态而非手动)

r - 如何在一个图中绘制 'multiple box plots'?

r - 在Rastervis中使用gplot方法时如何去除背景灰色?

r - 如何在R中使用正确的(中文)编码下载网页文本

行式迭代,如 apply with purrr

html - sendmailR 在 HTML 正文中添加额外空间,偶尔会破坏 HTML 标签

r - 通过传递列参数创建 dplyr 函数

r - ggplot fiddle 情节不是在策划

r - 如何通过仅对 R 中现有列中的行中的文本进行子集化来创建新列