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

问题描述 投票:0回答:1

我有这个条形图。

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中使用中断,但收到错误消息,它们必须与标签相同。

r ggplot2 geom-bar
1个回答
0
投票

[如果您提供可复制的示例,我可以自己进行测试。想法是更改width中的geom_barwidth中的position_dodge()。在以下示例中,您可能需要使用mtcars数据调整值。

library(ggplot2)

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9sRTdCeTBnLnBuZyJ9” alt =“”>


# 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(v0.3.0)在2020-01-17创建

编辑

可能有几种方法可以在特定钢筋之间插入间隙。一种直观的方法是使用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"))

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS81R2dKUWwzLnBuZyJ9” alt =“”>

reprex package(v0.3.0)在2020-01-18创建

© www.soinside.com 2019 - 2024. All rights reserved.