如何缩放Geom_bar以使其与R ggplot中的重叠线图一致

时间:2019-04-17 15:48:27

标签: r ggplot2

我正在尝试在R中使用ggplot在单个图上用条形图覆盖条形图。我的条形图可以正常工作,但是数据比条形图组件的数据大得多。

如何为该条形图使用额外的刻度,或者执行一些操作使该图在一个图中看起来都很好。

这是我到目前为止的绘图代码:

chart <- data.frame("QuantileName" = 1:5, "AvgLoss" = c(100, 500, 1000, 2500, 3000), "AvgFactor" = c(1.0, 1.1, 1.3, 1.4, 1.5))

Plot <- ggplot(chart, aes(x = 1:5)) +
  scale_x_continuous(name = "Quintile", limits = c(0, 5 + .5), breaks = seq(1, 5)) + 
  geom_line(aes(y = AvgLoss, colour = "AvgLoss")) +
  geom_bar(aes(y = AvgFactor, colour = "AvgFactor" ), stat = "identity") +
  geom_text(aes(y = AvgLoss,  label = round(AvgLoss)), position = position_nudge(x = .3)) +
  geom_point(aes(y = AvgLoss)) +
  ylab("AvgLoss") + 
  scale_colour_manual("",breaks = c("AvgLoss","AvgFactor"), values = c("AvgLoss" = "red", "AvgFactor" = "grey")) +
  ggtitle("Quintile Plot") +
  theme(plot.title = element_text(hjust=0.5))
Plot

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

本质上,将AvgFactor变量乘以数字

+ geom_bar(aes(y = AvgFactor*1000, colour = "AvgFactor" ), stat = "identity")

并设置

+ scale_y_continuous(sec.axis = sec_axis(~ ./1000, name = "AvgFactor"))

所以您的绘图代码应该像

Plot <- ggplot(chart, aes(x = 1:5)) +
  scale_x_continuous(name = "Quintile", limits = c(0, 5 + .5), 
                     breaks = seq(1, 5)) + 
  geom_bar(aes(y = AvgFactor*1000, colour = "AvgFactor" ), 
           stat = "identity") +
  geom_line(aes(y = AvgLoss, colour = "AvgLoss")) +
  geom_text(aes(y = AvgLoss,
                label = round(AvgLoss)), 
                position = position_nudge(x = .3)) +
  geom_point(aes(y = AvgLoss)) +
  ylab("AvgLoss") + 
  scale_colour_manual("",breaks = c("AvgLoss","AvgFactor"), 
                      values = c("AvgLoss" = "red", "AvgFactor" = "grey")) +
  ggtitle("Quintile Plot") +
  theme(plot.title = element_text(hjust=0.5)) +
  scale_y_continuous(sec.axis = sec_axis(~ ./1000, name = "AvgFactor"))

但是,我认为在可能的情况下避免使用辅助轴可能更为优雅。

知道geom_col(...)geom_bar(..., stat = 'identity')的简写可能很有用