ggplot2:如何在 R 中正确格式化 sec.axis

问题描述 投票:0回答:2

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

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,所以如果有人能解释我,我将不胜感激。

谢谢!

r ggplot2 scale
2个回答
4
投票

您正在寻找这样的东西吗?

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

4
投票

您也可以使用

geom_pointrange
,无需熔化数据。我稍微更改了数据以使图表更好看,但您可以稍后根据您的数据进行调整。

tab <- data.frame(year = seq(1979,2010), freq = runif(32, 280,300), max = 
                    runif(32, 975.1, 993.4), med = runif(32, 972.1, 975.3), 
                  min = runif(32,955.7, 971.3))   

ggplot(data = tab, mapping = aes(x = year)) +
  geom_pointrange(mapping = aes(y=med,ymin = min, ymax = max),size=0.5,color='blue',fatten = 1)+theme_bw()+
  geom_point(aes(x=year,y=freq/0.3), inherit.aes = FALSE,color='red')+
  scale_y_continuous( name = 'range and median', sec.axis = sec_axis(~. *0.3,name = "frequency"))+
  theme(axis.text.y  = element_text(color = 'blue'),
    axis.title.y = element_text(color='blue'),
    axis.text.y.right =  element_text(color = 'red'),
    axis.title.y.right = element_text(color='red'))

© www.soinside.com 2019 - 2024. All rights reserved.