R:共享一个X轴的两个图形(箱形图和条形图)

时间:2018-10-22 12:03:46

标签: r ggplot2

我正在尝试以这样的方式匹配两个图,即两个图在垂直方向上彼此垂直并共享一个x轴

我已经尝试使用@objc func handleTap(sender:UITapGestureRecognizer) { if let label = sender.view as? UILabel { if let QuotesDetail = self.Array_Quote.object(at: (label.tag)) as? NSDictionary { } } } ,但没有成功。我没有设法将命令ggplotbarplot()重写为plot(),以使图形仍然正确显示。 我将不胜感激!

这是第一个情节: image of the single graph

ggplot()

这是第二个情节: image of the second graph

plot(as.factor(DauerK_mcpM$Kulturkategorie), 
     DauerK_mcpM$Electivity, 
     ylim = c(-1,1),  
     ylab="Elektivitätsindex", 
     col = DauerK_mcpM$Farbe, xaxt = "n", 
     main = "Elektivität Männchen mit Dauer")
abline(h = 0, lty = 2) 
x.labels <- gsub("^.*?)","",levels(as.factor(DauerK_mcpM$Kulturkategorie)))
breaks <- seq(1,length(x.labels), 1)
axis(1, labels = x.labels, at = breaks, las = 2, cex.axis = 1)
dev.off()

1 个答案:

答案 0 :(得分:2)

这可以通过在ggplot中添加图表类型的指标列,然后对该指标进行构面来实现:

library(tidyverse)

#create some data
set.seed(20181022)
data <- data.frame(x = letters[ceiling(runif(100, 0, 10))],
                   y = runif(100),
                   stringsAsFactors = FALSE)

#duplicate the data and add an indicator for the Plot Type
data <- data %>% 
  bind_rows(data) %>% 
  mutate(PlotType = rep(1:2, each = nrow(data)))

#Facet by the plot type and subset each geom
data %>% 
  ggplot(aes(x, y)) +
  facet_grid(PlotType~., scales = "free")+
  geom_boxplot(data = filter(data, PlotType == 1)) + 
  geom_bar(data = filter(data, PlotType == 2), stat = "identity")

Faceted by geom