繁体   English   中英

R ggplot2 geom_bar 3维无面

[英]R ggplot2 geom_bar with 3 dimensions without facets

我有以下数据框:

 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")) 

我想创建这个没有刻面的图表,只有填充、颜色和线型。 我想弄清楚 2 个小时,但我不知道该怎么做。

通缉图

顺序非常重要。 第一个应该是百分比最高的一组“维生素”。 有没有办法减少组内条形图之间的差距? 有没有办法将性别添加为第二个传说,其中男性类别将带有条纹?

非常感谢您的帮助。

我试图用下面的代码尽可能地重现给定的图表:

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())

在此处输入图片说明

请注意, facet_wrap()仍然与定位参数strip.position = "bottom"和主题修改strip.placement = "outside" ,它告诉 ggplot 将 facet 标签放置在 x 轴标签下方。

另请注意,根据 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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM