简体   繁体   中英

R: Gaps between specific bars in ggplot

I have this bar graph.

在此处输入图片说明

I generate the graph with this code:

# Speedup Graph
  p <- ggplot(speedup_df, aes(x= benchmark, y = speedup, fill = factor(technique))) +
    geom_bar(stat = "identity", position = "dodge", width = 0.7) +
    scale_fill_discrete(name="Technique", labels=c("No Compression", "Compression Perfect", "Compression BDI", "Precompression BDI Hash",
                                               "Precompression BDI Similarity", "Compression CPack", "Precompression CPack Hash",
                                               "Precompression CPack Similarity", "Compression FPCD", "Precompression FPCD Hash",
                                               "Precompression FPCD Similarity")) +
    labs(title = plot_name, y="Speedup", x="Benchmarks") +
    coord_cartesian(ylim=c(min(speedup_df$speedup), max(speedup_df$speedup))) +
    theme(axis.text.x = element_text(angle=45, size=10, hjust=1)) +
    geom_text(data=speedup_df, aes(label=sprintf("%0.4f", round(speedup, digits = 4)), fontface = "bold"), size = 5, position=position_dodge(width=0.7), 
                               hjust=0.5, vjust=-0.7)

I want to insert gaps between the bars at arbitrary points. For example I want to have a gap before and after all the "BDI" bars. I tried using breaks in scale_fill_discrete but I get the error that they need to be the same number as the labels.

If you provide a reproducible example, I can test it on my side. The idea is to change the width within geom_bar and the width within position_dodge() . You may need to adjust the values in the following example using mtcars data.

library(ggplot2)

# without space
ggplot(mtcars, aes(x= 1, y = mpg, fill = factor(cyl))) +
  geom_bar(stat = "identity", position= "dodge", width = 0.7) 


# add space
ggplot(mtcars, aes(x= 1, y = mpg, fill = factor(cyl))) +
  geom_bar(stat = "identity", position = position_dodge(width=0.9), width = 0.7) 

Created on 2020-01-17 by the reprex package (v0.3.0)

Edit

There may be several ways to insert gap between specific bars. An intuitive way is to use add_row() to a few empty rows and re-set levels :

library(tidyverse)
df <- data.frame(x = c("a", "b", "c", "d", "e"), 
                 y = c(1, 2, 5, 6, 3))

df <- add_row(df, x = c(" ", "  "), y = c(NA))
df$x <- factor(df$x, levels = c("a", " ", "b", "c", "d", "  ", "e")) 

ggplot(df, aes(x= x, y = y, fill = x)) +
    geom_bar(stat = "identity", na.rm = TRUE, 
             position = "dodge", width = 1) +
     scale_fill_manual(values=c("red", "white", "green","blue","maroon", 
                             "white","navy"))

Created on 2020-01-18 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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