如何在 R 中的同一个图中创建两个具有不同 x 和 y 轴的条形图?

How to create two barplots with different x and y axis in tha same plot in R?

我需要用两个具有不同行数的数据框绘制两个分组的条形码:6、5。

我在 R 中尝试了很多代码,但我不知道如何修复它

这是我的数据框:Freq 列必须在 Y 轴上,inter 和 intra 列必须是 x 轴。

> freqinter
              inter Freq
1 0.293040975264367   17
2 0.296736775990729    2
3 0.297619926364764    4
4 0.587377012109561    1
5 0.595245125315916    4
6 0.597022018595893    2

> freqintra
              intra Freq
1                 0    3
2 0.293040975264367   15
3 0.597022018595893    4
4 0.598809552335782    2
5 0.898227748764939    6

我希望在同一个图中绘制条形图,并且可以通过颜色区分内部值和内部值

我想要一张这样的照片:

根据您发布的数据,我认为您无法使此图表看起来不错。当您的数据范围从 00.9.

时,您不能使用足够细的条来区分 0.2930.296

也许您可以尝试将其视为一个因素来说明您想要做什么:

freqinter <- data.frame(x = c(
0.293040975264367,
0.296736775990729,  
0.297619926364764,
0.587377012109561,   
0.595245125315916,   
0.597022018595893), Freq = c(17,2,4,1,4,2))

freqintra <- data.frame(x = c(
               0 ,
0.293040975264367,
0.597022018595893,
0.598809552335782,
0.898227748764939), Freq = c(3,15,4,2,6))

df <- bind_rows(freqinter, freqintra, .id = "id")

ggplot(df, aes(x = as.factor(x), y = Freq, fill = id)) + 
      geom_bar(stat = "identity", position = position_dodge2(preserve = "single")) +
      theme(axis.text.x = element_text(angle = 90)) + 
      scale_fill_discrete(labels = c("inter", "intra"))

您也可以通过不将 x 变量作为一个因素来检查问题:

ggplot(df, aes(x = x, y = Freq, fill = id)) + 
  geom_bar(stat = "identity", width = 0.05, position = "dodge") +
  theme(axis.text.x = element_text(angle = 90)) + 
  scale_fill_discrete(labels = c("inter", "intra"))

条形必须非常细(小 width),否则会出现重叠的 x 间隔,从而破坏情节。

您可能需要直方图。尽可能使用原始数据。例如:

library(tidyverse)

freqinter <- data.frame(x = c(
  0.293040975264367,
  0.296736775990729,  
  0.297619926364764,
  0.587377012109561,   
  0.595245125315916,   
  0.597022018595893), Freq = c(17,2,4,1,4,2))

freqintra <- data.frame(x = c(
  0 ,
  0.293040975264367,
  0.597022018595893,
  0.598809552335782,
  0.898227748764939), Freq = c(3,15,4,2,6))

df <- bind_rows(freqinter, freqintra, .id = "id") %>% 
  uncount(Freq)

ggplot(df, aes(x, fill = id)) + 
  geom_histogram(binwidth = 0.1, position = 'dodge', col = 1) +
  scale_fill_grey() +
  theme_minimal()