我有以下数据框:
df <- structure(list(Source = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L,2L, 1L, 1L, 2L, 2L), .Label = c("Nutrition", "Supplements"), class = "factor"),Gender = c("Female", "Male", "Female", "Male", "Female","Male", "Female", "Male", "Female", "Male", "Female", "Male"), vitamins = c("Carbohydrates", "Carbohydrates", "Carbohydrates","Carbohydrates", "Free sugars", "Free sugars", "Free sugars","Free sugars", "Dietary fibre", "Dietary fibre", "Dietary fibre","Dietary fibre"), percentage = c(103.257255625661, 103.435668737283,12.1783865511905, 10.3397081952058, 26.9383952366656, 14.6831075438958,66.1535947328921, 62.5632737468906, 161.653065420191, 205.648132846479,50.7043993619127, 48.5061463560061)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)
我想创建这个没有小面的图表,只有填充、颜色和线型。我花了两个小时想弄清楚,但我不知道该怎么做。
顺序非常重要。第一个应该是比例最高的一组“维生素”。有没有办法减少组内条形图之间的差距?有没有办法将性别添加为第二个图例,其中男性类别将带有条纹?
非常感谢您的帮助。
我尝试使用下面的代码尽可能接近地重现给定的图表:
library(ggplot2)
ggplot(df) +
aes(x = factor(Gender, levels = c("Male", "Female")),
y = percentage,
fill = factor(Source, levels = c("Supplements", "Nutrition"))) +
geom_col(width = 0.5) +
facet_wrap(~ factor(vitamins, levels = c("Dietary fibre", "Carbohydrates", "Free sugars")),
strip.position = "bottom") +
ylab(NULL) + xlab(NULL) +
scale_fill_manual(name = NULL, values = c(Supplements = "#C0504D", Nutrition = "#4F81BD")) +
scale_y_continuous(limits = c(0, 300), breaks = seq(0, 300, 50), minor_breaks = NULL, expand = expand_scale()) +
theme_minimal() +
theme(strip.placement = "outside", panel.grid.major.x = element_blank())
Run Code Online (Sandbox Code Playgroud)
请注意,它仍然与定位参数和主题修改facet_wrap()一起使用,它告诉 ggplot 将构面标签放置在 x 轴标签下方。strip.position = "bottom"strip.placement = "outside"
另请注意,按照 OP 的要求,每组内的条形图都放置得更近。
theme_minimal()删除大部分常见的装饰,包括刻面面板周围的矩形。另请注意,明确给出因子水平是为了强制数据按预期顺序出现。
df <- structure(list(Source = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L,
2L, 1L, 1L, 2L, 2L), .Label = c("Nutrition", "Supplements"), class = "factor"),
Gender = c("Female", "Male", "Female", "Male", "Female",
"Male", "Female", "Male", "Female", "Male", "Female", "Male"
), vitamins = c("Carbohydrates", "Carbohydrates", "Carbohydrates",
"Carbohydrates", "Free sugars", "Free sugars", "Free sugars",
"Free sugars", "Dietary fibre", "Dietary fibre", "Dietary fibre",
"Dietary fibre"), percentage = c(103.257255625661, 103.435668737283,
12.1783865511905, 10.3397081952058, 26.9383952366656, 14.6831075438958,
66.1535947328921, 62.5632737468906, 161.653065420191, 205.648132846479,
50.7043993619127, 48.5061463560061)), row.names = c(NA, -12L
), class = c("tbl_df", "tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)