简体   繁体   English

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

[英]ggplot2 - adding secondary y-axis with different breaks and labels

is it possible to manually add breaks and labels to the secondary y-axis using ggplot2? 是否可以使用ggplot2手动将断点和标签添加到辅助y轴?

在此输入图像描述 (see bottom right) (见右下角)

I want more compact breaks on the right y-axis, representing the bars. 我希望在右侧y轴上有更紧凑的断点,代表条形。

This graph will be the base case, then I'll show how to change breaks and labels on the secondary y-axis: 这个图表将是基本情况,然后我将展示如何更改辅助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()
  )

在此输入图像描述

Change the breaks: 改变休息时间:

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()
  )

在此输入图像描述

Change labels: 更改标签:

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()
  )

在此输入图像描述

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM