使用 ggplot 在线段下方绘制填充(条形图?)
Draw a fill (bar?) beneath line-segments using ggplot
我希望有一个简单的 geom_ 不是 geom_polygon 来做我在这里想做的事情。我想让“填充”在 y 轴上向下延伸到 0,并按分组拆分,类似于线段在我的组 = 美学中被“device_period”拆分的方式。我正在尝试制作看起来类似于条形图但 x、y 数据按示例所示方式分组的东西。
library(tidyverse)
theme_set(theme_bw())
test_df <- tribble(
~x, ~y, ~device, ~period,
2, 3, 1, 1,
3, 4, 1, 1,
4, 4, 1, 1,
6, 4, 1, 2,
7, 2, 1, 2,
8, 0, 1, 2,
4, 3, 2, 1,
5, 2, 2, 1,
6, 2, 2, 2,
7, 1, 2, 2,
8, 1, 2, 2,
)
test_df %>%
mutate(device_period = paste(device, period)) %>%
ggplot(aes(
x = x,
y = y,
shape = as.factor(device),
color = as.factor(device),
group = device_period
)) +
geom_point() + geom_line()
您正在寻找 geom_area
。我添加了 fill
美学并将 factor()
放在 mutate
中以避免输入 3 次。我还将 y 轴设置为从 0 开始。
test_df %>%
mutate(device_period = paste(device, period),
device = factor(device)) %>%
ggplot(aes(
x = x,
y = y,
shape = device,
fill = device,
color = device,
group = device_period
)) +
geom_point() +
geom_area(alpha = 0.4, position = "identity") +
scale_y_continuous(expand = expansion(c(0, 0.05))) +
theme_bw()
我希望有一个简单的 geom_ 不是 geom_polygon 来做我在这里想做的事情。我想让“填充”在 y 轴上向下延伸到 0,并按分组拆分,类似于线段在我的组 = 美学中被“device_period”拆分的方式。我正在尝试制作看起来类似于条形图但 x、y 数据按示例所示方式分组的东西。
library(tidyverse)
theme_set(theme_bw())
test_df <- tribble(
~x, ~y, ~device, ~period,
2, 3, 1, 1,
3, 4, 1, 1,
4, 4, 1, 1,
6, 4, 1, 2,
7, 2, 1, 2,
8, 0, 1, 2,
4, 3, 2, 1,
5, 2, 2, 1,
6, 2, 2, 2,
7, 1, 2, 2,
8, 1, 2, 2,
)
test_df %>%
mutate(device_period = paste(device, period)) %>%
ggplot(aes(
x = x,
y = y,
shape = as.factor(device),
color = as.factor(device),
group = device_period
)) +
geom_point() + geom_line()
您正在寻找 geom_area
。我添加了 fill
美学并将 factor()
放在 mutate
中以避免输入 3 次。我还将 y 轴设置为从 0 开始。
test_df %>%
mutate(device_period = paste(device, period),
device = factor(device)) %>%
ggplot(aes(
x = x,
y = y,
shape = device,
fill = device,
color = device,
group = device_period
)) +
geom_point() +
geom_area(alpha = 0.4, position = "identity") +
scale_y_continuous(expand = expansion(c(0, 0.05))) +
theme_bw()