英文:
Grouped barplot and percentages on bars
问题
以下是翻译好的部分:
假设有以下数据框:
> 年龄组 医院_A 医院_B 医院_C
> 0_17 12.69 3.6 9.5
> 18_24 2.23 4.5 6.6
> 25_30 22.3 12.4 10.2
有没有办法生成一个条形图,其中 x 轴表示年龄组,y 轴表示百分比,条形应该是按年龄组分组的医院*?类似于这样:,其中代替"Team",我需要年龄组,而条形应该是医院。是否还有一种方法在条形的顶部添加百分比(四舍五入的数字)?在此先行致谢。
英文:
suppose to have the following data.frame
> Age group Hospital_A Hospital_B Hospital_C
> 0_17 12.69 3.6 9.5
> 18_24 2.23 4.5 6.6
> 25_30 22.3 12.4 10.2
Is there a way to generate a barplot where on x-axis age-groups should be represented while on y-axis percentages and bars should be Hospitals* grouped by age groups? Something like this: where instead of Team, I need age groups and bars should be hospitals. Is there also a way to add percentages (rounded numbers) on top of bars? Thank you in advance.
答案1
得分: 1
以下是代码部分的翻译:
library(tidyr)
library(ggplot2)
library(ggsci)
library(ggthemes)
df |>
pivot_longer(-Age_group,
names_prefix = "Hospital_",
names_to = "Hospital") |>
ggplot(aes(x=Age_group, y=value, fill=Hospital)) +
geom_col(position = position_dodge()) +
geom_text(aes(label=value, y=value+1),
position=position_dodge(width=.9)) +
theme_few() +
scale_fill_d3()+
labs(x="Age group", y="Percentage(%)")
请注意,我只提供了代码的翻译,没有包括其他内容。
英文:
Probably like this bar graph.
library(tidyr)
library(ggplot2)
library(ggsci)
library(ggthemes)
df |>
pivot_longer(-Age_group,
names_prefix = "Hospital_",
names_to = "Hospital") |>
ggplot(aes(x=Age_group, y=value, fill=Hospital)) +
geom_col(position = position_dodge()) +
geom_text(aes(label=value, y=value+1),
position=position_dodge(width=.9)) +
theme_few() +
scale_fill_d3()+
labs(x="Age group", y="Percentage(%)")
<!-- -->
<sup>Created on 2023-05-13 with reprex v2.0.2</sup>
答案2
得分: 0
以下是使用rAmCharts4的示例代码的翻译部分:
resp1 <- c(67, 58, 42, 47, 43, 48)
resp2 <- c(33, 42, 58, 53, 57, 52)
question <- c("A","B","C","D","E","F")
dat <- data.frame(question, resp1, resp2)
library(rAmCharts4)
amBarChart(
data = dat,
category = "question",
values = c("resp1", "resp2"),
valueNames = c("Response 1", "Response 2"),
chartTitle = "My grouped bar chart",
theme = "kelly",
valueFormatter = "#p",
tooltip =
"[bold font-style:italic]{valueY.value.formatNumber('#p')}"
)
英文:
Here is an example with rAmCharts4:
resp1 <- c(67, 58, 42, 47, 43, 48)
resp2 <- c(33, 42, 58, 53, 57, 52)
question <- c("A","B","C","D","E","F")
dat <- data.frame(question, resp1, resp2)
library(rAmCharts4)
amBarChart(
data = dat,
category = "question",
values = c("resp1", "resp2"),
valueNames = c("Response 1", "Response 2"),
chartTitle = "My grouped bar chart",
theme = "kelly",
valueFormatter = "#p",
tooltip =
"[bold font-style:italic]{valueY.value.formatNumber('#p')}[/]"
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论