Search code examples
rdataframebar-chartaxis-labels

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


I need plot two grouped barcodes with two dataframes that has distinct number of rows: 6, 5.

I tried many codes in R but I don't know how to fix it

Here are my data frames: The Freq colum must be in Y axis and the inter and intra columns must be the x axis.

> 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

I expect to plot the barplots in the same plot and could differ inter e intra values by colour

I want a picture like this one: graph


Solution

  • With the data you posted I don't think you can have this graph to look good. You can't have bars thin enough to differentiate 0.293 and 0.296 when your data ranges from 0 to 0.9.

    Maybe you could try to treat it as a factor just to illustrate what you want to do:

    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

    You can also check the problem by not treating your x variable as a factor:

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

    Either the bars must be very thin (small width), or you'll get overlapping x intervals breaking the plot.

    enter image description here