简体   繁体   English

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

[英]R: Two graphs (boxplot and barplot) sharing one X-Axis

I am trying to match two graphs in such a way that the two graphs are located vertically above each other sharing one x Axis 我正在尝试以这样的方式匹配两个图,即两个图在垂直方向上位于彼此上方并共享一个x轴

I already tried to use ggplot but didn't succeed. 我已经尝试使用ggplot但没有成功。 I did not manage to rewrite the commands barplot() and plot() to ggplot() in such a way that the graphs still come out right. 我没能改写命令barplot()plot()ggplot()这样的图形仍然出来的权利。 I would be very grateful for any help! 我将不胜感激!

That's the first plot: 那是第一个情节: 单个图的图像

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()

That's the second plot: 那是第二个情节: 第二张图的图像

barplot(Dauer_pro_Kultur_prozentM, 
        beside = TRUE, 
        xaxt = "n", ylab="verbrachte Zeit [%]", 
        main = "Männchen", col = Dauer_pro_KulturW$Farbe)
x.labels <- gsub("^.*?)", "", levels(as.factor(Dauer_pro_KulturW$Kulturkategorie)))
length <- length(x.labels)*1.2
breaks <- seq(from = 0.7, to = length, 1.2)
axis(1, labels = x.labels, at = breaks, las = 2, cex.axis = 1)
dev.off()

This can be done in ggplot by adding an indicator column for the plot type and then faceting by that indicator: 可以通过在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")

由geom组成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM