ggplot2:如何在R中正确格式化sec.axis [英] ggplot2: How to format the sec.axis properly in R

查看:103
本文介绍了ggplot2:如何在R中正确格式化sec.axis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ggplot图表中使用geom_line()绘制3条线.其中一个变量的标度不同,因此我也尝试使用sec.axis来显示它.

I am trying to plot 3 lines using geom_line() in my ggplot graph. One of the variables has a different scale so I am trying to use the sec.axis in order to show it as well.

library(ggplot2)
library(reshape2)

tab <- data.frame(year = seq(1979,2010), freq = runif(32, 212,283), max = 
runif(32, 962.1, 993.4), med = runif(32, 972.1, 989.3), min = runif(32, 
955.7, 978.3))

summary(tab) # the column freq (frequency) has a different scale comparing with the other ones

我尝试过的一些代码.

tab <- melt(tab, id = c("year")) # melt the data

ggplot(tab, aes(x = year, y = value)) + 
theme_bw() + 
scale_colour_manual(values =c('red','blue', 'green')) + 
geom_line() + 
scale_y_continuous(limits = c(900,1000), sec.axis = sec_axis(~. *0.3)) # I am using limits in order to control the extent for the other variabiles besides 'freq'.

这显示了第二个y_axis,但是缺少变量"freq".到目前为止,我找不到一个示例,该示例也显示如何使用sec.scale对一个变量绘制多条线.另外,我不确定是需要先转换"freq"变量还是只需要控制它的sec.axis,所以如果有人可以解释我,我将不胜感激.

This shows the second y_axis but the variable 'freq' is missing. So far, I could not find an example showing how to plot multiple lines using a sec.scale as well for one variable. Also, I am not sure if I need to transform the 'freq' variable first or only to control the sec.axis for it so if anyone can explain me, I will be grateful.

谢谢!

推荐答案

您正在寻找类似的东西吗?

You are looking for something like this?

tab %>%
  mutate(value = if_else(variable == 'freq', value + 700, value)) %>%
  ggplot(aes(
    x = year,
    y = value,
    color = variable
  )) + 
  theme_bw() + 
  scale_colour_manual(values =c('red','blue', 'green', 'black')) + 
  geom_line() + 
  scale_y_continuous(sec.axis = sec_axis(
    trans = ~ . - 700,
  ))

这篇关于ggplot2:如何在R中正确格式化sec.axis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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