使用 ggplot

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

我想制作一个包含多年来(1991 - 2021)两个变量(体重 - 公斤)和(雨量 - 毫米)的图表。两个变量不相关!

绘制彼此分开的图表时一切正常:

图书馆(ggplot2)

    ggplot(data2, aes(x=ano_dtt)) +
      geom_col(aes(y=PesoAj220_d), fill="lightblue2") +
      ylim(0,300)
    

    ggplot(data2, aes(x=ano_dtt)) +
      geom_point(aes(y=ppt)) +
      geom_path(aes(y=ppt)) +
      ylim(0,1700)

但是,当我尝试添加第二个轴时,一切都出了问题!!!

    scaleRight <- 0.75
    
    ggplot(data2, aes(x=ano_dtt)) +
      geom_col(aes(y=PesoAj220_d), fill="lightblue2") +
      ylim(0,300) +
      geom_point(aes(y=ppt)) +
      geom_path(aes(y=ppt), colour="red", size=0.9) +
      ylim(0,1700)+
      scale_y_continuous(sec.axis = sec_axis(~.*scaleRight, name="precipitacion (mm)")) +
      labs(title = "", x="año", y="peso")

我也试试这个:

    scaleRight <- 0.75
    
    ggplot(data2, aes(x=ano_dtt)) +
      geom_col(aes(y=PesoAj220_d), fill="lightblue2") +
      ylim(0,300) +
      geom_point(aes(y=ppt)) +
      geom_path(aes(y=ppt), size=0.9) +
      ylim(c(0,1700)) 

但是图中唯一的轴有问题。

我认为问题在于

    scaleRight <- 0.75

有人可以帮忙解决这个问题吗?我很确定这非常非常简单!

r ggplot2 scale axis
1个回答
0
投票

您面临的问题是您必须缩放次要 y 轴值以使其落入主要 x 轴的范围内。正如您所猜测的,将辅助 y 轴值乘以设定值 (scaleRight) 并不是实现您目标的方法。

我很难在

ggplot()
函数内进行缩放,因此我更喜欢在绘图之前缩放辅助 y 轴值。下面概述的方法在两个 y 轴上创建相同数量的轴中断,如果您喜欢每侧不同数量的中断,请发表评论,我将更新代码。

library(ggplot2)

# Example data
set.seed(1)
data2 <- data.frame(ano_dtt = 1991:2021,
                    
                    PesoAj220_d = sample(250:300, 31),
                    ppt = sample(750:1550, 31))


# Set axes limits, must exceed or equal min/max data values
# Set min and max limits for left y-axis
l.y.min <- 0
l.y.max <- 300

# Set min and max limits for right y-axis
r.y.min <- 0
r.y.max <- 1700

# Function to scale secondary y-axis values
axis_scaled <- function(x, y, z, max.var) {
  y <- ((x - y) / (z - y)) * max.var
  y <- y[2:(length(y)-1)]
}

# Add scaled secondary y-axis values to data2
data2$scaled_ppt <- axis_scaled(c(r.y.min, data2$ppt, r.y.max),
                                r.y.min, r.y.max, l.y.max)

# Create breaks for primary y-axis and labels for secondary y-axis
l.y.breaks <- seq(l.y.min, l.y.max, length.out = 5)
r.y.labels <- seq(r.y.min, r.y.max, length.out = length(l.y.breaks))

# Plot
ggplot(data2, aes(x = ano_dtt)) +
  geom_col(aes(y = PesoAj220_d), fill = "lightblue2") +
  geom_point(aes(y = scaled_ppt)) +
  geom_path(aes(y = scaled_ppt), colour = "red", linewidth = 0.9) +
  scale_x_continuous(breaks = 1991:2021) +
  scale_y_continuous(breaks = l.y.breaks,
                     sec.axis = sec_axis(~ .,
                                         breaks = l.y.breaks,
                                         labels = r.y.labels,
                                         name="precipitacion (mm)")) +
  labs(title = "", x = "año", y = "peso") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

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