如何像这样绘制两个重叠的直方图?
How to plot two overlappling histograms like this?
数据为
y0
y1
M
100
200
F
50
250
如何绘制这样的直方图?注意M和F不会互相阻塞,所以How to plot two histograms together in R中不是这样。提前致谢。
这是一个直接的解决方案:
library(tidyverse)
my_df <- tribble(~ sex, ~ y0, ~ y1,
"M", 100, 200,
"F", 50, 250)
my_df %>%
pivot_longer(starts_with("y")) %>%
ggplot(aes(name, value, fill = sex)) +
geom_col(position = "stack")
如果您的数据如下df
:
library(tidyverse)
df <- tibble::tribble(
~V1, ~y0, ~y1,
"M", 100L, 200L,
"F", 50L, 250L
)
df %>%
pivot_longer(-V1) %>%
ggplot(aes(x = name, y = value, fill = V1)) +
geom_bar(stat = 'identity')
给出:
首先,使用 pivot_longer()
将数据转换为长格式。
library(ggplot2)
library(tidyr)
df_long <- pivot_longer(df, cols = c("y0","y1"))
ggplot(data = df_long) +
geom_col(aes(x = name, y = value, fill = sex)) +
scale_fill_manual(values = c("M" = "blue", "F" = "darkorange")) +
theme(legend.position = "bottom")
数据:
df <- data.frame(sex = c("M","F"),
y0 = c(100,50),
y1 = c(200,250))
数据为
y0 | y1 | |
---|---|---|
M | 100 | 200 |
F | 50 | 250 |
如何绘制这样的直方图?注意M和F不会互相阻塞,所以How to plot two histograms together in R中不是这样。提前致谢。
这是一个直接的解决方案:
library(tidyverse)
my_df <- tribble(~ sex, ~ y0, ~ y1,
"M", 100, 200,
"F", 50, 250)
my_df %>%
pivot_longer(starts_with("y")) %>%
ggplot(aes(name, value, fill = sex)) +
geom_col(position = "stack")
如果您的数据如下df
:
library(tidyverse)
df <- tibble::tribble(
~V1, ~y0, ~y1,
"M", 100L, 200L,
"F", 50L, 250L
)
df %>%
pivot_longer(-V1) %>%
ggplot(aes(x = name, y = value, fill = V1)) +
geom_bar(stat = 'identity')
给出:
首先,使用 pivot_longer()
将数据转换为长格式。
library(ggplot2)
library(tidyr)
df_long <- pivot_longer(df, cols = c("y0","y1"))
ggplot(data = df_long) +
geom_col(aes(x = name, y = value, fill = sex)) +
scale_fill_manual(values = c("M" = "blue", "F" = "darkorange")) +
theme(legend.position = "bottom")
df <- data.frame(sex = c("M","F"),
y0 = c(100,50),
y1 = c(200,250))