使用 ggplot2 在 R 中翻转堆积条形图

问题描述 投票:0回答:1

我们有这个数据框

t = c(0, 1, 2, 3, 4, 5, 6)
x = c("o", "o", "b", "b", "o", "o", "o")
df = data.frame(t, x)

并且希望使用

ggplo2
中的
R
绘制翻转堆叠条形图。

我正在使用此代码

colors <- c("o" = "black", "b" = "white")
df_long <- pivot_longer(df, cols = c("x"), names_to = "variable", values_to = "value")
df_long$value <- factor(df_long$value, levels = c("o", "b"))

定义颜色,以及用于绘图的代码

ggplot(df_long, aes(x = variable, fill = value)) +
  geom_bar(position = position_stack(reverse = FALSE)) +
  scale_fill_manual(values = colors) +
  coord_flip()

现在的问题是

x
栏应该是
black-white-black
,但我得到的是
white-black

有人可以帮忙吗?

r ggplot2 bar-chart
1个回答
0
投票

您不需要旋转数据,它已经是长格式了。
你遇到的问题来自于

geom_bar
会将所有
"o"
和所有
"b"
分组,因此你只有两个条形。
在下面的代码中,我使用
t
作为x坐标,其余的都是自动的。请注意,条形宽度必须完全填满其空间(
width = 1
,而不是默认的 90%)。这比你想象的要简单得多。

library(ggplot2)

t = c(0, 1, 2, 3, 4, 5, 6)
x = c("o", "o", "b", "b", "o", "o", "o")
df = data.frame(t, x)

colors <- c("o" = "black", "b" = "white")

ggplot(df, aes(x = t, fill = x)) +
  geom_bar(position = position_stack(reverse = FALSE), width = 1) +
  scale_fill_manual(values = colors) 

创建于 2024-05-10,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.