首页 > 解决方案 > 如何制作 x 轴包含间隙的条形图

问题描述

我希望我的条形图的 x 轴是一个连续的比例。

这是我的数据:

list(
 Century = c(1, 2, 3, 4, 5), 
 CenturyLabel = c("1st", "Bit later", "", "", "Post-Roman"), 
 Value = c(.2, .3, 0, 0, .4) ) %>% as_tibble()

我希望看到 1 世纪、2 世纪和 5 世纪的酒吧与 3 世纪和 4 世纪的差距。

标签: rggplot2bar-chart

解决方案


诀窍是将您的 x 轴变量定义为factor

library("dplyr")

df <- tibble(
 Century = c(1, 2, 3, 4, 5), 
 CenturyLabel = c("1st", "Bit later", "", "", "Post-Roman"), 
 Value = c(.2, .3, 0, 0, .4) )

df$CenturyFactor <- factor(df$Century, labels = df$CenturyLabel), ordered = TRUE)

然后,您可以将其CenturyFactor用作 x 轴变量,并且您会看到与任何正确的绘图库之间的差距... 需要注意的是,任何重复的标签都会导致世纪合并!

解决此问题的一种方法是绘制Century(1 到 5),但调整标签以显示CenturyLabel. 这将是特定于库的。不需要任何因素。

使用 ggplot2:

library("ggplot2")

ggplot(df, aes(x = Century, y = Value)) +
  geom_col() +
  scale_x_continuous(labels = df$CenturyLabel, breaks = df$Century)

有间隙的绘图


推荐阅读