R语言 是否有一个通用的方法来添加次要轴在ggplot没有缩放?

ie3xauqp  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(86)

我想使用ggplot在同一个图上绘制MAPE和准确度的线,以查看它们在不同集群上的变化。我尝试了不同的解决方案,如this post,但是,它们不工作。以下是我的数据:

data = structure(list(Clusters = c("1 Cluster", "2 Clusters", "3 Clusters", 
"4 Clusters", "5 Clusters", "6 Clusters", "7 Clusters", "8 Clusters"
), Accuracy = c("100", "72.4", "60.5", "42.4", "34.6", "24.7", 
"25.5", "22.4"), MAPE = c("138.604968", "130.1682745", "107.7288902", 
"156.0743566", "126.7168457", "144.2963746", "130.2850425", "134.7150458"
)), class = "data.frame", row.names = c(NA, -8L))

这是我正在尝试的,但我无法将MAPE和准确性缩放到相同的规模:

ggplot(data, aes(x = Clusters, y = Accuracy)) + 
  geom_point() + 
  geom_line(aes(y = MAPE))+
  scale_y_continuous(
    "MAPE (%)", 
    sec.axis = sec_axis(~ ., name = "MAPE (%)")
  )
ajsxfq5m

ajsxfq5m1#

可以说,如果尺度相同,就不需要第二个轴。但撇开这些不谈,您的数据和代码还有一些问题。
首先,y变量不是数字,所以让我们解决这个问题:

dataset <- structure(list(Clusters = c("1 Cluster", "2 Clusters", "3 Clusters", 
                                   "4 Clusters", "5 Clusters", "6 Clusters", "7 Clusters", "8 Clusters"
), Accuracy = c(100, 72.4, 60.5, 42.4, 34.6, 24.7, 
                25.5, 22.4), MAPE = c(138.604968, 130.1682745, 107.7288902, 
                                          156.0743566, 126.7168457, 144.2963746, 130.2850425, 134.7150458
                )), class = "data.frame", row.names = c(NA, -8L))

第二,如果您想在y轴上绘制多个变量,最好将数据重新整形为长格式,其中一列用于名称,一列用于值。可以使用tidyr::pivot_longer()

dataset %>%
  pivot_longer(-Clusters) %>% 
  ggplot(aes(x = Clusters, y = value)) + 
  geom_point(aes(color = name)) + 
  geom_line(aes(group = name))+
  scale_y_continuous("MAPE (%)", 
                     sec.axis = sec_axis(~ ., name = "Accuracy (%)"))

测试结果:

相关问题