R:ggplot 中特定条形之间的间隙

标签 r ggplot2 geom-bar

我有这个条形图。

enter image description here

我用以下代码生成图表:

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

我想在任意点的条形之间插入间隙。例如,我想在所有“BDI”条之前和之后有一个间隙。我尝试在scale_fill_discrete中使用中断,但收到错误消息,它们需要与标签的数字相同。

最佳答案

如果您提供可重现的示例,我可以在我这边进行测试。这个想法是改变geom_bar中的widthposition_dodge()中的width。您可能需要使用 mtcars 数据调整以下示例中的值。

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) 

reprex package于2020年1月17日创建(v0.3.0)

编辑

可能有多种方法可以在特定条形之间插入间隙。一种直观的方法是使用 add_row() 到一些空行并重新设置 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"))

reprex package于2020年1月18日创建(v0.3.0)

关于R:ggplot 中特定条形之间的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59780254/

相关文章:

c++ - 使用 rcpp/rinside 包时如何将 dll 库包含在 makefile 中

r - 将术语文档矩阵转换为 R 中的节点/边缘列表

r - 在我的 ggplot2 图中添加一个指向 x 轴的箭头

r - 识别 R 中六个变量的所有组合

r - 如何使用 mutate() 从外部列表中生成一系列未出现在给定列中的项目?

r - 在一个图中创建多个圆环图

r - 错误 : ggplot2 doesn't know how to deal with data of class uneval

r - 在 ggplot2 r 中操作 geom_bar 和 coord_polar 的描绘

r - 如何在带有条形图和点图的图中显示图例?

r - geom_bar() : stacked and dodged combined