r - 在 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"
)
谢谢!
解决方案
我不知道 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 创建
推荐阅读
- laravel - Laravel - 如何使用外部 API 的参数搜索并重定向到下一页
- javascript - 无法将文本框值写入 .text 文件
- django - 带有 Q 的 Django 查询集给出了错误的长度
- r - 从ggplot图例中删除关键字母
- debugging - 调试 .net 核心 WebApp 非常慢
- excel - 设置一个用户表单文本框以根据用户表单命令按钮将数据输入活动工作表和范围?
- node.js - Jenkins NodeJS 插件在使用 npm ci 的安装阶段失败
- webpack-5 - 如何将 terser webpack 插件迁移到 webpack v5
- apache-kafka - Spring Integration Message Driven Channel Adapter 不适用于 Spring-Kafka 2.3+
- git - Composer + VCS + 更新到最新提交的版本