首页 > 解决方案 > 在 ggplot2 条形图中使每个数据点都有自己的标记

问题描述

我正在重新创建一系列图形和图表,用于 R 中 ggplot 中报告的自动化,其中一个是下面的图表。原始图表将每个数据点都作为它自己的标记(我确信有更好的方式来表达这一点,但我现在想不出,抱歉),我很确定我在几年前看到过类似的东西,但是又想不起来了。ggplot 中是否有任何函数/参数可以让我将第一个图表更改为第二个图表。

我当前的图表; 我目前的图表

我想要的输出(请原谅糟糕的油漆尝试); 我想要的输出

示例数据:

df <- data.frame(person = c("staff", "staff", "customer", "staff", "customer", "customer", "customer", "staff", "customer", "staff"),
                 date = c("August", "August", "September", "September", "September", "October", "October", "October", "October", "November"))

示例代码:

    figure1 <-
  df %>%
  ggplot() + 
  geom_bar(
    mapping = aes(
      x = date, 
      fill = person),
    col = "black"
  ) %>%
  scale_x_date(
    date_breaks = "1 month",
    date_labels = "%b"
  )

谢谢!

标签: rggplot2bar-chart

解决方案


我不知道 ggplot2 中有一个开箱即用的函数可以为您执行此操作,但缺点stat_bin()是它汇总了数据,而您必须跳过直方图的汇总步骤。

这是一个辅助函数,可将 bin 分配给您可以使用的观察值geom_col()。我还添加了一个黄色直方图,以显示轮廓是相同的。

library(ggplot2)

binwidth <- 0.1

# Helper function for histogram
assign_bin <- function(x, binwidth = 0.1) {
  cuts <- seq(min(x) - binwidth, 
              max(x) + binwidth, 
              by = binwidth)
  cuts[findInterval(x, cuts)]
}

ggplot(iris) +
  geom_col(
    aes(x = assign_bin(Sepal.Width, binwidth), 
        y = 1,
        fill = Species),
    width = binwidth,
    colour = "black",
    position = "stack"
  ) +
  geom_histogram(
    aes(Sepal.Width),
    binwidth = 0.1,
    fill = NA,
    colour = "yellow"
  )

reprex 包(v1.0.0)于 2021-03-30 创建


推荐阅读