如何使用ggplot在R中使用2个数字变量创建按1个因子变量分组的堆积条形图? [英] How to create a stacked bar chart with 2 numeric variables in R using ggplot, grouped by 1 factor variable?

查看:81
本文介绍了如何使用ggplot在R中使用2个数字变量创建按1个因子变量分组的堆积条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R还是很陌生,这是我的第一个问题,如果我以一种令人困惑的方式编写它,就深表歉意!

I'm fairly new to R and this is my first question on here so apologies if I write it in a confusing way!

基本上我有一个数据框,其中有4列,分别是月份和站点,这是因子,而有机百分比和无机百分比是数字:

Basically I have a dataframe with 4 columns, month and site which are factors, and organic % and inorganic % which are numeric:

df<-data.frame(month = c("Mar", "Apr", "May", "Jun", "Jul", "Mar", "Apr", "May", "Jun", "Jul"), site = c("Borth", "Borth", "Borth", "Borth", "Borth", "Clarach", "Clarach", "Clarach", "Clarach", "Clarach"), organic = c(10,20,30,40,50), inorganic = c(90,80,70,60,50))

我想在ggplot上制作条形图,该条形图的有机/无机%"为在y轴上,有机和无机百分比在每个条中彼此堆叠在顶部,并且条按位置分组,月"为0.在x轴上(因此每月2条堆叠的条).到目前为止,我所看到的堆叠仅适用于单个变量,而您必须在分组和堆叠之间进行选择...

I would like to make a bar chart on ggplot which has "organic / inorganic %" on the y axis, with organic and inorganic percent stacked ontop of eachother in each bar, and the bars grouped by site, with "month" on the x axis (so 2 stacked bars per month). So far from what I've seen stacked only works with a single variable, and you have to pick between grouped and stacked for position...

我猜图将以图例结尾,该图例包含有机%borth,有机%clarach,无机%borth,无机%clarach.

I'm guessing the graph would end up with a legend that had organic % borth, organic % clarach, inorganic % borth, inorganic % clarach.

我不确定我写的内容是否有意义,但是如果有人可以提供任何帮助,那就太好了!

I'm not sure if what I've written makes sense but if someone could offer any help that would be so great!

推荐答案

这是除上述答案之外的另一种方法,用于考虑如何显示数据.使用 facet_wrap 可以对数据进行分组:

This is another way than the above answer to consider how to present your data. Using facet_wrap allows you to panel your data:

library(tidyverse)

# can also use library(dplyr); library(ggplot2); library(tidyr)

f %>% 
pivot_longer(c("organic", "inorganic")) %>% 
ggplot(aes(x = site, y = value, fill = name)) + 
geom_bar(position = "fill", stat = "identity") + 
facet_grid(~month) +     
scale_y_continuous(labels = scales::percent_format())

这篇关于如何使用ggplot在R中使用2个数字变量创建按1个因子变量分组的堆积条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆