带有 ggplot 多条线和辅助轴的线图

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

我正在尝试使用 ggplot 绘制线图,其中两条线表示左侧的 y 轴,一条线表示右侧的次轴。 我知道如何获取辅助轴,如果左轴只有一行,一切都会很好。 我认为问题是在左轴上显示两条线。 这是我的数据示例:

    years <- rep(c("2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022"), 3)
    legend <- c(rep("price1", 11), rep("price2", 11), rep("price3", 11))
    numbers <- c(8,3,14,10,16,19,26,23,9,3,16,2.0,0.6,3.0,2.1,3.3,4.1,6.1,6.0,3.4,1.4,5.6,
                           3943200,4694600,4644400,4876700,4792600,4610700,4239000,3832300,
                           2647500,2179400,2853700)
dataset <- data.frame(years, legend, numbers)

价格1和价格2的数字应显示在左轴上,价格3的数字应显示在右轴上。

r ggplot2
1个回答
0
投票

一种方法是将数据拆分为两组价格。比例因子约为 1:200,000,但我选择了 100,000 来将两组分开一点。

data1 <- filter(dataset, legend!="price3")
data2 <- filter(dataset, legend=="price3")

ggplot(data1, aes(x=years, y=numbers, col=legend, group=legend)) +
  geom_line(linewidth=1) +
  geom_line(data=data2, aes(y=numbers/100000), linewidth=1) +
  scale_y_continuous(sec.axis = sec_axis(~.*100000, labels=scales::comma))

enter image description here

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