ggplot2-添加具有不同中断和标签的辅助y轴 [英] ggplot2 - adding secondary y-axis with different breaks and labels

查看:61
本文介绍了ggplot2-添加具有不同中断和标签的辅助y轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用ggplot2在第二个y轴上手动添加中断和标签?

is it possible to manually add breaks and labels to the secondary y-axis using ggplot2?

(请参阅右下角)

我希望在右侧y轴上有更紧凑的断点,以表示条形.

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:

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

更改休息时间:

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

更改标签:

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

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

这篇关于ggplot2-添加具有不同中断和标签的辅助y轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆