R 中的 100% 百分比条形图
100% percentage barplot in R
我有这样一个数据集:
我想从中创建一个 100% 的条形图...这样就有一个 100% 的状态条和一个 100% 的类型条...像这样:
图片只有1个状态栏,但我希望并排有两个栏,1个状态栏,1个类型栏..
任何帮助将不胜感激,我想在 R 中这样做
尽管提供的信息确实有点匮乏,但您似乎在寻找带有百分比的堆叠条形图。您可以尝试类似的方法:
# Some sample data:
dta <- tibble(id = 1:10,
status = rbernoulli(n = 10, p = 0.3),
type = rbernoulli(n = 10, p = 0.6))
# Transformation and plotting:
dta %>%
pivot_longer(c(status, type), names_to = "variable") %>%
group_by(variable, value) %>%
summarize(percent = n()) %>%
mutate(percent = percent / sum(percent)) %>%
ungroup() %>%
ggplot() +
aes(x = variable, y = percent, fill = value) +
geom_bar(stat = "identity") +
theme_bw()
导致:
这有帮助吗?
简单的基础 R 解决方案:
p1 <- as.matrix(prop.table(table(data$status))) * 100
p2 <- as.matrix(prop.table(table(data$Type))) * 100
op <- par(mfrow=c(1,2), las=1, mar=c(3,4,1,0))
barplot(p1, legend=TRUE, names="status", ylab="Percent")
barplot(p2, legend=TRUE, names="Type")
par(op)
data <- data.frame(id=1:10,
status=c("P","F","F","P","F","P","P","F","P","P"),
Type=c("full","full","full","part","part","full","full","part","part","full"))
data
id status Type
1 1 P full
2 2 F full
3 3 F full
4 4 P part
5 5 F part
6 6 P full
7 7 P full
8 8 F part
9 9 P part
10 10 P full
也许用 ggplot2
data %>%
pivot_longer(-id) %>%
group_by(name, value) %>%
summarise(n=n()) %>%
ggplot(aes(fill=value, y=n, x=name)) +
geom_bar(position="fill", stat="identity") # Needs polishing
我有这样一个数据集:
我想从中创建一个 100% 的条形图...这样就有一个 100% 的状态条和一个 100% 的类型条...像这样:
图片只有1个状态栏,但我希望并排有两个栏,1个状态栏,1个类型栏..
任何帮助将不胜感激,我想在 R 中这样做
尽管提供的信息确实有点匮乏,但您似乎在寻找带有百分比的堆叠条形图。您可以尝试类似的方法:
# Some sample data:
dta <- tibble(id = 1:10,
status = rbernoulli(n = 10, p = 0.3),
type = rbernoulli(n = 10, p = 0.6))
# Transformation and plotting:
dta %>%
pivot_longer(c(status, type), names_to = "variable") %>%
group_by(variable, value) %>%
summarize(percent = n()) %>%
mutate(percent = percent / sum(percent)) %>%
ungroup() %>%
ggplot() +
aes(x = variable, y = percent, fill = value) +
geom_bar(stat = "identity") +
theme_bw()
导致:
这有帮助吗?
简单的基础 R 解决方案:
p1 <- as.matrix(prop.table(table(data$status))) * 100
p2 <- as.matrix(prop.table(table(data$Type))) * 100
op <- par(mfrow=c(1,2), las=1, mar=c(3,4,1,0))
barplot(p1, legend=TRUE, names="status", ylab="Percent")
barplot(p2, legend=TRUE, names="Type")
par(op)
data <- data.frame(id=1:10,
status=c("P","F","F","P","F","P","P","F","P","P"),
Type=c("full","full","full","part","part","full","full","part","part","full"))
data
id status Type
1 1 P full
2 2 F full
3 3 F full
4 4 P part
5 5 F part
6 6 P full
7 7 P full
8 8 F part
9 9 P part
10 10 P full
也许用 ggplot2
data %>%
pivot_longer(-id) %>%
group_by(name, value) %>%
summarise(n=n()) %>%
ggplot(aes(fill=value, y=n, x=name)) +
geom_bar(position="fill", stat="identity") # Needs polishing