简体   繁体   中英

ggplot: how to plot a stack bar plot with dodge position

I have a dataset like:

region country urban_rural treatment      potential
----------------------------------------------------
Africa  Kenya     1         chlorine       compatible
Europe  England   2         non_clorine    not compatible
Africa  Kenya     1         other          potential

And I want to make a figure like:

在此处输入图像描述

can anyone help with this?

I hope I understood your question/problem correctly. I made up some more lines of dummy data to get a nicer plots. The graphs can (and probably should) be further polished.

library(dplyr)
library(ggplot2)
library(data.table) # for the dummy data read in from plain text

# reading in some dummy data I made up buy copy and pasting plus minor changes
df <- data.table::fread("region,country,urban_rural,treatment,potential
Africa,Kenya,1,chlorine,compatible
Europe,England,2,non_clorine,not compatible
Africa,Kenya,1,other,potential
Africa,Kenya,1,chlorine,compatible
Africa,Kenya,2,non_clorine,not compatible
Europe,England,1,other,potential
Europe,England,1,other,potential
Europe,England,1,non_clorine,compatible
Africa,Kenya,2,non_clorine,not compatible
Africa,Kenya,1,non_clorine,potential
Africa,Kenya,1,other,potential
Europe,England,1,chlorine,compatible
Africa,Kenya,2,non_clorine,not compatible
Europe,England,1,other,potential
Africa,Kenya,1,other,potential
Africa,Kenya,1,non_clorine,compatible") 


# one plot for Kenya with title and modified X axis label
df %>% 
  # build the counts to display in graph
  dplyr::count(region, country, treatment, potential) %>% 
  # filter Kenya 
  dplyr::filter(country == 'Kenya') %>% 
  # plot
  ggplot2::ggplot(aes(x = treatment, y = n, fill = potential )) +
  ggplot2::geom_bar(stat="identity") +
  # visual enhancement
  ggplot2::ggtitle("Africa") +
  ggplot2::xlab("Kenya")

在此处输入图像描述

# fast way to plot data for all countries
df %>% 
  # build the counts to display in graph
  dplyr::count(region, country, treatment, potential) %>%  
  # plot
  ggplot2::ggplot(aes(x = treatment, y = n, fill = potential )) +
  ggplot2::geom_bar(stat="identity") +
  # build the subplots from country variable
  ggplot2::facet_wrap(~country)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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