当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R ggplot2 position_dodge 躲避左右重叠的物体


躲避会在调整水平位置时保留几何图形的垂直位置。 position_dodge() 要求在全局或geom_* 层中指定分组变量。与 position_dodge() 不同,position_dodge2() 在层中无需分组变量即可工作。 position_dodge2() 适用于条形图和矩形,但对于排列宽度可变的箱线图特别有用。

用法

position_dodge(width = NULL, preserve = "total")

position_dodge2(
  width = NULL,
  preserve = "total",
  padding = 0.1,
  reverse = FALSE
)

参数

width

当与单个元素的宽度不同时,躲避宽度。当您想要将狭窄的几何图形与较宽的几何图形对齐时,这非常有用。请参阅示例。

preserve

躲避应该保留某个位置上所有元素的 "total" 宽度,还是 "single" 元素的宽度?

padding

同一位置的元素之间的填充。元素按此比例缩小,以在它们之间留出空间。默认为 0.1。

reverse

如果是 TRUE ,将反转默认的堆叠顺序。如果您要旋转绘图和图例,这非常有用。

也可以看看

例子

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar(position = "dodge2")


# By default, dodging with `position_dodge2()` preserves the total width of
# the elements. You can choose to preserve the width of each element with:
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar(position = position_dodge2(preserve = "single"))


# \donttest{
ggplot(diamonds, aes(price, fill = cut)) +
  geom_histogram(position="dodge2")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# see ?geom_bar for more examples

# In this case a frequency polygon is probably a better choice
ggplot(diamonds, aes(price, colour = cut)) +
  geom_freqpoly()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# }

# Dodging with various widths -------------------------------------
# To dodge items with different widths, you need to be explicit
df <- data.frame(
  x = c("a","a","b","b"),
  y = 2:5,
  g = rep(1:2, 2)
)
p <- ggplot(df, aes(x, y, group = g)) +
  geom_col(position = "dodge", fill = "grey50", colour = "black")
p


# A line range has no width:
p + geom_linerange(aes(ymin = y - 1, ymax = y + 1), position = "dodge")
#> Warning: Width not defined
#> ℹ Set with `position_dodge(width = ...)`


# So you must explicitly specify the width
p + geom_linerange(
  aes(ymin = y - 1, ymax = y + 1),
  position = position_dodge(width = 0.9)
)


# The same principle applies to error bars, which are usually
# narrower than the bars
p + geom_errorbar(
  aes(ymin = y - 1, ymax = y + 1),
  width = 0.2,
  position = "dodge"
)

p + geom_errorbar(
  aes(ymin = y - 1, ymax = y + 1),
  width = 0.2,
  position = position_dodge(width = 0.9)
)


# Box plots use position_dodge2 by default, and bars can use it too
ggplot(mpg, aes(factor(year), displ)) +
  geom_boxplot(aes(colour = hwy < 30))


ggplot(mpg, aes(factor(year), displ)) +
  geom_boxplot(aes(colour = hwy < 30), varwidth = TRUE)


ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar(position = position_dodge2(preserve = "single"))


ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar(position = position_dodge2(preserve = "total"))

相关用法


注:本文由纯净天空筛选整理自Hadley Wickham等大神的英文原创作品 Dodge overlapping objects side-to-side。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。