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

时间:2019-06-05 18:13:11

标签: r dataframe bar-chart axis-labels

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

我在R中尝试了很多代码,但我不知道如何解决

这是我的数据帧:Freq列必须在Y轴上,中间列和内部列必须在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

我希望在同一图中绘制条形图,并且内部颜色之间可能会有所不同

我想要一张这样的照片: graph

2 个答案:

答案 0 :(得分:0)

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

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

enter image description here

答案 1 :(得分:-1)

根据您发布的数据,我认为您无法让此图看起来不错。当您的数据范围从0.2930.296时,栏的厚度不足以区分00.9

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

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

enter image description here

您还可以通过将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个重叠的间隔,从而破坏了情节。

enter image description here