创建主y轴和次y轴在R方向的碎石图

uqdfh47h  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个数据集

structure(list(X = c(26.7788998092606, 18.6280163936587, 14.349845629237, 
9.66310505252417, 7.94423462318618, 5.04943860391983, 3.27216212415563, 
2.94046432374716, 2.16429582651011, 1.63761158654806, 1.11240348866093
), X0 = 1:11, index1 = c(26.7788998092606, 18.6280163936587, 
14.349845629237, 9.66310505252417, 7.94423462318618, 5.04943860391983, 
3.27216212415563, 2.94046432374716, 2.16429582651011, 1.63761158654806, 
1.11240348866093), variance_pct = c(28.6281410315749, 19.9143909665674, 
15.3407872385057, 10.3303995390774, 8.49283095274311, 5.39813216797301, 
3.49812424840959, 3.14352075545081, 2.31375323843416, 1.75069834043094, 
1.18922152083292), cumulative_variance = c(28.6281410315749, 
48.5425319981423, 63.883319236648, 74.2137187757255, 82.7065497284686, 
88.1046818964416, 91.6028061448512, 94.746326900302, 97.0600801387361, 
98.8107784791671, 100)), row.names = c(NA, -11L), class = "data.frame")

我想创建一个scree plot,这样主y轴的刻度范围是0-30,次y轴的刻度范围是0-100。我的代码现在看起来:

p2 <- ggplot(data = pca, aes(x = X0)) +
  geom_point(aes(y = variance_pct), size = 4, color = "blue") +
  geom_line(aes(y = variance_pct), color = "blue") +
  scale_y_continuous(name = "Variance Explained (%)", breaks = seq(0, 30, 5)) +
  labs(title = "Scree Plot") +
  theme_bw() +
  scale_y_continuous(
    sec.axis = sec_axis(~ . * 100 / 30, name = "Cumulative Variance Explained (%)", breaks = seq(0, 100, 20)),
    limits = c(0, 100)
  ) +
  geom_point(aes(y = cumulative_variance), size = 4, color = "red") +
  geom_line(aes(x = X0, y = cumulative_variance), color = "red") +
  labs(title = "Scree Plot with Cumulative Variance Explained")

p2

和图:x1c 0d1x
我可以将y轴上的值固定为0-30和0-100吗?

fd3cxomn

fd3cxomn1#

通常的误解是,添加辅助轴将随之转换数据。添加辅助轴时,需要记住的关键是 * 它只是一个惰性注解 *。如果您希望红线由该轴表示,则需要通过应用与辅助轴相反的转换来更改数据。此外,limits参数需要引用主轴,而不是次轴,因此应该是c(0, 30)

ggplot(data = pca, aes(x = X0)) +
  geom_point(aes(y = variance_pct, color = "Variance percent"), size = 4) +
  geom_line(aes(y = variance_pct,color = "Variance percent")) +
  scale_y_continuous(name = "Variance Explained (%)", breaks = seq(0, 30, 5)) +
  labs(title = "Scree Plot") +
  theme_bw() +
  scale_y_continuous(
    sec.axis = sec_axis(~ . * 100 / 30, 
                        name = "Cumulative Variance Explained (%)", 
                        breaks = seq(0, 100, 20)),
    limits = c(0, 30)
  ) +
  geom_point(aes(y = 3/10 * cumulative_variance, color = "Cumulative variance"), 
             size = 4) +
  geom_line(aes(y = 3/10 *cumulative_variance, color = "Cumulative variance")) +
  scale_color_brewer(palette = "Set1") +
  labs(title = "Scree Plot with Cumulative Variance Explained")

相关问题