在R中添加第二个y轴

时间:2020-06-19 16:55:46

标签: r ggplot2 charts

我正在设想使用以下数据集来创建将群集的条形图和折线图与以下数据结合在一起的图:

structure(list(X = 1:14, ORIGIN = c("AUS", "AUS", "DAL", "DAL", 
"DFW", "DFW", "IAH", "IAH", "OKC", "OKC", "SAT", "SAT", "SHV", 
"SHV"), DEST = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L), .Label = c("ATL", "SEA"), class = "factor"), 
    flight19.x = c(293L, 93L, 284L, 93L, 558L, 284L, 441L, 175L, 
    171L, 31L, 262L, 31L, 175L, 0L), flight19.y = c(5526L, 5526L, 
    6106L, 6106L, 23808L, 23808L, 15550L, 15550L, 2055L, 2055L, 
    3621L, 3621L, 558L, 558L)), row.names = c(NA, -14L), class = "data.frame")

在Excel中,我正在设想的图表如下所示: enter image description here

我已经尝试使用sec.axis函数来生成第二条轴。但是,结果看起来折线图仍使用第一个y轴而不是第二个轴:

p1 <- ggplot()+
  geom_bar(data = flight19, aes(ORIGIN, flight19.x, fill = DEST),stat = "identity", position = "dodge" )+
  scale_fill_viridis(name = "Destinations", discrete = TRUE)+
  labs(y= "Operation Counts", x = "Airports")


p2 <- p1 + geom_line(data = flight19, aes(as.character(ORIGIN), flight19.y, group = 1))+
  geom_point(data = flight19, aes(as.character(ORIGIN), flight19.y, group = 1))+
  scale_y_continuous(limit = c(0,600),sec.axis = sec_axis(~.*75/10, name = "Total Monthly Operations")) 

该图显示以下警告:

Warning messages:
1: Removed 12 row(s) containing missing values (geom_path). 
2: Removed 12 rows containing missing values (geom_point).

这些代码产生如下图: enter image description here

有人可以教我如何让线图对应第二个轴吗? 提前非常感谢。

1 个答案:

答案 0 :(得分:0)

找到合适的变换因子,这里我只用了50个来获得漂亮的y轴标签

#create x-axis 
flight19$x_axis <- paste0(flight19$ORIGIN,'\n',flight19$DEST)

# The transformation factor
#transf_fact <- max(flight19$flight19.y)/max(flight19$flight19.x)
transf_fact <- 50

ggplot(flight19, aes(x = x_axis)) +
  geom_bar(aes(y = flight19.x),stat = "identity", fill = "blue") +
  geom_line(aes(y = flight19.y/transf_fact,group=1), color = "orange") + 
  scale_y_continuous(name = "Operation Counts",
                     limit = c(0,600),
                     breaks = seq(0,600,100), 
                     sec.axis = sec_axis(~ (.*transf_fact), 
                                         breaks = function(limit)seq(0,limit[2],5000),
                                         labels = scales::dollar_format(prefix = "$",suffix = " k",scale = .001),
                                         name = "Total Monthly Operations")) + 
  xlab("Airports") + 
  theme_bw()

enter image description here